blob: 73256c324465b5da3b07d26cde4bcfbcc87d199f [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*/
drh029b44b2006-01-15 00:13:15 +0000168#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000169# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000170# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
171 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000172#else
173# define SET_THREADID(X)
174# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000175#endif
176
drhbbd42a62004-05-22 17:41:58 +0000177/*
178** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
179** section 6.5.2.2 lines 483 through 490 specify that when a process
180** sets or clears a lock, that operation overrides any prior locks set
181** by the same process. It does not explicitly say so, but this implies
182** that it overrides locks set by the same process using a different
183** file descriptor. Consider this test case:
184**
185** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
186** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
187**
188** Suppose ./file1 and ./file2 are really the same file (because
189** one is a hard or symbolic link to the other) then if you set
190** an exclusive lock on fd1, then try to get an exclusive lock
191** on fd2, it works. I would have expected the second lock to
192** fail since there was already a lock on the file due to fd1.
193** But not so. Since both locks came from the same process, the
194** second overrides the first, even though they were on different
195** file descriptors opened on different file names.
196**
197** Bummer. If you ask me, this is broken. Badly broken. It means
198** that we cannot use POSIX locks to synchronize file access among
199** competing threads of the same process. POSIX locks will work fine
200** to synchronize access for threads in separate processes, but not
201** threads within the same process.
202**
203** To work around the problem, SQLite has to manage file locks internally
204** on its own. Whenever a new database is opened, we have to find the
205** specific inode of the database file (the inode is determined by the
206** st_dev and st_ino fields of the stat structure that fstat() fills in)
207** and check for locks already existing on that inode. When locks are
208** created or removed, we have to look at our own internal record of the
209** locks to see if another thread has previously set a lock on that same
210** inode.
211**
212** The OsFile structure for POSIX is no longer just an integer file
213** descriptor. It is now a structure that holds the integer file
214** descriptor and a pointer to a structure that describes the internal
215** locks on the corresponding inode. There is one locking structure
216** per inode, so if the same inode is opened twice, both OsFile structures
217** point to the same locking structure. The locking structure keeps
218** a reference count (so we will know when to delete it) and a "cnt"
219** field that tells us its internal lock status. cnt==0 means the
220** file is unlocked. cnt==-1 means the file has an exclusive lock.
221** cnt>0 means there are cnt shared locks on the file.
222**
223** Any attempt to lock or unlock a file first checks the locking
224** structure. The fcntl() system call is only invoked to set a
225** POSIX lock if the internal lock structure transitions between
226** a locked and an unlocked state.
227**
228** 2004-Jan-11:
229** More recent discoveries about POSIX advisory locks. (The more
230** I discover, the more I realize the a POSIX advisory locks are
231** an abomination.)
232**
233** If you close a file descriptor that points to a file that has locks,
234** all locks on that file that are owned by the current process are
235** released. To work around this problem, each OsFile structure contains
236** a pointer to an openCnt structure. There is one openCnt structure
237** per open inode, which means that multiple OsFiles can point to a single
238** openCnt. When an attempt is made to close an OsFile, if there are
239** other OsFiles open on the same inode that are holding locks, the call
240** to close() the file descriptor is deferred until all of the locks clear.
241** The openCnt structure keeps a list of file descriptors that need to
242** be closed and that list is walked (and cleared) when the last lock
243** clears.
244**
245** First, under Linux threads, because each thread has a separate
246** process ID, lock operations in one thread do not override locks
247** to the same file in other threads. Linux threads behave like
248** separate processes in this respect. But, if you close a file
249** descriptor in linux threads, all locks are cleared, even locks
250** on other threads and even though the other threads have different
251** process IDs. Linux threads is inconsistent in this respect.
252** (I'm beginning to think that linux threads is an abomination too.)
253** The consequence of this all is that the hash table for the lockInfo
254** structure has to include the process id as part of its key because
255** locks in different threads are treated as distinct. But the
256** openCnt structure should not include the process id in its
257** key because close() clears lock on all threads, not just the current
258** thread. Were it not for this goofiness in linux threads, we could
259** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000260**
261** 2004-Jun-28:
262** On some versions of linux, threads can override each others locks.
263** On others not. Sometimes you can change the behavior on the same
264** system by setting the LD_ASSUME_KERNEL environment variable. The
265** POSIX standard is silent as to which behavior is correct, as far
266** as I can tell, so other versions of unix might show the same
267** inconsistency. There is no little doubt in my mind that posix
268** advisory locks and linux threads are profoundly broken.
269**
270** To work around the inconsistencies, we have to test at runtime
271** whether or not threads can override each others locks. This test
272** is run once, the first time any lock is attempted. A static
273** variable is set to record the results of this test for future
274** use.
drhbbd42a62004-05-22 17:41:58 +0000275*/
276
277/*
278** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000279** to locate a particular lockInfo structure given its inode.
280**
281** If threads cannot override each others locks, then we set the
282** lockKey.tid field to the thread ID. If threads can override
283** each others locks then tid is always set to zero. tid is also
284** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000285*/
286struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000287 dev_t dev; /* Device number */
288 ino_t ino; /* Inode number */
289#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000290 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000291#endif
drhbbd42a62004-05-22 17:41:58 +0000292};
293
294/*
295** An instance of the following structure is allocated for each open
296** inode on each thread with a different process ID. (Threads have
297** different process IDs on linux, but not on most other unixes.)
298**
299** A single inode can have multiple file descriptors, so each OsFile
300** structure contains a pointer to an instance of this object and this
301** object keeps a count of the number of OsFiles pointing to it.
302*/
303struct lockInfo {
304 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000305 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000306 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000307 int nRef; /* Number of pointers to this structure */
308};
309
310/*
311** An instance of the following structure serves as the key used
312** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000313** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000314*/
315struct openKey {
316 dev_t dev; /* Device number */
317 ino_t ino; /* Inode number */
318};
319
320/*
321** An instance of the following structure is allocated for each open
322** inode. This structure keeps track of the number of locks on that
323** inode. If a close is attempted against an inode that is holding
324** locks, the close is deferred until all locks clear by adding the
325** file descriptor to be closed to the pending list.
326*/
327struct openCnt {
328 struct openKey key; /* The lookup key */
329 int nRef; /* Number of pointers to this structure */
330 int nLock; /* Number of outstanding locks */
331 int nPending; /* Number of pending close() operations */
332 int *aPending; /* Malloced space holding fd's awaiting a close() */
333};
334
335/*
336** These hash table maps inodes and process IDs into lockInfo and openCnt
337** structures. Access to these hash tables must be protected by a mutex.
338*/
339static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
340static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
341
drh5fdae772004-06-29 03:29:00 +0000342
343#ifdef SQLITE_UNIX_THREADS
344/*
345** This variable records whether or not threads can override each others
346** locks.
347**
348** 0: No. Threads cannot override each others locks.
349** 1: Yes. Threads can override each others locks.
350** -1: We don't know yet.
351*/
drh029b44b2006-01-15 00:13:15 +0000352#ifdef SQLITE_TEST
353int threadsOverrideEachOthersLocks = -1;
354#else
drh5fdae772004-06-29 03:29:00 +0000355static int threadsOverrideEachOthersLocks = -1;
drh029b44b2006-01-15 00:13:15 +0000356#endif
drh5fdae772004-06-29 03:29:00 +0000357
358/*
359** This structure holds information passed into individual test
360** threads by the testThreadLockingBehavior() routine.
361*/
362struct threadTestData {
363 int fd; /* File to be locked */
364 struct flock lock; /* The locking operation */
365 int result; /* Result of the locking operation */
366};
367
drh2b4b5962005-06-15 17:47:55 +0000368#ifdef SQLITE_LOCK_TRACE
369/*
370** Print out information about all locking operations.
371**
372** This routine is used for troubleshooting locks on multithreaded
373** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
374** command-line option on the compiler. This code is normally
375** turnned off.
376*/
377static int lockTrace(int fd, int op, struct flock *p){
378 char *zOpName, *zType;
379 int s;
380 int savedErrno;
381 if( op==F_GETLK ){
382 zOpName = "GETLK";
383 }else if( op==F_SETLK ){
384 zOpName = "SETLK";
385 }else{
386 s = fcntl(fd, op, p);
387 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
388 return s;
389 }
390 if( p->l_type==F_RDLCK ){
391 zType = "RDLCK";
392 }else if( p->l_type==F_WRLCK ){
393 zType = "WRLCK";
394 }else if( p->l_type==F_UNLCK ){
395 zType = "UNLCK";
396 }else{
397 assert( 0 );
398 }
399 assert( p->l_whence==SEEK_SET );
400 s = fcntl(fd, op, p);
401 savedErrno = errno;
402 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
403 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
404 (int)p->l_pid, s);
405 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
406 struct flock l2;
407 l2 = *p;
408 fcntl(fd, F_GETLK, &l2);
409 if( l2.l_type==F_RDLCK ){
410 zType = "RDLCK";
411 }else if( l2.l_type==F_WRLCK ){
412 zType = "WRLCK";
413 }else if( l2.l_type==F_UNLCK ){
414 zType = "UNLCK";
415 }else{
416 assert( 0 );
417 }
418 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
419 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
420 }
421 errno = savedErrno;
422 return s;
423}
424#define fcntl lockTrace
425#endif /* SQLITE_LOCK_TRACE */
426
drh5fdae772004-06-29 03:29:00 +0000427/*
428** The testThreadLockingBehavior() routine launches two separate
429** threads on this routine. This routine attempts to lock a file
430** descriptor then returns. The success or failure of that attempt
431** allows the testThreadLockingBehavior() procedure to determine
432** whether or not threads can override each others locks.
433*/
434static void *threadLockingTest(void *pArg){
435 struct threadTestData *pData = (struct threadTestData*)pArg;
436 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
437 return pArg;
438}
439
440/*
441** This procedure attempts to determine whether or not threads
442** can override each others locks then sets the
443** threadsOverrideEachOthersLocks variable appropriately.
444*/
445static void testThreadLockingBehavior(fd_orig){
446 int fd;
447 struct threadTestData d[2];
448 pthread_t t[2];
449
450 fd = dup(fd_orig);
451 if( fd<0 ) return;
452 memset(d, 0, sizeof(d));
453 d[0].fd = fd;
454 d[0].lock.l_type = F_RDLCK;
455 d[0].lock.l_len = 1;
456 d[0].lock.l_start = 0;
457 d[0].lock.l_whence = SEEK_SET;
458 d[1] = d[0];
459 d[1].lock.l_type = F_WRLCK;
460 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
461 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
462 pthread_join(t[0], 0);
463 pthread_join(t[1], 0);
464 close(fd);
465 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
466}
467#endif /* SQLITE_UNIX_THREADS */
468
drhbbd42a62004-05-22 17:41:58 +0000469/*
470** Release a lockInfo structure previously allocated by findLockInfo().
471*/
472static void releaseLockInfo(struct lockInfo *pLock){
drh029b44b2006-01-15 00:13:15 +0000473 assert( sqlite3OsInMutex() );
drhbbd42a62004-05-22 17:41:58 +0000474 pLock->nRef--;
475 if( pLock->nRef==0 ){
476 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
477 sqliteFree(pLock);
478 }
479}
480
481/*
482** Release a openCnt structure previously allocated by findLockInfo().
483*/
484static void releaseOpenCnt(struct openCnt *pOpen){
drh029b44b2006-01-15 00:13:15 +0000485 assert( sqlite3OsInMutex() );
drhbbd42a62004-05-22 17:41:58 +0000486 pOpen->nRef--;
487 if( pOpen->nRef==0 ){
488 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000489 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +0000490 sqliteFree(pOpen);
491 }
492}
493
494/*
495** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000496** describes that file descriptor. Create new ones if necessary. The
497** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000498**
499** Return the number of errors.
500*/
drh38f82712004-06-18 17:10:16 +0000501static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000502 int fd, /* The file descriptor used in the key */
503 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000504 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000505){
506 int rc;
507 struct lockKey key1;
508 struct openKey key2;
509 struct stat statbuf;
510 struct lockInfo *pLock;
511 struct openCnt *pOpen;
512 rc = fstat(fd, &statbuf);
513 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000514
drh029b44b2006-01-15 00:13:15 +0000515 assert( sqlite3OsInMutex() );
drhbbd42a62004-05-22 17:41:58 +0000516 memset(&key1, 0, sizeof(key1));
517 key1.dev = statbuf.st_dev;
518 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000519#ifdef SQLITE_UNIX_THREADS
520 if( threadsOverrideEachOthersLocks<0 ){
521 testThreadLockingBehavior(fd);
522 }
523 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
524#endif
drhbbd42a62004-05-22 17:41:58 +0000525 memset(&key2, 0, sizeof(key2));
526 key2.dev = statbuf.st_dev;
527 key2.ino = statbuf.st_ino;
528 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
529 if( pLock==0 ){
530 struct lockInfo *pOld;
531 pLock = sqliteMallocRaw( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000532 if( pLock==0 ){
533 rc = 1;
534 goto exit_findlockinfo;
535 }
drhbbd42a62004-05-22 17:41:58 +0000536 pLock->key = key1;
537 pLock->nRef = 1;
538 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000539 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000540 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
541 if( pOld!=0 ){
542 assert( pOld==pLock );
543 sqliteFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000544 rc = 1;
545 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000546 }
547 }else{
548 pLock->nRef++;
549 }
550 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000551 if( ppOpen!=0 ){
552 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000553 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000554 struct openCnt *pOld;
555 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
556 if( pOpen==0 ){
557 releaseLockInfo(pLock);
558 rc = 1;
559 goto exit_findlockinfo;
560 }
561 pOpen->key = key2;
562 pOpen->nRef = 1;
563 pOpen->nLock = 0;
564 pOpen->nPending = 0;
565 pOpen->aPending = 0;
566 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
567 if( pOld!=0 ){
568 assert( pOld==pOpen );
569 sqliteFree(pOpen);
570 releaseLockInfo(pLock);
571 rc = 1;
572 goto exit_findlockinfo;
573 }
574 }else{
575 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000576 }
drh029b44b2006-01-15 00:13:15 +0000577 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000578 }
danielk1977441b09a2006-01-05 13:48:29 +0000579
580exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000581 return rc;
drhbbd42a62004-05-22 17:41:58 +0000582}
583
drh64b1bea2006-01-15 02:30:57 +0000584#ifdef SQLITE_DEBUG
585/*
586** Helper function for printing out trace information from debugging
587** binaries. This returns the string represetation of the supplied
588** integer lock-type.
589*/
590static const char *locktypeName(int locktype){
591 switch( locktype ){
592 case NO_LOCK: return "NONE";
593 case SHARED_LOCK: return "SHARED";
594 case RESERVED_LOCK: return "RESERVED";
595 case PENDING_LOCK: return "PENDING";
596 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
597 }
598 return "ERROR";
599}
600#endif
601
drhbbd42a62004-05-22 17:41:58 +0000602/*
drh029b44b2006-01-15 00:13:15 +0000603** If we are currently in a different thread than the thread that the
604** unixFile argument belongs to, then transfer ownership of the unixFile
605** over to the current thread.
606**
607** A unixFile is only owned by a thread on systems where one thread is
608** unable to override locks created by a different thread. RedHat9 is
609** an example of such a system.
610**
611** Ownership transfer is only allowed if the unixFile is currently unlocked.
612** If the unixFile is locked and an ownership is wrong, then return
613** SQLITE_MISUSE. Otherwise return SQLITE_OK.
614*/
615#ifdef SQLITE_UNIX_THREADS
616static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000617 int rc;
drh029b44b2006-01-15 00:13:15 +0000618 pthread_t hSelf;
619 if( threadsOverrideEachOthersLocks ){
620 /* Ownership transfers not needed on this system */
621 return SQLITE_OK;
622 }
623 hSelf = pthread_self();
624 if( pthread_equal(pFile->tid, hSelf) ){
625 /* We are still in the same thread */
drh64b1bea2006-01-15 02:30:57 +0000626 TRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000627 return SQLITE_OK;
628 }
629 if( pFile->locktype!=NO_LOCK ){
630 /* We cannot change ownership while we are holding a lock! */
631 return SQLITE_MISUSE;
632 }
drh64b1bea2006-01-15 02:30:57 +0000633 TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
drh029b44b2006-01-15 00:13:15 +0000634 pFile->tid = hSelf;
635 releaseLockInfo(pFile->pLock);
drh64b1bea2006-01-15 02:30:57 +0000636 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
637 TRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
638 locktypeName(pFile->locktype),
639 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
640 return rc;
drh029b44b2006-01-15 00:13:15 +0000641}
642#else
643# define transferOwnership(X) SQLITE_OK
644#endif
645
646/*
drhbbd42a62004-05-22 17:41:58 +0000647** Delete the named file
648*/
drh66560ad2006-01-06 14:32:19 +0000649int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000650 unlink(zFilename);
651 return SQLITE_OK;
652}
653
654/*
655** Return TRUE if the named file exists.
656*/
drh66560ad2006-01-06 14:32:19 +0000657int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000658 return access(zFilename, 0)==0;
659}
660
drh054889e2005-11-30 03:20:31 +0000661/* Forward declaration */
662static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000663
664/*
drhbbd42a62004-05-22 17:41:58 +0000665** Attempt to open a file for both reading and writing. If that
666** fails, try opening it read-only. If the file does not exist,
667** try to create it.
668**
669** On success, a handle for the open file is written to *id
670** and *pReadonly is set to 0 if the file was opened for reading and
671** writing or 1 if the file was opened read-only. The function returns
672** SQLITE_OK.
673**
674** On failure, the function returns SQLITE_CANTOPEN and leaves
675** *id and *pReadonly unchanged.
676*/
drh66560ad2006-01-06 14:32:19 +0000677int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000678 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000679 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000680 int *pReadonly
681){
682 int rc;
drh054889e2005-11-30 03:20:31 +0000683 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000684
drh66560ad2006-01-06 14:32:19 +0000685 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000686 assert( 0==*pId );
687 f.dirfd = -1;
688 SET_THREADID(&f);
689 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000690 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000691 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000692#ifdef EISDIR
693 if( errno==EISDIR ){
694 return SQLITE_CANTOPEN;
695 }
696#endif
drh9cbe6352005-11-29 03:13:21 +0000697 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
698 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000699 return SQLITE_CANTOPEN;
700 }
701 *pReadonly = 1;
702 }else{
703 *pReadonly = 0;
704 }
drh66560ad2006-01-06 14:32:19 +0000705 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000706 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000707 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000708 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000709 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000710 return SQLITE_NOMEM;
711 }
drh9cbe6352005-11-29 03:13:21 +0000712 f.locktype = 0;
713 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000714 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000715}
716
717
718/*
719** Attempt to open a new file for exclusive access by this process.
720** The file will be opened for both reading and writing. To avoid
721** a potential security problem, we do not allow the file to have
722** previously existed. Nor do we allow the file to be a symbolic
723** link.
724**
725** If delFlag is true, then make arrangements to automatically delete
726** the file when it is closed.
727**
728** On success, write the file handle into *id and return SQLITE_OK.
729**
730** On failure, return SQLITE_CANTOPEN.
731*/
drh66560ad2006-01-06 14:32:19 +0000732int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000733 int rc;
drh054889e2005-11-30 03:20:31 +0000734 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000735
drh66560ad2006-01-06 14:32:19 +0000736 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000737 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000738 if( access(zFilename, 0)==0 ){
739 return SQLITE_CANTOPEN;
740 }
drh9cbe6352005-11-29 03:13:21 +0000741 SET_THREADID(&f);
742 f.dirfd = -1;
743 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000744 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
745 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000746 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000747 return SQLITE_CANTOPEN;
748 }
drh66560ad2006-01-06 14:32:19 +0000749 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000750 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000751 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000752 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000753 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000754 unlink(zFilename);
755 return SQLITE_NOMEM;
756 }
drh9cbe6352005-11-29 03:13:21 +0000757 f.locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000758 if( delFlag ){
759 unlink(zFilename);
760 }
drh9cbe6352005-11-29 03:13:21 +0000761 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000762 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000763}
764
765/*
766** Attempt to open a new file for read-only access.
767**
768** On success, write the file handle into *id and return SQLITE_OK.
769**
770** On failure, return SQLITE_CANTOPEN.
771*/
drh66560ad2006-01-06 14:32:19 +0000772int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000773 int rc;
drh054889e2005-11-30 03:20:31 +0000774 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000775
drh66560ad2006-01-06 14:32:19 +0000776 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000777 assert( 0==*pId );
778 SET_THREADID(&f);
779 f.dirfd = -1;
780 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
781 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000782 return SQLITE_CANTOPEN;
783 }
drh66560ad2006-01-06 14:32:19 +0000784 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000785 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000786 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000787 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000788 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000789 return SQLITE_NOMEM;
790 }
drh9cbe6352005-11-29 03:13:21 +0000791 f.locktype = 0;
792 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
danielk1977261919c2005-12-06 12:52:59 +0000793
drh054889e2005-11-30 03:20:31 +0000794 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000795}
796
797/*
798** Attempt to open a file descriptor for the directory that contains a
799** file. This file descriptor can be used to fsync() the directory
800** in order to make sure the creation of a new file is actually written
801** to disk.
802**
803** This routine is only meaningful for Unix. It is a no-op under
804** windows since windows does not support hard links.
805**
drh9cbe6352005-11-29 03:13:21 +0000806** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000807** updated with the new directory file descriptor and SQLITE_OK is
808** returned.
809**
810** On failure, the function returns SQLITE_CANTOPEN and leaves
811** *id unchanged.
812*/
drh9c06c952005-11-26 00:25:00 +0000813static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000814 OsFile *id,
815 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000816){
drh054889e2005-11-30 03:20:31 +0000817 unixFile *pFile = (unixFile*)id;
818 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000819 /* Do not open the directory if the corresponding file is not already
820 ** open. */
821 return SQLITE_CANTOPEN;
822 }
drh054889e2005-11-30 03:20:31 +0000823 SET_THREADID(pFile);
824 assert( pFile->dirfd<0 );
825 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
826 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000827 return SQLITE_CANTOPEN;
828 }
drh054889e2005-11-30 03:20:31 +0000829 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000830 return SQLITE_OK;
831}
832
833/*
drhab3f9fe2004-08-14 17:10:10 +0000834** If the following global variable points to a string which is the
835** name of a directory, then that directory will be used to store
836** temporary files.
837*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000838char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000839
840/*
drhbbd42a62004-05-22 17:41:58 +0000841** Create a temporary file name in zBuf. zBuf must be big enough to
842** hold at least SQLITE_TEMPNAME_SIZE characters.
843*/
drh66560ad2006-01-06 14:32:19 +0000844int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000845 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000846 0,
drhbbd42a62004-05-22 17:41:58 +0000847 "/var/tmp",
848 "/usr/tmp",
849 "/tmp",
850 ".",
851 };
drh57196282004-10-06 15:41:16 +0000852 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000853 "abcdefghijklmnopqrstuvwxyz"
854 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
855 "0123456789";
856 int i, j;
857 struct stat buf;
858 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000859 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000860 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000861 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000862 if( stat(azDirs[i], &buf) ) continue;
863 if( !S_ISDIR(buf.st_mode) ) continue;
864 if( access(azDirs[i], 07) ) continue;
865 zDir = azDirs[i];
866 break;
867 }
868 do{
869 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
870 j = strlen(zBuf);
871 sqlite3Randomness(15, &zBuf[j]);
872 for(i=0; i<15; i++, j++){
873 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
874 }
875 zBuf[j] = 0;
876 }while( access(zBuf,0)==0 );
877 return SQLITE_OK;
878}
879
880/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000881** Check that a given pathname is a directory and is writable
882**
883*/
drh66560ad2006-01-06 14:32:19 +0000884int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000885#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000886 struct stat buf;
887 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000888 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000889 if( stat(zBuf, &buf) ) return 0;
890 if( !S_ISDIR(buf.st_mode) ) return 0;
891 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000892#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000893 return 1;
894}
895
896/*
drhbbd42a62004-05-22 17:41:58 +0000897** Read data from a file into a buffer. Return SQLITE_OK if all
898** bytes were read successfully and SQLITE_IOERR if anything goes
899** wrong.
900*/
drh9c06c952005-11-26 00:25:00 +0000901static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000902 int got;
drh9cbe6352005-11-29 03:13:21 +0000903 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000904 SimulateIOError(SQLITE_IOERR);
905 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000906 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000907 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000908 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
909 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000910 SEEK(0);
911 /* if( got<0 ) got = 0; */
912 if( got==amt ){
913 return SQLITE_OK;
914 }else{
915 return SQLITE_IOERR;
916 }
917}
918
919/*
920** Write data from a buffer into a file. Return SQLITE_OK on success
921** or some other error code on failure.
922*/
drh9c06c952005-11-26 00:25:00 +0000923static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000924 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000925 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000926 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000927 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000928 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000929 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000930 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000931 amt -= wrote;
932 pBuf = &((char*)pBuf)[wrote];
933 }
934 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000935 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
936 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000937 SEEK(0);
938 if( amt>0 ){
939 return SQLITE_FULL;
940 }
941 return SQLITE_OK;
942}
943
944/*
945** Move the read/write pointer in a file.
946*/
drh9c06c952005-11-26 00:25:00 +0000947static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000948 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000949 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000950#ifdef SQLITE_TEST
951 if( offset ) SimulateDiskfullError
952#endif
drh054889e2005-11-30 03:20:31 +0000953 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000954 return SQLITE_OK;
955}
956
drhb851b2c2005-03-10 14:11:12 +0000957#ifdef SQLITE_TEST
958/*
959** Count the number of fullsyncs and normal syncs. This is used to test
960** that syncs and fullsyncs are occuring at the right times.
961*/
962int sqlite3_sync_count = 0;
963int sqlite3_fullsync_count = 0;
964#endif
965
drhf2f23912005-10-05 10:29:36 +0000966/*
967** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
968** Otherwise use fsync() in its place.
969*/
970#ifndef HAVE_FDATASYNC
971# define fdatasync fsync
972#endif
973
drhb851b2c2005-03-10 14:11:12 +0000974
drhbbd42a62004-05-22 17:41:58 +0000975/*
drhdd809b02004-07-17 21:44:57 +0000976** The fsync() system call does not work as advertised on many
977** unix systems. The following procedure is an attempt to make
978** it work better.
drh1398ad32005-01-19 23:24:50 +0000979**
980** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
981** for testing when we want to run through the test suite quickly.
982** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
983** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
984** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000985*/
drheb796a72005-09-08 12:38:41 +0000986static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000987 int rc;
drhb851b2c2005-03-10 14:11:12 +0000988
989 /* Record the number of times that we do a normal fsync() and
990 ** FULLSYNC. This is used during testing to verify that this procedure
991 ** gets called with the correct arguments.
992 */
993#ifdef SQLITE_TEST
994 if( fullSync ) sqlite3_fullsync_count++;
995 sqlite3_sync_count++;
996#endif
997
998 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
999 ** no-op
1000 */
1001#ifdef SQLITE_NO_SYNC
1002 rc = SQLITE_OK;
1003#else
1004
drhdd809b02004-07-17 21:44:57 +00001005#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001006 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001007 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +00001008 }else{
1009 rc = 1;
1010 }
1011 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +00001012 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +00001013
drhc035e6e2005-09-22 15:45:04 +00001014#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +00001015 if( dataOnly ){
1016 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001017 }else{
drheb796a72005-09-08 12:38:41 +00001018 rc = fsync(fd);
1019 }
drhf30cc942005-03-11 17:52:34 +00001020#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +00001021#endif /* defined(SQLITE_NO_SYNC) */
1022
drhdd809b02004-07-17 21:44:57 +00001023 return rc;
1024}
1025
1026/*
drhbbd42a62004-05-22 17:41:58 +00001027** Make sure all writes to a particular file are committed to disk.
1028**
drheb796a72005-09-08 12:38:41 +00001029** If dataOnly==0 then both the file itself and its metadata (file
1030** size, access time, etc) are synced. If dataOnly!=0 then only the
1031** file data is synced.
1032**
drhbbd42a62004-05-22 17:41:58 +00001033** Under Unix, also make sure that the directory entry for the file
1034** has been created by fsync-ing the directory that contains the file.
1035** If we do not do this and we encounter a power failure, the directory
1036** entry for the journal might not exist after we reboot. The next
1037** SQLite to access the file will not know that the journal exists (because
1038** the directory entry for the journal was never created) and the transaction
1039** will not roll back - possibly leading to database corruption.
1040*/
drh9c06c952005-11-26 00:25:00 +00001041static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +00001042 unixFile *pFile = (unixFile*)id;
1043 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +00001044 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001045 TRACE2("SYNC %-3d\n", pFile->h);
1046 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +00001047 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001048 }
drh054889e2005-11-30 03:20:31 +00001049 if( pFile->dirfd>=0 ){
1050 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +00001051#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +00001052 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
danielk19770964b232005-11-25 08:47:57 +00001053 return SQLITE_IOERR;
1054 }
danielk1977d7c03f72005-11-25 10:38:22 +00001055#endif
drh054889e2005-11-30 03:20:31 +00001056 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1057 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001058 }
drha2854222004-06-17 19:04:17 +00001059 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001060}
1061
1062/*
danielk1977962398d2004-06-14 09:35:16 +00001063** Sync the directory zDirname. This is a no-op on operating systems other
1064** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001065**
1066** This is used to make sure the master journal file has truely been deleted
1067** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001068** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001069*/
drh66560ad2006-01-06 14:32:19 +00001070int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001071#ifdef SQLITE_DISABLE_DIRSYNC
1072 return SQLITE_OK;
1073#else
danielk1977962398d2004-06-14 09:35:16 +00001074 int fd;
1075 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001076 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001077 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001078 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001079 if( fd<0 ){
1080 return SQLITE_CANTOPEN;
1081 }
1082 r = fsync(fd);
1083 close(fd);
1084 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001085#endif
danielk1977962398d2004-06-14 09:35:16 +00001086}
1087
1088/*
drhbbd42a62004-05-22 17:41:58 +00001089** Truncate an open file to a specified size
1090*/
drh9c06c952005-11-26 00:25:00 +00001091static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001092 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001093 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001094 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001095}
1096
1097/*
1098** Determine the current size of a file in bytes
1099*/
drh9c06c952005-11-26 00:25:00 +00001100static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001101 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001102 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001103 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001104 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001105 return SQLITE_IOERR;
1106 }
1107 *pSize = buf.st_size;
1108 return SQLITE_OK;
1109}
1110
danielk19779a1d0ab2004-06-01 14:09:28 +00001111/*
danielk197713adf8a2004-06-03 16:08:41 +00001112** This routine checks if there is a RESERVED lock held on the specified
1113** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001114** non-zero. If the file is unlocked or holds only SHARED locks, then
1115** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001116*/
drh9c06c952005-11-26 00:25:00 +00001117static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001118 int r = 0;
drh054889e2005-11-30 03:20:31 +00001119 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001120
drh054889e2005-11-30 03:20:31 +00001121 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001122 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001123
1124 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001125 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001126 r = 1;
1127 }
1128
drh2ac3ee92004-06-07 16:27:46 +00001129 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001130 */
1131 if( !r ){
1132 struct flock lock;
1133 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001134 lock.l_start = RESERVED_BYTE;
1135 lock.l_len = 1;
1136 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001137 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001138 if( lock.l_type!=F_UNLCK ){
1139 r = 1;
1140 }
1141 }
1142
drh66560ad2006-01-06 14:32:19 +00001143 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001144 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001145
1146 return r;
1147}
1148
1149/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001150** Lock the file with the lock specified by parameter locktype - one
1151** of the following:
1152**
drh2ac3ee92004-06-07 16:27:46 +00001153** (1) SHARED_LOCK
1154** (2) RESERVED_LOCK
1155** (3) PENDING_LOCK
1156** (4) EXCLUSIVE_LOCK
1157**
drhb3e04342004-06-08 00:47:47 +00001158** Sometimes when requesting one lock state, additional lock states
1159** are inserted in between. The locking might fail on one of the later
1160** transitions leaving the lock state different from what it started but
1161** still short of its goal. The following chart shows the allowed
1162** transitions and the inserted intermediate states:
1163**
1164** UNLOCKED -> SHARED
1165** SHARED -> RESERVED
1166** SHARED -> (PENDING) -> EXCLUSIVE
1167** RESERVED -> (PENDING) -> EXCLUSIVE
1168** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001169**
drha6abd042004-06-09 17:37:22 +00001170** This routine will only increase a lock. Use the sqlite3OsUnlock()
1171** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001172*/
drh9c06c952005-11-26 00:25:00 +00001173static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001174 /* The following describes the implementation of the various locks and
1175 ** lock transitions in terms of the POSIX advisory shared and exclusive
1176 ** lock primitives (called read-locks and write-locks below, to avoid
1177 ** confusion with SQLite lock names). The algorithms are complicated
1178 ** slightly in order to be compatible with windows systems simultaneously
1179 ** accessing the same database file, in case that is ever required.
1180 **
1181 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1182 ** byte', each single bytes at well known offsets, and the 'shared byte
1183 ** range', a range of 510 bytes at a well known offset.
1184 **
1185 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1186 ** byte'. If this is successful, a random byte from the 'shared byte
1187 ** range' is read-locked and the lock on the 'pending byte' released.
1188 **
danielk197790ba3bd2004-06-25 08:32:25 +00001189 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1190 ** A RESERVED lock is implemented by grabbing a write-lock on the
1191 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001192 **
1193 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001194 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1195 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1196 ** obtained, but existing SHARED locks are allowed to persist. A process
1197 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1198 ** This property is used by the algorithm for rolling back a journal file
1199 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001200 **
danielk197790ba3bd2004-06-25 08:32:25 +00001201 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1202 ** implemented by obtaining a write-lock on the entire 'shared byte
1203 ** range'. Since all other locks require a read-lock on one of the bytes
1204 ** within this range, this ensures that no other locks are held on the
1205 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001206 **
1207 ** The reason a single byte cannot be used instead of the 'shared byte
1208 ** range' is that some versions of windows do not support read-locks. By
1209 ** locking a random byte from a range, concurrent SHARED locks may exist
1210 ** even if the locking primitive used is always a write-lock.
1211 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001212 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001213 unixFile *pFile = (unixFile*)id;
1214 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001215 struct flock lock;
1216 int s;
1217
drh054889e2005-11-30 03:20:31 +00001218 assert( pFile );
1219 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1220 locktypeName(locktype), locktypeName(pFile->locktype),
1221 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001222
1223 /* If there is already a lock of this type or more restrictive on the
1224 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001225 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001226 */
drh054889e2005-11-30 03:20:31 +00001227 if( pFile->locktype>=locktype ){
1228 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1229 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001230 return SQLITE_OK;
1231 }
1232
drhb3e04342004-06-08 00:47:47 +00001233 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001234 */
drh054889e2005-11-30 03:20:31 +00001235 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001236 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001237 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001238
drh054889e2005-11-30 03:20:31 +00001239 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001240 */
drh66560ad2006-01-06 14:32:19 +00001241 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001242
drh029b44b2006-01-15 00:13:15 +00001243 /* Make sure the current thread owns the pFile.
1244 */
1245 rc = transferOwnership(pFile);
1246 if( rc!=SQLITE_OK ){
1247 sqlite3OsLeaveMutex();
1248 return rc;
1249 }
drh64b1bea2006-01-15 02:30:57 +00001250 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001251
danielk19779a1d0ab2004-06-01 14:09:28 +00001252 /* If some thread using this PID has a lock via a different OsFile*
1253 ** handle that precludes the requested lock, return BUSY.
1254 */
drh054889e2005-11-30 03:20:31 +00001255 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001256 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001257 ){
1258 rc = SQLITE_BUSY;
1259 goto end_lock;
1260 }
1261
1262 /* If a SHARED lock is requested, and some thread using this PID already
1263 ** has a SHARED or RESERVED lock, then increment reference counts and
1264 ** return SQLITE_OK.
1265 */
1266 if( locktype==SHARED_LOCK &&
1267 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1268 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001269 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001270 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001271 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001272 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001273 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001274 goto end_lock;
1275 }
1276
danielk197713adf8a2004-06-03 16:08:41 +00001277 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001278
danielk19779a1d0ab2004-06-01 14:09:28 +00001279 lock.l_whence = SEEK_SET;
1280
drh3cde3bb2004-06-12 02:17:14 +00001281 /* A PENDING lock is needed before acquiring a SHARED lock and before
1282 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1283 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001284 */
drh3cde3bb2004-06-12 02:17:14 +00001285 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001286 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001287 ){
danielk1977489468c2004-06-28 08:25:47 +00001288 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001289 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001290 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001291 if( s ){
1292 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1293 goto end_lock;
1294 }
drh3cde3bb2004-06-12 02:17:14 +00001295 }
1296
1297
1298 /* If control gets to this point, then actually go ahead and make
1299 ** operating system calls for the specified lock.
1300 */
1301 if( locktype==SHARED_LOCK ){
1302 assert( pLock->cnt==0 );
1303 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001304
drh2ac3ee92004-06-07 16:27:46 +00001305 /* Now get the read-lock */
1306 lock.l_start = SHARED_FIRST;
1307 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001308 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001309
1310 /* Drop the temporary PENDING lock */
1311 lock.l_start = PENDING_BYTE;
1312 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001313 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001314 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001315 rc = SQLITE_IOERR; /* This should never happen */
1316 goto end_lock;
1317 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001318 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001319 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1320 }else{
drh054889e2005-11-30 03:20:31 +00001321 pFile->locktype = SHARED_LOCK;
1322 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001324 }
drh3cde3bb2004-06-12 02:17:14 +00001325 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1326 /* We are trying for an exclusive lock but another thread in this
1327 ** same process is still holding a shared lock. */
1328 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001329 }else{
drh3cde3bb2004-06-12 02:17:14 +00001330 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001331 ** assumed that there is a SHARED or greater lock on the file
1332 ** already.
1333 */
drh054889e2005-11-30 03:20:31 +00001334 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001335 lock.l_type = F_WRLCK;
1336 switch( locktype ){
1337 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001338 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001339 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001340 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001341 lock.l_start = SHARED_FIRST;
1342 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001343 break;
1344 default:
1345 assert(0);
1346 }
drh054889e2005-11-30 03:20:31 +00001347 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001348 if( s ){
1349 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1350 }
drhbbd42a62004-05-22 17:41:58 +00001351 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001352
danielk1977ecb2a962004-06-02 06:30:16 +00001353 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001354 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001355 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001356 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001357 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001358 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001359 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001360
1361end_lock:
drh66560ad2006-01-06 14:32:19 +00001362 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001363 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001364 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001365 return rc;
1366}
1367
1368/*
drh054889e2005-11-30 03:20:31 +00001369** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001370** must be either NO_LOCK or SHARED_LOCK.
1371**
1372** If the locking level of the file descriptor is already at or below
1373** the requested locking level, this routine is a no-op.
1374**
drh9c105bb2004-10-02 20:38:28 +00001375** It is not possible for this routine to fail if the second argument
1376** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1377** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001378*/
drh9c06c952005-11-26 00:25:00 +00001379static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001380 struct lockInfo *pLock;
1381 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001382 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001383 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001384
drh054889e2005-11-30 03:20:31 +00001385 assert( pFile );
1386 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1387 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001388
1389 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001390 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001391 return SQLITE_OK;
1392 }
drh029b44b2006-01-15 00:13:15 +00001393 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drh66560ad2006-01-06 14:32:19 +00001394 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001395 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001396 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001397 if( pFile->locktype>SHARED_LOCK ){
1398 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001399 if( locktype==SHARED_LOCK ){
1400 lock.l_type = F_RDLCK;
1401 lock.l_whence = SEEK_SET;
1402 lock.l_start = SHARED_FIRST;
1403 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001404 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001405 /* This should never happen */
1406 rc = SQLITE_IOERR;
1407 }
1408 }
drhbbd42a62004-05-22 17:41:58 +00001409 lock.l_type = F_UNLCK;
1410 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001411 lock.l_start = PENDING_BYTE;
1412 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001413 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001414 pLock->locktype = SHARED_LOCK;
1415 }else{
1416 rc = SQLITE_IOERR; /* This should never happen */
1417 }
drhbbd42a62004-05-22 17:41:58 +00001418 }
drha6abd042004-06-09 17:37:22 +00001419 if( locktype==NO_LOCK ){
1420 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001421
drha6abd042004-06-09 17:37:22 +00001422 /* Decrement the shared lock counter. Release the lock using an
1423 ** OS call only when all threads in this same process have released
1424 ** the lock.
1425 */
1426 pLock->cnt--;
1427 if( pLock->cnt==0 ){
1428 lock.l_type = F_UNLCK;
1429 lock.l_whence = SEEK_SET;
1430 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001431 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001432 pLock->locktype = NO_LOCK;
1433 }else{
1434 rc = SQLITE_IOERR; /* This should never happen */
1435 }
drha6abd042004-06-09 17:37:22 +00001436 }
1437
drhbbd42a62004-05-22 17:41:58 +00001438 /* Decrement the count of locks against this same file. When the
1439 ** count reaches zero, close any other file descriptors whose close
1440 ** was deferred because of outstanding locks.
1441 */
drh054889e2005-11-30 03:20:31 +00001442 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001443 pOpen->nLock--;
1444 assert( pOpen->nLock>=0 );
1445 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1446 int i;
1447 for(i=0; i<pOpen->nPending; i++){
1448 close(pOpen->aPending[i]);
1449 }
drh64b1bea2006-01-15 02:30:57 +00001450 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001451 pOpen->nPending = 0;
1452 pOpen->aPending = 0;
1453 }
1454 }
drh66560ad2006-01-06 14:32:19 +00001455 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001456 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001457 return rc;
drhbbd42a62004-05-22 17:41:58 +00001458}
1459
1460/*
danielk1977e3026632004-06-22 11:29:02 +00001461** Close a file.
1462*/
drh9cbe6352005-11-29 03:13:21 +00001463static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001464 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001465 int rc;
1466
drh9cbe6352005-11-29 03:13:21 +00001467 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001468 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001469 if( id->dirfd>=0 ) close(id->dirfd);
1470 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001471 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001472
drh38322302006-01-15 02:43:16 +00001473 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001474 /* If there are outstanding locks, do not actually close the file just
1475 ** yet because that would clear those locks. Instead, add the file
1476 ** descriptor to pOpen->aPending. It will be automatically closed when
1477 ** the last lock is cleared.
1478 */
1479 int *aNew;
1480 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001481 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001482 if( aNew==0 ){
1483 /* If a malloc fails, just leak the file descriptor */
1484 }else{
1485 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001486 pOpen->aPending[pOpen->nPending] = id->h;
1487 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001488 }
1489 }else{
1490 /* There are no outstanding locks so we can close the file immediately */
1491 close(id->h);
1492 }
1493 releaseLockInfo(id->pLock);
1494 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001495
drh66560ad2006-01-06 14:32:19 +00001496 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001497 id->isOpen = 0;
1498 TRACE2("CLOSE %-3d\n", id->h);
1499 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001500 sqliteFree(id);
1501 *pId = 0;
drh38322302006-01-15 02:43:16 +00001502 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001503}
1504
1505/*
drh0ccebe72005-06-07 22:22:50 +00001506** Turn a relative pathname into a full pathname. Return a pointer
1507** to the full pathname stored in space obtained from sqliteMalloc().
1508** The calling function is responsible for freeing this space once it
1509** is no longer needed.
1510*/
drh66560ad2006-01-06 14:32:19 +00001511char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001512 char *zFull = 0;
1513 if( zRelative[0]=='/' ){
1514 sqlite3SetString(&zFull, zRelative, (char*)0);
1515 }else{
drh79158e12005-09-06 21:40:45 +00001516 char *zBuf = sqliteMalloc(5000);
1517 if( zBuf==0 ){
1518 return 0;
1519 }
drh0ccebe72005-06-07 22:22:50 +00001520 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001521 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001522 (char*)0);
drh79158e12005-09-06 21:40:45 +00001523 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001524 }
1525 return zFull;
1526}
1527
drh18839212005-11-26 03:43:23 +00001528/*
drh9cbe6352005-11-29 03:13:21 +00001529** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001530*/
drh9cbe6352005-11-29 03:13:21 +00001531static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001532 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001533}
1534
1535/*
1536** Return the underlying file handle for an OsFile
1537*/
1538static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001539 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001540}
1541
1542/*
1543** Return an integer that indices the type of lock currently held
1544** by this handle. (Used for testing and analysis only.)
1545*/
1546static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001547 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001548}
drh0ccebe72005-06-07 22:22:50 +00001549
drh9c06c952005-11-26 00:25:00 +00001550/*
drh054889e2005-11-30 03:20:31 +00001551** This vector defines all the methods that can operate on an OsFile
1552** for unix.
drh9c06c952005-11-26 00:25:00 +00001553*/
drh054889e2005-11-30 03:20:31 +00001554static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001555 unixClose,
drh054889e2005-11-30 03:20:31 +00001556 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001557 unixRead,
1558 unixWrite,
1559 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001560 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001561 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001562 unixSetFullSync,
1563 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001564 unixFileSize,
1565 unixLock,
1566 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001567 unixLockState,
drh054889e2005-11-30 03:20:31 +00001568 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001569};
1570
drh054889e2005-11-30 03:20:31 +00001571/*
1572** Allocate memory for a unixFile. Initialize the new unixFile
1573** to the value given in pInit and return a pointer to the new
1574** OsFile. If we run out of memory, close the file and return NULL.
1575*/
1576static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1577 unixFile *pNew;
1578 pNew = sqliteMalloc( sizeof(unixFile) );
1579 if( pNew==0 ){
1580 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001581 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001582 releaseLockInfo(pInit->pLock);
1583 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001584 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001585 *pId = 0;
1586 return SQLITE_NOMEM;
1587 }else{
1588 *pNew = *pInit;
1589 pNew->pMethod = &sqlite3UnixIoMethod;
1590 *pId = (OsFile*)pNew;
1591 OpenCounter(+1);
1592 return SQLITE_OK;
1593 }
1594}
1595
drh9c06c952005-11-26 00:25:00 +00001596
drh0ccebe72005-06-07 22:22:50 +00001597#endif /* SQLITE_OMIT_DISKIO */
1598/***************************************************************************
1599** Everything above deals with file I/O. Everything that follows deals
1600** with other miscellanous aspects of the operating system interface
1601****************************************************************************/
1602
1603
1604/*
drhbbd42a62004-05-22 17:41:58 +00001605** Get information to seed the random number generator. The seed
1606** is written into the buffer zBuf[256]. The calling function must
1607** supply a sufficiently large buffer.
1608*/
drh66560ad2006-01-06 14:32:19 +00001609int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001610 /* We have to initialize zBuf to prevent valgrind from reporting
1611 ** errors. The reports issued by valgrind are incorrect - we would
1612 ** prefer that the randomness be increased by making use of the
1613 ** uninitialized space in zBuf - but valgrind errors tend to worry
1614 ** some users. Rather than argue, it seems easier just to initialize
1615 ** the whole array and silence valgrind, even if that means less randomness
1616 ** in the random seed.
1617 **
1618 ** When testing, initializing zBuf[] to zero is all we do. That means
1619 ** that we always use the same random number sequence.* This makes the
1620 ** tests repeatable.
1621 */
1622 memset(zBuf, 0, 256);
1623#if !defined(SQLITE_TEST)
1624 {
drh842b8642005-01-21 17:53:17 +00001625 int pid, fd;
1626 fd = open("/dev/urandom", O_RDONLY);
1627 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001628 time_t t;
1629 time(&t);
1630 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001631 pid = getpid();
1632 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1633 }else{
1634 read(fd, zBuf, 256);
1635 close(fd);
1636 }
drhbbd42a62004-05-22 17:41:58 +00001637 }
1638#endif
1639 return SQLITE_OK;
1640}
1641
1642/*
1643** Sleep for a little while. Return the amount of time slept.
1644*/
drh66560ad2006-01-06 14:32:19 +00001645int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001646#if defined(HAVE_USLEEP) && HAVE_USLEEP
1647 usleep(ms*1000);
1648 return ms;
1649#else
1650 sleep((ms+999)/1000);
1651 return 1000*((ms+999)/1000);
1652#endif
1653}
1654
1655/*
1656** Static variables used for thread synchronization
1657*/
1658static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001659#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001660static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001661#endif
drhbbd42a62004-05-22 17:41:58 +00001662
1663/*
1664** The following pair of routine implement mutual exclusion for
1665** multi-threaded processes. Only a single thread is allowed to
1666** executed code that is surrounded by EnterMutex() and LeaveMutex().
1667**
1668** SQLite uses only a single Mutex. There is not much critical
1669** code and what little there is executes quickly and without blocking.
1670*/
drh66560ad2006-01-06 14:32:19 +00001671void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001672#ifdef SQLITE_UNIX_THREADS
1673 pthread_mutex_lock(&mutex);
1674#endif
1675 assert( !inMutex );
1676 inMutex = 1;
1677}
drh66560ad2006-01-06 14:32:19 +00001678void sqlite3UnixLeaveMutex(){
drhbbd42a62004-05-22 17:41:58 +00001679 assert( inMutex );
1680 inMutex = 0;
1681#ifdef SQLITE_UNIX_THREADS
1682 pthread_mutex_unlock(&mutex);
1683#endif
1684}
1685
1686/*
drh88f474a2006-01-02 20:00:12 +00001687** Return TRUE if we are currently within the mutex and FALSE if not.
drh88f474a2006-01-02 20:00:12 +00001688*/
drh66560ad2006-01-06 14:32:19 +00001689int sqlite3UnixInMutex(){
drh88f474a2006-01-02 20:00:12 +00001690 return inMutex;
1691}
1692
1693/*
drhb4bc7052006-01-11 23:40:33 +00001694** Remember the number of thread-specific-data blocks allocated.
1695** Use this to verify that we are not leaking thread-specific-data.
1696** Ticket #1601
1697*/
1698#ifdef SQLITE_TEST
1699int sqlite3_tsd_count = 0;
1700# ifdef SQLITE_UNIX_THREADS
1701 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1702# define TSD_COUNTER(N) \
1703 pthread_mutex_lock(&tsd_counter_mutex); \
1704 sqlite3_tsd_count += N; \
1705 pthread_mutex_unlock(&tsd_counter_mutex);
1706# else
1707# define TSD_COUNTER(N) sqlite3_tsd_count += N
1708# endif
1709#else
1710# define TSD_COUNTER(N) /* no-op */
1711#endif
1712
1713
1714/*
drh70ff98a2006-01-12 01:25:18 +00001715** If called with allocateFlag>1, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001716** specific data for the current thread. Allocate and zero the
1717** thread-specific data if it does not already exist necessary.
danielk197713a68c32005-12-15 10:11:30 +00001718**
drh6f7adc82006-01-11 21:41:20 +00001719** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001720** specific data. Return it if it exists. If it does not exist,
1721** then return NULL.
1722**
1723** If called with allocateFlag<0, check to see if the thread specific
1724** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001725** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001726** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001727*/
drh6f7adc82006-01-11 21:41:20 +00001728ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
1729 static const ThreadData zeroData;
danielk197713a68c32005-12-15 10:11:30 +00001730#ifdef SQLITE_UNIX_THREADS
1731 static pthread_key_t key;
1732 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001733 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001734
1735 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001736 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001737 if( !keyInit ){
1738 int rc;
drh6f7adc82006-01-11 21:41:20 +00001739 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001740 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001741 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001742 return 0;
1743 }
1744 keyInit = 1;
1745 }
drh66560ad2006-01-06 14:32:19 +00001746 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001747 }
1748
drh3fbb0b12006-01-06 00:36:00 +00001749 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001750 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001751 if( pTsd==0 ){
1752 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1753 if( pTsd ){
1754 *pTsd = zeroData;
1755 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001756 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001757 }
danielk197713a68c32005-12-15 10:11:30 +00001758 }
drh70ff98a2006-01-12 01:25:18 +00001759 }else if( pTsd!=0 && allocateFlag<0
1760 && memcmp(pTsd, &zeroData, sizeof(zeroData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001761 sqlite3OsFree(pTsd);
1762 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001763 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001764 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001765 }
1766 return pTsd;
1767#else
drh6f7adc82006-01-11 21:41:20 +00001768 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001769 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001770 if( pTsd==0 ){
1771 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1772 if( pTsd ){
1773 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001774 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001775 }
drh3fbb0b12006-01-06 00:36:00 +00001776 }
drh70ff98a2006-01-12 01:25:18 +00001777 }else if( pTsd!=0 && allocateFlag<0
1778 && memcmp(pTsd, &zeroData, sizeof(zeroData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001779 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001780 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001781 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001782 }
drh3fbb0b12006-01-06 00:36:00 +00001783 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001784#endif
1785}
1786
1787/*
drhbbd42a62004-05-22 17:41:58 +00001788** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001789** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001790*/
1791#ifdef SQLITE_TEST
1792int sqlite3_current_time = 0;
1793#endif
1794
1795/*
1796** Find the current time (in Universal Coordinated Time). Write the
1797** current time and date as a Julian Day number into *prNow and
1798** return 0. Return 1 if the time and date cannot be found.
1799*/
drh66560ad2006-01-06 14:32:19 +00001800int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001801#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001802 time_t t;
1803 time(&t);
1804 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001805#else
1806 struct timeval sNow;
1807 struct timezone sTz; /* Not used */
1808 gettimeofday(&sNow, &sTz);
1809 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1810#endif
drhbbd42a62004-05-22 17:41:58 +00001811#ifdef SQLITE_TEST
1812 if( sqlite3_current_time ){
1813 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1814 }
1815#endif
1816 return 0;
1817}
1818
drhbbd42a62004-05-22 17:41:58 +00001819#endif /* OS_UNIX */