blob: 1e49657201cd43cd5b12fed009d81ba588102653 [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);
489 sqliteFree(pOpen->aPending);
490 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
584/*
drh029b44b2006-01-15 00:13:15 +0000585** If we are currently in a different thread than the thread that the
586** unixFile argument belongs to, then transfer ownership of the unixFile
587** over to the current thread.
588**
589** A unixFile is only owned by a thread on systems where one thread is
590** unable to override locks created by a different thread. RedHat9 is
591** an example of such a system.
592**
593** Ownership transfer is only allowed if the unixFile is currently unlocked.
594** If the unixFile is locked and an ownership is wrong, then return
595** SQLITE_MISUSE. Otherwise return SQLITE_OK.
596*/
597#ifdef SQLITE_UNIX_THREADS
598static int transferOwnership(unixFile *pFile){
599 pthread_t hSelf;
600 if( threadsOverrideEachOthersLocks ){
601 /* Ownership transfers not needed on this system */
602 return SQLITE_OK;
603 }
604 hSelf = pthread_self();
605 if( pthread_equal(pFile->tid, hSelf) ){
606 /* We are still in the same thread */
607 return SQLITE_OK;
608 }
609 if( pFile->locktype!=NO_LOCK ){
610 /* We cannot change ownership while we are holding a lock! */
611 return SQLITE_MISUSE;
612 }
613 pFile->tid = hSelf;
614 releaseLockInfo(pFile->pLock);
615 return findLockInfo(pFile->h, &pFile->pLock, 0);
616}
617#else
618# define transferOwnership(X) SQLITE_OK
619#endif
620
621/*
drhbbd42a62004-05-22 17:41:58 +0000622** Delete the named file
623*/
drh66560ad2006-01-06 14:32:19 +0000624int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000625 unlink(zFilename);
626 return SQLITE_OK;
627}
628
629/*
630** Return TRUE if the named file exists.
631*/
drh66560ad2006-01-06 14:32:19 +0000632int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000633 return access(zFilename, 0)==0;
634}
635
drh054889e2005-11-30 03:20:31 +0000636/* Forward declaration */
637static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000638
639/*
drhbbd42a62004-05-22 17:41:58 +0000640** Attempt to open a file for both reading and writing. If that
641** fails, try opening it read-only. If the file does not exist,
642** try to create it.
643**
644** On success, a handle for the open file is written to *id
645** and *pReadonly is set to 0 if the file was opened for reading and
646** writing or 1 if the file was opened read-only. The function returns
647** SQLITE_OK.
648**
649** On failure, the function returns SQLITE_CANTOPEN and leaves
650** *id and *pReadonly unchanged.
651*/
drh66560ad2006-01-06 14:32:19 +0000652int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000653 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000654 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000655 int *pReadonly
656){
657 int rc;
drh054889e2005-11-30 03:20:31 +0000658 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000659
drh66560ad2006-01-06 14:32:19 +0000660 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000661 assert( 0==*pId );
662 f.dirfd = -1;
663 SET_THREADID(&f);
664 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000665 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000666 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000667#ifdef EISDIR
668 if( errno==EISDIR ){
669 return SQLITE_CANTOPEN;
670 }
671#endif
drh9cbe6352005-11-29 03:13:21 +0000672 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
673 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000674 return SQLITE_CANTOPEN;
675 }
676 *pReadonly = 1;
677 }else{
678 *pReadonly = 0;
679 }
drh66560ad2006-01-06 14:32:19 +0000680 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000681 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000682 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000683 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000684 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000685 return SQLITE_NOMEM;
686 }
drh9cbe6352005-11-29 03:13:21 +0000687 f.locktype = 0;
688 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000689 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000690}
691
692
693/*
694** Attempt to open a new file for exclusive access by this process.
695** The file will be opened for both reading and writing. To avoid
696** a potential security problem, we do not allow the file to have
697** previously existed. Nor do we allow the file to be a symbolic
698** link.
699**
700** If delFlag is true, then make arrangements to automatically delete
701** the file when it is closed.
702**
703** On success, write the file handle into *id and return SQLITE_OK.
704**
705** On failure, return SQLITE_CANTOPEN.
706*/
drh66560ad2006-01-06 14:32:19 +0000707int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000708 int rc;
drh054889e2005-11-30 03:20:31 +0000709 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000710
drh66560ad2006-01-06 14:32:19 +0000711 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000712 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000713 if( access(zFilename, 0)==0 ){
714 return SQLITE_CANTOPEN;
715 }
drh9cbe6352005-11-29 03:13:21 +0000716 SET_THREADID(&f);
717 f.dirfd = -1;
718 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000719 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
720 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000721 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000722 return SQLITE_CANTOPEN;
723 }
drh66560ad2006-01-06 14:32:19 +0000724 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000725 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000726 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000727 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000728 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000729 unlink(zFilename);
730 return SQLITE_NOMEM;
731 }
drh9cbe6352005-11-29 03:13:21 +0000732 f.locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000733 if( delFlag ){
734 unlink(zFilename);
735 }
drh9cbe6352005-11-29 03:13:21 +0000736 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000737 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000738}
739
740/*
741** Attempt to open a new file for read-only access.
742**
743** On success, write the file handle into *id and return SQLITE_OK.
744**
745** On failure, return SQLITE_CANTOPEN.
746*/
drh66560ad2006-01-06 14:32:19 +0000747int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000748 int rc;
drh054889e2005-11-30 03:20:31 +0000749 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000750
drh66560ad2006-01-06 14:32:19 +0000751 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000752 assert( 0==*pId );
753 SET_THREADID(&f);
754 f.dirfd = -1;
755 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
756 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000757 return SQLITE_CANTOPEN;
758 }
drh66560ad2006-01-06 14:32:19 +0000759 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000760 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000761 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000762 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000763 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000764 return SQLITE_NOMEM;
765 }
drh9cbe6352005-11-29 03:13:21 +0000766 f.locktype = 0;
767 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
danielk1977261919c2005-12-06 12:52:59 +0000768
drh054889e2005-11-30 03:20:31 +0000769 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000770}
771
772/*
773** Attempt to open a file descriptor for the directory that contains a
774** file. This file descriptor can be used to fsync() the directory
775** in order to make sure the creation of a new file is actually written
776** to disk.
777**
778** This routine is only meaningful for Unix. It is a no-op under
779** windows since windows does not support hard links.
780**
drh9cbe6352005-11-29 03:13:21 +0000781** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000782** updated with the new directory file descriptor and SQLITE_OK is
783** returned.
784**
785** On failure, the function returns SQLITE_CANTOPEN and leaves
786** *id unchanged.
787*/
drh9c06c952005-11-26 00:25:00 +0000788static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000789 OsFile *id,
790 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000791){
drh054889e2005-11-30 03:20:31 +0000792 unixFile *pFile = (unixFile*)id;
793 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000794 /* Do not open the directory if the corresponding file is not already
795 ** open. */
796 return SQLITE_CANTOPEN;
797 }
drh054889e2005-11-30 03:20:31 +0000798 SET_THREADID(pFile);
799 assert( pFile->dirfd<0 );
800 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
801 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000802 return SQLITE_CANTOPEN;
803 }
drh054889e2005-11-30 03:20:31 +0000804 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000805 return SQLITE_OK;
806}
807
808/*
drhab3f9fe2004-08-14 17:10:10 +0000809** If the following global variable points to a string which is the
810** name of a directory, then that directory will be used to store
811** temporary files.
812*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000813char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000814
815/*
drhbbd42a62004-05-22 17:41:58 +0000816** Create a temporary file name in zBuf. zBuf must be big enough to
817** hold at least SQLITE_TEMPNAME_SIZE characters.
818*/
drh66560ad2006-01-06 14:32:19 +0000819int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000820 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000821 0,
drhbbd42a62004-05-22 17:41:58 +0000822 "/var/tmp",
823 "/usr/tmp",
824 "/tmp",
825 ".",
826 };
drh57196282004-10-06 15:41:16 +0000827 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000828 "abcdefghijklmnopqrstuvwxyz"
829 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
830 "0123456789";
831 int i, j;
832 struct stat buf;
833 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000834 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000835 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000836 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000837 if( stat(azDirs[i], &buf) ) continue;
838 if( !S_ISDIR(buf.st_mode) ) continue;
839 if( access(azDirs[i], 07) ) continue;
840 zDir = azDirs[i];
841 break;
842 }
843 do{
844 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
845 j = strlen(zBuf);
846 sqlite3Randomness(15, &zBuf[j]);
847 for(i=0; i<15; i++, j++){
848 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
849 }
850 zBuf[j] = 0;
851 }while( access(zBuf,0)==0 );
852 return SQLITE_OK;
853}
854
855/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000856** Check that a given pathname is a directory and is writable
857**
858*/
drh66560ad2006-01-06 14:32:19 +0000859int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000860#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000861 struct stat buf;
862 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000863 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000864 if( stat(zBuf, &buf) ) return 0;
865 if( !S_ISDIR(buf.st_mode) ) return 0;
866 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000867#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000868 return 1;
869}
870
871/*
drhbbd42a62004-05-22 17:41:58 +0000872** Read data from a file into a buffer. Return SQLITE_OK if all
873** bytes were read successfully and SQLITE_IOERR if anything goes
874** wrong.
875*/
drh9c06c952005-11-26 00:25:00 +0000876static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000877 int got;
drh9cbe6352005-11-29 03:13:21 +0000878 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000879 SimulateIOError(SQLITE_IOERR);
880 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000881 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000882 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000883 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
884 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000885 SEEK(0);
886 /* if( got<0 ) got = 0; */
887 if( got==amt ){
888 return SQLITE_OK;
889 }else{
890 return SQLITE_IOERR;
891 }
892}
893
894/*
895** Write data from a buffer into a file. Return SQLITE_OK on success
896** or some other error code on failure.
897*/
drh9c06c952005-11-26 00:25:00 +0000898static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000899 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000900 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000901 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000902 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000903 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000904 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000905 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000906 amt -= wrote;
907 pBuf = &((char*)pBuf)[wrote];
908 }
909 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000910 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
911 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000912 SEEK(0);
913 if( amt>0 ){
914 return SQLITE_FULL;
915 }
916 return SQLITE_OK;
917}
918
919/*
920** Move the read/write pointer in a file.
921*/
drh9c06c952005-11-26 00:25:00 +0000922static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000923 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000924 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000925#ifdef SQLITE_TEST
926 if( offset ) SimulateDiskfullError
927#endif
drh054889e2005-11-30 03:20:31 +0000928 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000929 return SQLITE_OK;
930}
931
drhb851b2c2005-03-10 14:11:12 +0000932#ifdef SQLITE_TEST
933/*
934** Count the number of fullsyncs and normal syncs. This is used to test
935** that syncs and fullsyncs are occuring at the right times.
936*/
937int sqlite3_sync_count = 0;
938int sqlite3_fullsync_count = 0;
939#endif
940
drhf2f23912005-10-05 10:29:36 +0000941/*
942** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
943** Otherwise use fsync() in its place.
944*/
945#ifndef HAVE_FDATASYNC
946# define fdatasync fsync
947#endif
948
drhb851b2c2005-03-10 14:11:12 +0000949
drhbbd42a62004-05-22 17:41:58 +0000950/*
drhdd809b02004-07-17 21:44:57 +0000951** The fsync() system call does not work as advertised on many
952** unix systems. The following procedure is an attempt to make
953** it work better.
drh1398ad32005-01-19 23:24:50 +0000954**
955** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
956** for testing when we want to run through the test suite quickly.
957** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
958** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
959** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000960*/
drheb796a72005-09-08 12:38:41 +0000961static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000962 int rc;
drhb851b2c2005-03-10 14:11:12 +0000963
964 /* Record the number of times that we do a normal fsync() and
965 ** FULLSYNC. This is used during testing to verify that this procedure
966 ** gets called with the correct arguments.
967 */
968#ifdef SQLITE_TEST
969 if( fullSync ) sqlite3_fullsync_count++;
970 sqlite3_sync_count++;
971#endif
972
973 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
974 ** no-op
975 */
976#ifdef SQLITE_NO_SYNC
977 rc = SQLITE_OK;
978#else
979
drhdd809b02004-07-17 21:44:57 +0000980#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000981 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000982 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +0000983 }else{
984 rc = 1;
985 }
986 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +0000987 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +0000988
drhc035e6e2005-09-22 15:45:04 +0000989#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +0000990 if( dataOnly ){
991 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000992 }else{
drheb796a72005-09-08 12:38:41 +0000993 rc = fsync(fd);
994 }
drhf30cc942005-03-11 17:52:34 +0000995#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +0000996#endif /* defined(SQLITE_NO_SYNC) */
997
drhdd809b02004-07-17 21:44:57 +0000998 return rc;
999}
1000
1001/*
drhbbd42a62004-05-22 17:41:58 +00001002** Make sure all writes to a particular file are committed to disk.
1003**
drheb796a72005-09-08 12:38:41 +00001004** If dataOnly==0 then both the file itself and its metadata (file
1005** size, access time, etc) are synced. If dataOnly!=0 then only the
1006** file data is synced.
1007**
drhbbd42a62004-05-22 17:41:58 +00001008** Under Unix, also make sure that the directory entry for the file
1009** has been created by fsync-ing the directory that contains the file.
1010** If we do not do this and we encounter a power failure, the directory
1011** entry for the journal might not exist after we reboot. The next
1012** SQLite to access the file will not know that the journal exists (because
1013** the directory entry for the journal was never created) and the transaction
1014** will not roll back - possibly leading to database corruption.
1015*/
drh9c06c952005-11-26 00:25:00 +00001016static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +00001017 unixFile *pFile = (unixFile*)id;
1018 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +00001019 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001020 TRACE2("SYNC %-3d\n", pFile->h);
1021 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +00001022 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001023 }
drh054889e2005-11-30 03:20:31 +00001024 if( pFile->dirfd>=0 ){
1025 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +00001026#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +00001027 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
danielk19770964b232005-11-25 08:47:57 +00001028 return SQLITE_IOERR;
1029 }
danielk1977d7c03f72005-11-25 10:38:22 +00001030#endif
drh054889e2005-11-30 03:20:31 +00001031 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1032 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001033 }
drha2854222004-06-17 19:04:17 +00001034 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001035}
1036
1037/*
danielk1977962398d2004-06-14 09:35:16 +00001038** Sync the directory zDirname. This is a no-op on operating systems other
1039** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001040**
1041** This is used to make sure the master journal file has truely been deleted
1042** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001043** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001044*/
drh66560ad2006-01-06 14:32:19 +00001045int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001046#ifdef SQLITE_DISABLE_DIRSYNC
1047 return SQLITE_OK;
1048#else
danielk1977962398d2004-06-14 09:35:16 +00001049 int fd;
1050 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001051 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001052 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001053 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001054 if( fd<0 ){
1055 return SQLITE_CANTOPEN;
1056 }
1057 r = fsync(fd);
1058 close(fd);
1059 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001060#endif
danielk1977962398d2004-06-14 09:35:16 +00001061}
1062
1063/*
drhbbd42a62004-05-22 17:41:58 +00001064** Truncate an open file to a specified size
1065*/
drh9c06c952005-11-26 00:25:00 +00001066static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001067 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001068 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001069 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001070}
1071
1072/*
1073** Determine the current size of a file in bytes
1074*/
drh9c06c952005-11-26 00:25:00 +00001075static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001076 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001077 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001078 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001079 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001080 return SQLITE_IOERR;
1081 }
1082 *pSize = buf.st_size;
1083 return SQLITE_OK;
1084}
1085
danielk19779a1d0ab2004-06-01 14:09:28 +00001086/*
danielk197713adf8a2004-06-03 16:08:41 +00001087** This routine checks if there is a RESERVED lock held on the specified
1088** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001089** non-zero. If the file is unlocked or holds only SHARED locks, then
1090** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001091*/
drh9c06c952005-11-26 00:25:00 +00001092static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001093 int r = 0;
drh054889e2005-11-30 03:20:31 +00001094 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001095
drh054889e2005-11-30 03:20:31 +00001096 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001097 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001098
1099 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001100 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001101 r = 1;
1102 }
1103
drh2ac3ee92004-06-07 16:27:46 +00001104 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001105 */
1106 if( !r ){
1107 struct flock lock;
1108 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001109 lock.l_start = RESERVED_BYTE;
1110 lock.l_len = 1;
1111 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001112 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001113 if( lock.l_type!=F_UNLCK ){
1114 r = 1;
1115 }
1116 }
1117
drh66560ad2006-01-06 14:32:19 +00001118 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001119 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001120
1121 return r;
1122}
1123
danielk19772b444852004-06-29 07:45:33 +00001124#ifdef SQLITE_DEBUG
1125/*
1126** Helper function for printing out trace information from debugging
1127** binaries. This returns the string represetation of the supplied
1128** integer lock-type.
1129*/
drh054889e2005-11-30 03:20:31 +00001130static const char *locktypeName(int locktype){
danielk19772b444852004-06-29 07:45:33 +00001131 switch( locktype ){
1132 case NO_LOCK: return "NONE";
1133 case SHARED_LOCK: return "SHARED";
1134 case RESERVED_LOCK: return "RESERVED";
1135 case PENDING_LOCK: return "PENDING";
1136 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
1137 }
1138 return "ERROR";
1139}
1140#endif
1141
danielk197713adf8a2004-06-03 16:08:41 +00001142/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001143** Lock the file with the lock specified by parameter locktype - one
1144** of the following:
1145**
drh2ac3ee92004-06-07 16:27:46 +00001146** (1) SHARED_LOCK
1147** (2) RESERVED_LOCK
1148** (3) PENDING_LOCK
1149** (4) EXCLUSIVE_LOCK
1150**
drhb3e04342004-06-08 00:47:47 +00001151** Sometimes when requesting one lock state, additional lock states
1152** are inserted in between. The locking might fail on one of the later
1153** transitions leaving the lock state different from what it started but
1154** still short of its goal. The following chart shows the allowed
1155** transitions and the inserted intermediate states:
1156**
1157** UNLOCKED -> SHARED
1158** SHARED -> RESERVED
1159** SHARED -> (PENDING) -> EXCLUSIVE
1160** RESERVED -> (PENDING) -> EXCLUSIVE
1161** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001162**
drha6abd042004-06-09 17:37:22 +00001163** This routine will only increase a lock. Use the sqlite3OsUnlock()
1164** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001165*/
drh9c06c952005-11-26 00:25:00 +00001166static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001167 /* The following describes the implementation of the various locks and
1168 ** lock transitions in terms of the POSIX advisory shared and exclusive
1169 ** lock primitives (called read-locks and write-locks below, to avoid
1170 ** confusion with SQLite lock names). The algorithms are complicated
1171 ** slightly in order to be compatible with windows systems simultaneously
1172 ** accessing the same database file, in case that is ever required.
1173 **
1174 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1175 ** byte', each single bytes at well known offsets, and the 'shared byte
1176 ** range', a range of 510 bytes at a well known offset.
1177 **
1178 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1179 ** byte'. If this is successful, a random byte from the 'shared byte
1180 ** range' is read-locked and the lock on the 'pending byte' released.
1181 **
danielk197790ba3bd2004-06-25 08:32:25 +00001182 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1183 ** A RESERVED lock is implemented by grabbing a write-lock on the
1184 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001185 **
1186 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001187 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1188 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1189 ** obtained, but existing SHARED locks are allowed to persist. A process
1190 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1191 ** This property is used by the algorithm for rolling back a journal file
1192 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001193 **
danielk197790ba3bd2004-06-25 08:32:25 +00001194 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1195 ** implemented by obtaining a write-lock on the entire 'shared byte
1196 ** range'. Since all other locks require a read-lock on one of the bytes
1197 ** within this range, this ensures that no other locks are held on the
1198 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001199 **
1200 ** The reason a single byte cannot be used instead of the 'shared byte
1201 ** range' is that some versions of windows do not support read-locks. By
1202 ** locking a random byte from a range, concurrent SHARED locks may exist
1203 ** even if the locking primitive used is always a write-lock.
1204 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001205 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001206 unixFile *pFile = (unixFile*)id;
1207 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001208 struct flock lock;
1209 int s;
1210
drh054889e2005-11-30 03:20:31 +00001211 assert( pFile );
1212 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1213 locktypeName(locktype), locktypeName(pFile->locktype),
1214 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001215
1216 /* If there is already a lock of this type or more restrictive on the
1217 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001218 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001219 */
drh054889e2005-11-30 03:20:31 +00001220 if( pFile->locktype>=locktype ){
1221 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1222 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 return SQLITE_OK;
1224 }
1225
drhb3e04342004-06-08 00:47:47 +00001226 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001227 */
drh054889e2005-11-30 03:20:31 +00001228 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001229 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001230 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001231
drh054889e2005-11-30 03:20:31 +00001232 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001233 */
drh66560ad2006-01-06 14:32:19 +00001234 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001235
drh029b44b2006-01-15 00:13:15 +00001236 /* Make sure the current thread owns the pFile.
1237 */
1238 rc = transferOwnership(pFile);
1239 if( rc!=SQLITE_OK ){
1240 sqlite3OsLeaveMutex();
1241 return rc;
1242 }
1243
danielk19779a1d0ab2004-06-01 14:09:28 +00001244 /* If some thread using this PID has a lock via a different OsFile*
1245 ** handle that precludes the requested lock, return BUSY.
1246 */
drh054889e2005-11-30 03:20:31 +00001247 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001248 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001249 ){
1250 rc = SQLITE_BUSY;
1251 goto end_lock;
1252 }
1253
1254 /* If a SHARED lock is requested, and some thread using this PID already
1255 ** has a SHARED or RESERVED lock, then increment reference counts and
1256 ** return SQLITE_OK.
1257 */
1258 if( locktype==SHARED_LOCK &&
1259 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1260 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001261 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001262 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001263 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001264 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001265 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001266 goto end_lock;
1267 }
1268
danielk197713adf8a2004-06-03 16:08:41 +00001269 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001270
danielk19779a1d0ab2004-06-01 14:09:28 +00001271 lock.l_whence = SEEK_SET;
1272
drh3cde3bb2004-06-12 02:17:14 +00001273 /* A PENDING lock is needed before acquiring a SHARED lock and before
1274 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1275 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001276 */
drh3cde3bb2004-06-12 02:17:14 +00001277 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001278 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001279 ){
danielk1977489468c2004-06-28 08:25:47 +00001280 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001281 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001282 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001283 if( s ){
1284 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1285 goto end_lock;
1286 }
drh3cde3bb2004-06-12 02:17:14 +00001287 }
1288
1289
1290 /* If control gets to this point, then actually go ahead and make
1291 ** operating system calls for the specified lock.
1292 */
1293 if( locktype==SHARED_LOCK ){
1294 assert( pLock->cnt==0 );
1295 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001296
drh2ac3ee92004-06-07 16:27:46 +00001297 /* Now get the read-lock */
1298 lock.l_start = SHARED_FIRST;
1299 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001300 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001301
1302 /* Drop the temporary PENDING lock */
1303 lock.l_start = PENDING_BYTE;
1304 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001305 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001306 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001307 rc = SQLITE_IOERR; /* This should never happen */
1308 goto end_lock;
1309 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001310 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001311 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1312 }else{
drh054889e2005-11-30 03:20:31 +00001313 pFile->locktype = SHARED_LOCK;
1314 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001315 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001316 }
drh3cde3bb2004-06-12 02:17:14 +00001317 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1318 /* We are trying for an exclusive lock but another thread in this
1319 ** same process is still holding a shared lock. */
1320 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001321 }else{
drh3cde3bb2004-06-12 02:17:14 +00001322 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 ** assumed that there is a SHARED or greater lock on the file
1324 ** already.
1325 */
drh054889e2005-11-30 03:20:31 +00001326 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001327 lock.l_type = F_WRLCK;
1328 switch( locktype ){
1329 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001330 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001331 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001332 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001333 lock.l_start = SHARED_FIRST;
1334 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001335 break;
1336 default:
1337 assert(0);
1338 }
drh054889e2005-11-30 03:20:31 +00001339 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001340 if( s ){
1341 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1342 }
drhbbd42a62004-05-22 17:41:58 +00001343 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001344
danielk1977ecb2a962004-06-02 06:30:16 +00001345 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001346 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001347 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001348 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001349 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001350 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001351 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001352
1353end_lock:
drh66560ad2006-01-06 14:32:19 +00001354 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001355 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001356 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001357 return rc;
1358}
1359
1360/*
drh054889e2005-11-30 03:20:31 +00001361** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001362** must be either NO_LOCK or SHARED_LOCK.
1363**
1364** If the locking level of the file descriptor is already at or below
1365** the requested locking level, this routine is a no-op.
1366**
drh9c105bb2004-10-02 20:38:28 +00001367** It is not possible for this routine to fail if the second argument
1368** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1369** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001370*/
drh9c06c952005-11-26 00:25:00 +00001371static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001372 struct lockInfo *pLock;
1373 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001374 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001375 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001376
drh054889e2005-11-30 03:20:31 +00001377 assert( pFile );
1378 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1379 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001380
1381 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001382 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001383 return SQLITE_OK;
1384 }
drh029b44b2006-01-15 00:13:15 +00001385 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drh66560ad2006-01-06 14:32:19 +00001386 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001387 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001388 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001389 if( pFile->locktype>SHARED_LOCK ){
1390 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001391 if( locktype==SHARED_LOCK ){
1392 lock.l_type = F_RDLCK;
1393 lock.l_whence = SEEK_SET;
1394 lock.l_start = SHARED_FIRST;
1395 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001396 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001397 /* This should never happen */
1398 rc = SQLITE_IOERR;
1399 }
1400 }
drhbbd42a62004-05-22 17:41:58 +00001401 lock.l_type = F_UNLCK;
1402 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001403 lock.l_start = PENDING_BYTE;
1404 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001405 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001406 pLock->locktype = SHARED_LOCK;
1407 }else{
1408 rc = SQLITE_IOERR; /* This should never happen */
1409 }
drhbbd42a62004-05-22 17:41:58 +00001410 }
drha6abd042004-06-09 17:37:22 +00001411 if( locktype==NO_LOCK ){
1412 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001413
drha6abd042004-06-09 17:37:22 +00001414 /* Decrement the shared lock counter. Release the lock using an
1415 ** OS call only when all threads in this same process have released
1416 ** the lock.
1417 */
1418 pLock->cnt--;
1419 if( pLock->cnt==0 ){
1420 lock.l_type = F_UNLCK;
1421 lock.l_whence = SEEK_SET;
1422 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001423 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001424 pLock->locktype = NO_LOCK;
1425 }else{
1426 rc = SQLITE_IOERR; /* This should never happen */
1427 }
drha6abd042004-06-09 17:37:22 +00001428 }
1429
drhbbd42a62004-05-22 17:41:58 +00001430 /* Decrement the count of locks against this same file. When the
1431 ** count reaches zero, close any other file descriptors whose close
1432 ** was deferred because of outstanding locks.
1433 */
drh054889e2005-11-30 03:20:31 +00001434 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001435 pOpen->nLock--;
1436 assert( pOpen->nLock>=0 );
1437 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1438 int i;
1439 for(i=0; i<pOpen->nPending; i++){
1440 close(pOpen->aPending[i]);
1441 }
1442 sqliteFree(pOpen->aPending);
1443 pOpen->nPending = 0;
1444 pOpen->aPending = 0;
1445 }
1446 }
drh66560ad2006-01-06 14:32:19 +00001447 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001448 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001449 return rc;
drhbbd42a62004-05-22 17:41:58 +00001450}
1451
1452/*
danielk1977e3026632004-06-22 11:29:02 +00001453** Close a file.
1454*/
drh9cbe6352005-11-29 03:13:21 +00001455static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001456 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001457 int rc;
1458
drh9cbe6352005-11-29 03:13:21 +00001459 if( !id ) return SQLITE_OK;
drh029b44b2006-01-15 00:13:15 +00001460 rc = unixUnlock(*pId, NO_LOCK);
1461 if( rc ) return rc;
danielk1977e3026632004-06-22 11:29:02 +00001462 if( id->dirfd>=0 ) close(id->dirfd);
1463 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001464 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001465
danielk1977e3026632004-06-22 11:29:02 +00001466 if( id->pOpen->nLock ){
1467 /* If there are outstanding locks, do not actually close the file just
1468 ** yet because that would clear those locks. Instead, add the file
1469 ** descriptor to pOpen->aPending. It will be automatically closed when
1470 ** the last lock is cleared.
1471 */
1472 int *aNew;
1473 struct openCnt *pOpen = id->pOpen;
drhad81e872005-08-21 21:45:01 +00001474 aNew = sqliteRealloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001475 if( aNew==0 ){
1476 /* If a malloc fails, just leak the file descriptor */
1477 }else{
1478 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001479 pOpen->aPending[pOpen->nPending] = id->h;
1480 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001481 }
1482 }else{
1483 /* There are no outstanding locks so we can close the file immediately */
1484 close(id->h);
1485 }
1486 releaseLockInfo(id->pLock);
1487 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001488
drh66560ad2006-01-06 14:32:19 +00001489 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001490 id->isOpen = 0;
1491 TRACE2("CLOSE %-3d\n", id->h);
1492 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001493 sqliteFree(id);
1494 *pId = 0;
danielk1977e3026632004-06-22 11:29:02 +00001495 return SQLITE_OK;
1496}
1497
1498/*
drh0ccebe72005-06-07 22:22:50 +00001499** Turn a relative pathname into a full pathname. Return a pointer
1500** to the full pathname stored in space obtained from sqliteMalloc().
1501** The calling function is responsible for freeing this space once it
1502** is no longer needed.
1503*/
drh66560ad2006-01-06 14:32:19 +00001504char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001505 char *zFull = 0;
1506 if( zRelative[0]=='/' ){
1507 sqlite3SetString(&zFull, zRelative, (char*)0);
1508 }else{
drh79158e12005-09-06 21:40:45 +00001509 char *zBuf = sqliteMalloc(5000);
1510 if( zBuf==0 ){
1511 return 0;
1512 }
drh0ccebe72005-06-07 22:22:50 +00001513 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001514 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001515 (char*)0);
drh79158e12005-09-06 21:40:45 +00001516 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001517 }
1518 return zFull;
1519}
1520
drh18839212005-11-26 03:43:23 +00001521/*
drh9cbe6352005-11-29 03:13:21 +00001522** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001523*/
drh9cbe6352005-11-29 03:13:21 +00001524static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001525 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001526}
1527
1528/*
1529** Return the underlying file handle for an OsFile
1530*/
1531static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001532 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001533}
1534
1535/*
1536** Return an integer that indices the type of lock currently held
1537** by this handle. (Used for testing and analysis only.)
1538*/
1539static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001540 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001541}
drh0ccebe72005-06-07 22:22:50 +00001542
drh9c06c952005-11-26 00:25:00 +00001543/*
drh054889e2005-11-30 03:20:31 +00001544** This vector defines all the methods that can operate on an OsFile
1545** for unix.
drh9c06c952005-11-26 00:25:00 +00001546*/
drh054889e2005-11-30 03:20:31 +00001547static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001548 unixClose,
drh054889e2005-11-30 03:20:31 +00001549 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001550 unixRead,
1551 unixWrite,
1552 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001553 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001554 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001555 unixSetFullSync,
1556 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001557 unixFileSize,
1558 unixLock,
1559 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001560 unixLockState,
drh054889e2005-11-30 03:20:31 +00001561 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001562};
1563
drh054889e2005-11-30 03:20:31 +00001564/*
1565** Allocate memory for a unixFile. Initialize the new unixFile
1566** to the value given in pInit and return a pointer to the new
1567** OsFile. If we run out of memory, close the file and return NULL.
1568*/
1569static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1570 unixFile *pNew;
1571 pNew = sqliteMalloc( sizeof(unixFile) );
1572 if( pNew==0 ){
1573 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001574 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001575 releaseLockInfo(pInit->pLock);
1576 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001577 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001578 *pId = 0;
1579 return SQLITE_NOMEM;
1580 }else{
1581 *pNew = *pInit;
1582 pNew->pMethod = &sqlite3UnixIoMethod;
1583 *pId = (OsFile*)pNew;
1584 OpenCounter(+1);
1585 return SQLITE_OK;
1586 }
1587}
1588
drh9c06c952005-11-26 00:25:00 +00001589
drh0ccebe72005-06-07 22:22:50 +00001590#endif /* SQLITE_OMIT_DISKIO */
1591/***************************************************************************
1592** Everything above deals with file I/O. Everything that follows deals
1593** with other miscellanous aspects of the operating system interface
1594****************************************************************************/
1595
1596
1597/*
drhbbd42a62004-05-22 17:41:58 +00001598** Get information to seed the random number generator. The seed
1599** is written into the buffer zBuf[256]. The calling function must
1600** supply a sufficiently large buffer.
1601*/
drh66560ad2006-01-06 14:32:19 +00001602int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001603 /* We have to initialize zBuf to prevent valgrind from reporting
1604 ** errors. The reports issued by valgrind are incorrect - we would
1605 ** prefer that the randomness be increased by making use of the
1606 ** uninitialized space in zBuf - but valgrind errors tend to worry
1607 ** some users. Rather than argue, it seems easier just to initialize
1608 ** the whole array and silence valgrind, even if that means less randomness
1609 ** in the random seed.
1610 **
1611 ** When testing, initializing zBuf[] to zero is all we do. That means
1612 ** that we always use the same random number sequence.* This makes the
1613 ** tests repeatable.
1614 */
1615 memset(zBuf, 0, 256);
1616#if !defined(SQLITE_TEST)
1617 {
drh842b8642005-01-21 17:53:17 +00001618 int pid, fd;
1619 fd = open("/dev/urandom", O_RDONLY);
1620 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001621 time_t t;
1622 time(&t);
1623 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001624 pid = getpid();
1625 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1626 }else{
1627 read(fd, zBuf, 256);
1628 close(fd);
1629 }
drhbbd42a62004-05-22 17:41:58 +00001630 }
1631#endif
1632 return SQLITE_OK;
1633}
1634
1635/*
1636** Sleep for a little while. Return the amount of time slept.
1637*/
drh66560ad2006-01-06 14:32:19 +00001638int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001639#if defined(HAVE_USLEEP) && HAVE_USLEEP
1640 usleep(ms*1000);
1641 return ms;
1642#else
1643 sleep((ms+999)/1000);
1644 return 1000*((ms+999)/1000);
1645#endif
1646}
1647
1648/*
1649** Static variables used for thread synchronization
1650*/
1651static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001652#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001653static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001654#endif
drhbbd42a62004-05-22 17:41:58 +00001655
1656/*
1657** The following pair of routine implement mutual exclusion for
1658** multi-threaded processes. Only a single thread is allowed to
1659** executed code that is surrounded by EnterMutex() and LeaveMutex().
1660**
1661** SQLite uses only a single Mutex. There is not much critical
1662** code and what little there is executes quickly and without blocking.
1663*/
drh66560ad2006-01-06 14:32:19 +00001664void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001665#ifdef SQLITE_UNIX_THREADS
1666 pthread_mutex_lock(&mutex);
1667#endif
1668 assert( !inMutex );
1669 inMutex = 1;
1670}
drh66560ad2006-01-06 14:32:19 +00001671void sqlite3UnixLeaveMutex(){
drhbbd42a62004-05-22 17:41:58 +00001672 assert( inMutex );
1673 inMutex = 0;
1674#ifdef SQLITE_UNIX_THREADS
1675 pthread_mutex_unlock(&mutex);
1676#endif
1677}
1678
1679/*
drh88f474a2006-01-02 20:00:12 +00001680** Return TRUE if we are currently within the mutex and FALSE if not.
drh88f474a2006-01-02 20:00:12 +00001681*/
drh66560ad2006-01-06 14:32:19 +00001682int sqlite3UnixInMutex(){
drh88f474a2006-01-02 20:00:12 +00001683 return inMutex;
1684}
1685
1686/*
drhb4bc7052006-01-11 23:40:33 +00001687** Remember the number of thread-specific-data blocks allocated.
1688** Use this to verify that we are not leaking thread-specific-data.
1689** Ticket #1601
1690*/
1691#ifdef SQLITE_TEST
1692int sqlite3_tsd_count = 0;
1693# ifdef SQLITE_UNIX_THREADS
1694 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1695# define TSD_COUNTER(N) \
1696 pthread_mutex_lock(&tsd_counter_mutex); \
1697 sqlite3_tsd_count += N; \
1698 pthread_mutex_unlock(&tsd_counter_mutex);
1699# else
1700# define TSD_COUNTER(N) sqlite3_tsd_count += N
1701# endif
1702#else
1703# define TSD_COUNTER(N) /* no-op */
1704#endif
1705
1706
1707/*
drh70ff98a2006-01-12 01:25:18 +00001708** If called with allocateFlag>1, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001709** specific data for the current thread. Allocate and zero the
1710** thread-specific data if it does not already exist necessary.
danielk197713a68c32005-12-15 10:11:30 +00001711**
drh6f7adc82006-01-11 21:41:20 +00001712** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001713** specific data. Return it if it exists. If it does not exist,
1714** then return NULL.
1715**
1716** If called with allocateFlag<0, check to see if the thread specific
1717** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001718** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001719** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001720*/
drh6f7adc82006-01-11 21:41:20 +00001721ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
1722 static const ThreadData zeroData;
danielk197713a68c32005-12-15 10:11:30 +00001723#ifdef SQLITE_UNIX_THREADS
1724 static pthread_key_t key;
1725 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001726 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001727
1728 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001729 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001730 if( !keyInit ){
1731 int rc;
drh6f7adc82006-01-11 21:41:20 +00001732 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001733 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001734 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001735 return 0;
1736 }
1737 keyInit = 1;
1738 }
drh66560ad2006-01-06 14:32:19 +00001739 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001740 }
1741
drh3fbb0b12006-01-06 00:36:00 +00001742 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001743 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001744 if( pTsd==0 ){
1745 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1746 if( pTsd ){
1747 *pTsd = zeroData;
1748 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001749 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001750 }
danielk197713a68c32005-12-15 10:11:30 +00001751 }
drh70ff98a2006-01-12 01:25:18 +00001752 }else if( pTsd!=0 && allocateFlag<0
1753 && memcmp(pTsd, &zeroData, sizeof(zeroData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001754 sqlite3OsFree(pTsd);
1755 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001756 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001757 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001758 }
1759 return pTsd;
1760#else
drh6f7adc82006-01-11 21:41:20 +00001761 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001762 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001763 if( pTsd==0 ){
1764 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1765 if( pTsd ){
1766 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001767 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001768 }
drh3fbb0b12006-01-06 00:36:00 +00001769 }
drh70ff98a2006-01-12 01:25:18 +00001770 }else if( pTsd!=0 && allocateFlag<0
1771 && memcmp(pTsd, &zeroData, sizeof(zeroData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001772 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001773 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001774 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001775 }
drh3fbb0b12006-01-06 00:36:00 +00001776 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001777#endif
1778}
1779
1780/*
drhbbd42a62004-05-22 17:41:58 +00001781** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001782** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001783*/
1784#ifdef SQLITE_TEST
1785int sqlite3_current_time = 0;
1786#endif
1787
1788/*
1789** Find the current time (in Universal Coordinated Time). Write the
1790** current time and date as a Julian Day number into *prNow and
1791** return 0. Return 1 if the time and date cannot be found.
1792*/
drh66560ad2006-01-06 14:32:19 +00001793int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001794#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001795 time_t t;
1796 time(&t);
1797 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001798#else
1799 struct timeval sNow;
1800 struct timezone sTz; /* Not used */
1801 gettimeofday(&sNow, &sTz);
1802 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1803#endif
drhbbd42a62004-05-22 17:41:58 +00001804#ifdef SQLITE_TEST
1805 if( sqlite3_current_time ){
1806 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1807 }
1808#endif
1809 return 0;
1810}
1811
drhbbd42a62004-05-22 17:41:58 +00001812#endif /* OS_UNIX */