blob: e9150f1df9052dfe1271ae2dc0d217dee74d2c9f [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#if OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000017
drhbfe66312006-10-03 17:40:40 +000018/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
19
drh9cbe6352005-11-29 03:13:21 +000020/*
21** These #defines should enable >2GB file support on Posix if the
22** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000023** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000024**
25** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
26** on the compiler command line. This is necessary if you are compiling
27** on a recent machine (ex: RedHat 7.2) but you want your code to work
28** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
29** without this option, LFS is enable. But LFS does not exist in the kernel
30** in RedHat 6.0, so the code won't work. Hence, for maximum binary
31** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000032*/
33#ifndef SQLITE_DISABLE_LFS
34# define _LARGE_FILE 1
35# ifndef _FILE_OFFSET_BITS
36# define _FILE_OFFSET_BITS 64
37# endif
38# define _LARGEFILE_SOURCE 1
39#endif
drhbbd42a62004-05-22 17:41:58 +000040
drh9cbe6352005-11-29 03:13:21 +000041/*
42** standard include files.
43*/
44#include <sys/types.h>
45#include <sys/stat.h>
46#include <fcntl.h>
47#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000048#include <time.h>
drh19e2d372005-08-29 23:00:03 +000049#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000050#include <errno.h>
drhbfe66312006-10-03 17:40:40 +000051#ifdef SQLITE_ENABLE_LOCKING_STYLE
52#include <sys/ioctl.h>
53#include <sys/param.h>
54#include <sys/mount.h>
55#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000056
57/*
drhf1a221e2006-01-15 17:27:17 +000058** If we are to be thread-safe, include the pthreads header and define
59** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000060*/
drhd677b3d2007-08-20 22:48:41 +000061#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000062# include <pthread.h>
63# define SQLITE_UNIX_THREADS 1
64#endif
65
66/*
67** Default permissions when creating a new file
68*/
69#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
70# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
71#endif
72
danielk1977b4b47412007-08-17 15:53:36 +000073/*
74** Maximum supported path-length.
75*/
76#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +000077
78
79/*
danielk1977ad94b582007-08-20 06:44:22 +000080** The unixFile structure is subclass of sqlite3_file specific for the unix
drh054889e2005-11-30 03:20:31 +000081** protability layer.
drh9cbe6352005-11-29 03:13:21 +000082*/
drh054889e2005-11-30 03:20:31 +000083typedef struct unixFile unixFile;
84struct unixFile {
danielk197762079062007-08-15 17:08:46 +000085 sqlite3_io_methods const *pMethod; /* Always the first entry */
danielk1977967a4a12007-08-20 14:23:44 +000086#ifdef SQLITE_TEST
87 /* In test mode, increase the size of this structure a bit so that
88 ** it is larger than the struct CrashFile defined in test6.c.
89 */
90 char aPadding[32];
91#endif
drh9cbe6352005-11-29 03:13:21 +000092 struct openCnt *pOpen; /* Info about all open fd's on this inode */
93 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +000094#ifdef SQLITE_ENABLE_LOCKING_STYLE
95 void *lockingContext; /* Locking style specific state */
96#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000097 int h; /* The file descriptor */
98 unsigned char locktype; /* The type of lock held on this fd */
99 unsigned char isOpen; /* True if needs to be closed */
drh9cbe6352005-11-29 03:13:21 +0000100 int dirfd; /* File descriptor for the directory */
drhd677b3d2007-08-20 22:48:41 +0000101#if SQLITE_THREADSAFE
danielk1977ad94b582007-08-20 06:44:22 +0000102 pthread_t tid; /* The thread that "owns" this unixFile */
drh9cbe6352005-11-29 03:13:21 +0000103#endif
104};
105
drh0ccebe72005-06-07 22:22:50 +0000106/*
drh198bf392006-01-06 21:52:49 +0000107** Include code that is common to all os_*.c files
108*/
109#include "os_common.h"
110
111/*
drh0ccebe72005-06-07 22:22:50 +0000112** Define various macros that are missing from some systems.
113*/
drhbbd42a62004-05-22 17:41:58 +0000114#ifndef O_LARGEFILE
115# define O_LARGEFILE 0
116#endif
117#ifdef SQLITE_DISABLE_LFS
118# undef O_LARGEFILE
119# define O_LARGEFILE 0
120#endif
121#ifndef O_NOFOLLOW
122# define O_NOFOLLOW 0
123#endif
124#ifndef O_BINARY
125# define O_BINARY 0
126#endif
127
128/*
129** The DJGPP compiler environment looks mostly like Unix, but it
130** lacks the fcntl() system call. So redefine fcntl() to be something
131** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000132** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000133*/
134#ifdef __DJGPP__
135# define fcntl(A,B,C) 0
136#endif
137
138/*
drh2b4b5962005-06-15 17:47:55 +0000139** The threadid macro resolves to the thread-id or to 0. Used for
140** testing and debugging only.
141*/
drhd677b3d2007-08-20 22:48:41 +0000142#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000143#define threadid pthread_self()
144#else
145#define threadid 0
146#endif
147
148/*
danielk1977ad94b582007-08-20 06:44:22 +0000149** Set or check the unixFile.tid field. This field is set when an unixFile
150** is first opened. All subsequent uses of the unixFile verify that the
151** same thread is operating on the unixFile. Some operating systems do
drh2b4b5962005-06-15 17:47:55 +0000152** not allow locks to be overridden by other threads and that restriction
153** means that sqlite3* database handles cannot be moved from one thread
154** to another. This logic makes sure a user does not try to do that
155** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000156**
danielk1977ad94b582007-08-20 06:44:22 +0000157** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
drhf1a221e2006-01-15 17:27:17 +0000158** another as long as we are running on a system that supports threads
159** overriding each others locks (which now the most common behavior)
danielk1977ad94b582007-08-20 06:44:22 +0000160** or if no locks are held. But the unixFile.pLock field needs to be
drhf1a221e2006-01-15 17:27:17 +0000161** recomputed because its key includes the thread-id. See the
162** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000163*/
drhd677b3d2007-08-20 22:48:41 +0000164#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000165# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000166# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
167 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000168#else
169# define SET_THREADID(X)
170# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000171#endif
172
drhbbd42a62004-05-22 17:41:58 +0000173/*
174** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
175** section 6.5.2.2 lines 483 through 490 specify that when a process
176** sets or clears a lock, that operation overrides any prior locks set
177** by the same process. It does not explicitly say so, but this implies
178** that it overrides locks set by the same process using a different
179** file descriptor. Consider this test case:
180**
181** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
182** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
183**
184** Suppose ./file1 and ./file2 are really the same file (because
185** one is a hard or symbolic link to the other) then if you set
186** an exclusive lock on fd1, then try to get an exclusive lock
187** on fd2, it works. I would have expected the second lock to
188** fail since there was already a lock on the file due to fd1.
189** But not so. Since both locks came from the same process, the
190** second overrides the first, even though they were on different
191** file descriptors opened on different file names.
192**
193** Bummer. If you ask me, this is broken. Badly broken. It means
194** that we cannot use POSIX locks to synchronize file access among
195** competing threads of the same process. POSIX locks will work fine
196** to synchronize access for threads in separate processes, but not
197** threads within the same process.
198**
199** To work around the problem, SQLite has to manage file locks internally
200** on its own. Whenever a new database is opened, we have to find the
201** specific inode of the database file (the inode is determined by the
202** st_dev and st_ino fields of the stat structure that fstat() fills in)
203** and check for locks already existing on that inode. When locks are
204** created or removed, we have to look at our own internal record of the
205** locks to see if another thread has previously set a lock on that same
206** inode.
207**
danielk1977ad94b582007-08-20 06:44:22 +0000208** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000209** descriptor. It is now a structure that holds the integer file
210** descriptor and a pointer to a structure that describes the internal
211** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000212** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000213** point to the same locking structure. The locking structure keeps
214** a reference count (so we will know when to delete it) and a "cnt"
215** field that tells us its internal lock status. cnt==0 means the
216** file is unlocked. cnt==-1 means the file has an exclusive lock.
217** cnt>0 means there are cnt shared locks on the file.
218**
219** Any attempt to lock or unlock a file first checks the locking
220** structure. The fcntl() system call is only invoked to set a
221** POSIX lock if the internal lock structure transitions between
222** a locked and an unlocked state.
223**
224** 2004-Jan-11:
225** More recent discoveries about POSIX advisory locks. (The more
226** I discover, the more I realize the a POSIX advisory locks are
227** an abomination.)
228**
229** If you close a file descriptor that points to a file that has locks,
230** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000231** released. To work around this problem, each unixFile structure contains
drhbbd42a62004-05-22 17:41:58 +0000232** a pointer to an openCnt structure. There is one openCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000233** per open inode, which means that multiple unixFile can point to a single
234** openCnt. When an attempt is made to close an unixFile, if there are
235** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000236** to close() the file descriptor is deferred until all of the locks clear.
237** The openCnt structure keeps a list of file descriptors that need to
238** be closed and that list is walked (and cleared) when the last lock
239** clears.
240**
241** First, under Linux threads, because each thread has a separate
242** process ID, lock operations in one thread do not override locks
243** to the same file in other threads. Linux threads behave like
244** separate processes in this respect. But, if you close a file
245** descriptor in linux threads, all locks are cleared, even locks
246** on other threads and even though the other threads have different
247** process IDs. Linux threads is inconsistent in this respect.
248** (I'm beginning to think that linux threads is an abomination too.)
249** The consequence of this all is that the hash table for the lockInfo
250** structure has to include the process id as part of its key because
251** locks in different threads are treated as distinct. But the
252** openCnt structure should not include the process id in its
253** key because close() clears lock on all threads, not just the current
254** thread. Were it not for this goofiness in linux threads, we could
255** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000256**
257** 2004-Jun-28:
258** On some versions of linux, threads can override each others locks.
259** On others not. Sometimes you can change the behavior on the same
260** system by setting the LD_ASSUME_KERNEL environment variable. The
261** POSIX standard is silent as to which behavior is correct, as far
262** as I can tell, so other versions of unix might show the same
263** inconsistency. There is no little doubt in my mind that posix
264** advisory locks and linux threads are profoundly broken.
265**
266** To work around the inconsistencies, we have to test at runtime
267** whether or not threads can override each others locks. This test
268** is run once, the first time any lock is attempted. A static
269** variable is set to record the results of this test for future
270** use.
drhbbd42a62004-05-22 17:41:58 +0000271*/
272
273/*
274** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000275** to locate a particular lockInfo structure given its inode.
276**
277** If threads cannot override each others locks, then we set the
278** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000279** each others locks then tid is always set to zero. tid is omitted
280** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000281*/
282struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000283 dev_t dev; /* Device number */
284 ino_t ino; /* Inode number */
drhd677b3d2007-08-20 22:48:41 +0000285#if SQLITE_THREADSAFE
drhd9cb6ac2005-10-20 07:28:17 +0000286 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000287#endif
drhbbd42a62004-05-22 17:41:58 +0000288};
289
290/*
291** An instance of the following structure is allocated for each open
292** inode on each thread with a different process ID. (Threads have
293** different process IDs on linux, but not on most other unixes.)
294**
danielk1977ad94b582007-08-20 06:44:22 +0000295** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000296** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000297** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000298*/
299struct lockInfo {
300 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000301 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000302 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000303 int nRef; /* Number of pointers to this structure */
304};
305
306/*
307** An instance of the following structure serves as the key used
308** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000309** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000310*/
311struct openKey {
312 dev_t dev; /* Device number */
313 ino_t ino; /* Inode number */
314};
315
316/*
317** An instance of the following structure is allocated for each open
318** inode. This structure keeps track of the number of locks on that
319** inode. If a close is attempted against an inode that is holding
320** locks, the close is deferred until all locks clear by adding the
321** file descriptor to be closed to the pending list.
322*/
323struct openCnt {
324 struct openKey key; /* The lookup key */
325 int nRef; /* Number of pointers to this structure */
326 int nLock; /* Number of outstanding locks */
327 int nPending; /* Number of pending close() operations */
328 int *aPending; /* Malloced space holding fd's awaiting a close() */
329};
330
331/*
drhf1a221e2006-01-15 17:27:17 +0000332** These hash tables map inodes and file descriptors (really, lockKey and
333** openKey structures) into lockInfo and openCnt structures. Access to
334** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000335*/
drh17435752007-08-16 04:30:38 +0000336static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
337static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000338
drhbfe66312006-10-03 17:40:40 +0000339#ifdef SQLITE_ENABLE_LOCKING_STYLE
340/*
341** The locking styles are associated with the different file locking
342** capabilities supported by different file systems.
343**
344** POSIX locking style fully supports shared and exclusive byte-range locks
345** ADP locking only supports exclusive byte-range locks
346** FLOCK only supports a single file-global exclusive lock
347** DOTLOCK isn't a true locking style, it refers to the use of a special
348** file named the same as the database file with a '.lock' extension, this
349** can be used on file systems that do not offer any reliable file locking
350** NO locking means that no locking will be attempted, this is only used for
351** read-only file systems currently
352** UNSUPPORTED means that no locking will be attempted, this is only used for
353** file systems that are known to be unsupported
354*/
355typedef enum {
drhfd131da2007-08-07 17:13:03 +0000356 posixLockingStyle = 0, /* standard posix-advisory locks */
357 afpLockingStyle, /* use afp locks */
358 flockLockingStyle, /* use flock() */
359 dotlockLockingStyle, /* use <file>.lock files */
360 noLockingStyle, /* useful for read-only file system */
361 unsupportedLockingStyle /* indicates unsupported file system */
drhbfe66312006-10-03 17:40:40 +0000362} sqlite3LockingStyle;
363#endif /* SQLITE_ENABLE_LOCKING_STYLE */
364
danielk1977ad94b582007-08-20 06:44:22 +0000365/*
366** Helper functions to obtain and relinquish the global mutex.
367*/
danielk1977b4b47412007-08-17 15:53:36 +0000368static void enterMutex(){
drh51fc3472007-08-21 13:51:23 +0000369 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000370}
371static void leaveMutex(){
drh51fc3472007-08-21 13:51:23 +0000372 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000373}
374
drhd677b3d2007-08-20 22:48:41 +0000375#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000376/*
377** This variable records whether or not threads can override each others
378** locks.
379**
380** 0: No. Threads cannot override each others locks.
381** 1: Yes. Threads can override each others locks.
382** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000383**
drh5062d3a2006-01-31 23:03:35 +0000384** On some systems, we know at compile-time if threads can override each
385** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
386** will be set appropriately. On other systems, we have to check at
387** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
388** undefined.
389**
drhf1a221e2006-01-15 17:27:17 +0000390** This variable normally has file scope only. But during testing, we make
391** it a global so that the test code can change its value in order to verify
392** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000393*/
drh5062d3a2006-01-31 23:03:35 +0000394#ifndef SQLITE_THREAD_OVERRIDE_LOCK
395# define SQLITE_THREAD_OVERRIDE_LOCK -1
396#endif
drh029b44b2006-01-15 00:13:15 +0000397#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000398int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000399#else
drh5062d3a2006-01-31 23:03:35 +0000400static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000401#endif
drh5fdae772004-06-29 03:29:00 +0000402
403/*
404** This structure holds information passed into individual test
405** threads by the testThreadLockingBehavior() routine.
406*/
407struct threadTestData {
408 int fd; /* File to be locked */
409 struct flock lock; /* The locking operation */
410 int result; /* Result of the locking operation */
411};
412
drh2b4b5962005-06-15 17:47:55 +0000413#ifdef SQLITE_LOCK_TRACE
414/*
415** Print out information about all locking operations.
416**
417** This routine is used for troubleshooting locks on multithreaded
418** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
419** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000420** turned off.
drh2b4b5962005-06-15 17:47:55 +0000421*/
422static int lockTrace(int fd, int op, struct flock *p){
423 char *zOpName, *zType;
424 int s;
425 int savedErrno;
426 if( op==F_GETLK ){
427 zOpName = "GETLK";
428 }else if( op==F_SETLK ){
429 zOpName = "SETLK";
430 }else{
431 s = fcntl(fd, op, p);
432 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
433 return s;
434 }
435 if( p->l_type==F_RDLCK ){
436 zType = "RDLCK";
437 }else if( p->l_type==F_WRLCK ){
438 zType = "WRLCK";
439 }else if( p->l_type==F_UNLCK ){
440 zType = "UNLCK";
441 }else{
442 assert( 0 );
443 }
444 assert( p->l_whence==SEEK_SET );
445 s = fcntl(fd, op, p);
446 savedErrno = errno;
447 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
448 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
449 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000450 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000451 struct flock l2;
452 l2 = *p;
453 fcntl(fd, F_GETLK, &l2);
454 if( l2.l_type==F_RDLCK ){
455 zType = "RDLCK";
456 }else if( l2.l_type==F_WRLCK ){
457 zType = "WRLCK";
458 }else if( l2.l_type==F_UNLCK ){
459 zType = "UNLCK";
460 }else{
461 assert( 0 );
462 }
463 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
464 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
465 }
466 errno = savedErrno;
467 return s;
468}
469#define fcntl lockTrace
470#endif /* SQLITE_LOCK_TRACE */
471
drh5fdae772004-06-29 03:29:00 +0000472/*
473** The testThreadLockingBehavior() routine launches two separate
474** threads on this routine. This routine attempts to lock a file
475** descriptor then returns. The success or failure of that attempt
476** allows the testThreadLockingBehavior() procedure to determine
477** whether or not threads can override each others locks.
478*/
479static void *threadLockingTest(void *pArg){
480 struct threadTestData *pData = (struct threadTestData*)pArg;
481 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
482 return pArg;
483}
484
485/*
486** This procedure attempts to determine whether or not threads
487** can override each others locks then sets the
488** threadsOverrideEachOthersLocks variable appropriately.
489*/
danielk19774d5238f2006-01-27 06:32:00 +0000490static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000491 int fd;
492 struct threadTestData d[2];
493 pthread_t t[2];
494
495 fd = dup(fd_orig);
496 if( fd<0 ) return;
497 memset(d, 0, sizeof(d));
498 d[0].fd = fd;
499 d[0].lock.l_type = F_RDLCK;
500 d[0].lock.l_len = 1;
501 d[0].lock.l_start = 0;
502 d[0].lock.l_whence = SEEK_SET;
503 d[1] = d[0];
504 d[1].lock.l_type = F_WRLCK;
505 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
506 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
507 pthread_join(t[0], 0);
508 pthread_join(t[1], 0);
509 close(fd);
510 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
511}
drhd677b3d2007-08-20 22:48:41 +0000512#endif /* SQLITE_THREADSAFE */
drh5fdae772004-06-29 03:29:00 +0000513
drhbbd42a62004-05-22 17:41:58 +0000514/*
515** Release a lockInfo structure previously allocated by findLockInfo().
516*/
517static void releaseLockInfo(struct lockInfo *pLock){
drhbfe66312006-10-03 17:40:40 +0000518 if (pLock == NULL)
519 return;
drhbbd42a62004-05-22 17:41:58 +0000520 pLock->nRef--;
521 if( pLock->nRef==0 ){
522 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
drh17435752007-08-16 04:30:38 +0000523 sqlite3_free(pLock);
drhbbd42a62004-05-22 17:41:58 +0000524 }
525}
526
527/*
528** Release a openCnt structure previously allocated by findLockInfo().
529*/
530static void releaseOpenCnt(struct openCnt *pOpen){
drhbfe66312006-10-03 17:40:40 +0000531 if (pOpen == NULL)
532 return;
drhbbd42a62004-05-22 17:41:58 +0000533 pOpen->nRef--;
534 if( pOpen->nRef==0 ){
535 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000536 free(pOpen->aPending);
drh17435752007-08-16 04:30:38 +0000537 sqlite3_free(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000538 }
539}
540
drhbfe66312006-10-03 17:40:40 +0000541#ifdef SQLITE_ENABLE_LOCKING_STYLE
542/*
543** Tests a byte-range locking query to see if byte range locks are
544** supported, if not we fall back to dotlockLockingStyle.
545*/
danielk1977ad94b582007-08-20 06:44:22 +0000546static sqlite3LockingStyle sqlite3TestLockingStyle(
547 const char *filePath,
548 int fd
549){
drhbfe66312006-10-03 17:40:40 +0000550 /* test byte-range lock using fcntl */
551 struct flock lockInfo;
552
553 lockInfo.l_len = 1;
554 lockInfo.l_start = 0;
555 lockInfo.l_whence = SEEK_SET;
556 lockInfo.l_type = F_RDLCK;
557
danielk1977ad94b582007-08-20 06:44:22 +0000558 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
drhbfe66312006-10-03 17:40:40 +0000559 return posixLockingStyle;
560 }
561
562 /* testing for flock can give false positives. So if if the above test
563 ** fails, then we fall back to using dot-lock style locking.
564 */
565 return dotlockLockingStyle;
566}
567
568/*
569** Examines the f_fstypename entry in the statfs structure as returned by
570** stat() for the file system hosting the database file, assigns the
571** appropriate locking style based on it's value. These values and
572** assignments are based on Darwin/OSX behavior and have not been tested on
573** other systems.
574*/
danielk1977ad94b582007-08-20 06:44:22 +0000575static sqlite3LockingStyle sqlite3DetectLockingStyle(
576 const char *filePath,
577 int fd
578){
drhbfe66312006-10-03 17:40:40 +0000579
580#ifdef SQLITE_FIXED_LOCKING_STYLE
581 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
582#else
583 struct statfs fsInfo;
584
585 if (statfs(filePath, &fsInfo) == -1)
586 return sqlite3TestLockingStyle(filePath, fd);
587
588 if (fsInfo.f_flags & MNT_RDONLY)
589 return noLockingStyle;
590
591 if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
592 (!strcmp(fsInfo.f_fstypename, "ufs")) )
drhfd131da2007-08-07 17:13:03 +0000593 return posixLockingStyle;
drhbfe66312006-10-03 17:40:40 +0000594
595 if(!strcmp(fsInfo.f_fstypename, "afpfs"))
596 return afpLockingStyle;
597
598 if(!strcmp(fsInfo.f_fstypename, "nfs"))
599 return sqlite3TestLockingStyle(filePath, fd);
600
601 if(!strcmp(fsInfo.f_fstypename, "smbfs"))
602 return flockLockingStyle;
603
604 if(!strcmp(fsInfo.f_fstypename, "msdos"))
605 return dotlockLockingStyle;
606
607 if(!strcmp(fsInfo.f_fstypename, "webdav"))
608 return unsupportedLockingStyle;
609
610 return sqlite3TestLockingStyle(filePath, fd);
drh3b62b2f2007-06-08 18:27:03 +0000611#endif /* SQLITE_FIXED_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +0000612}
613
614#endif /* SQLITE_ENABLE_LOCKING_STYLE */
615
drhbbd42a62004-05-22 17:41:58 +0000616/*
617** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000618** describes that file descriptor. Create new ones if necessary. The
619** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000620**
621** Return the number of errors.
622*/
drh38f82712004-06-18 17:10:16 +0000623static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000624 int fd, /* The file descriptor used in the key */
625 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000626 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000627){
628 int rc;
629 struct lockKey key1;
630 struct openKey key2;
631 struct stat statbuf;
632 struct lockInfo *pLock;
633 struct openCnt *pOpen;
634 rc = fstat(fd, &statbuf);
635 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000636
drhbbd42a62004-05-22 17:41:58 +0000637 memset(&key1, 0, sizeof(key1));
638 key1.dev = statbuf.st_dev;
639 key1.ino = statbuf.st_ino;
drhd677b3d2007-08-20 22:48:41 +0000640#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000641 if( threadsOverrideEachOthersLocks<0 ){
642 testThreadLockingBehavior(fd);
643 }
644 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
645#endif
drhbbd42a62004-05-22 17:41:58 +0000646 memset(&key2, 0, sizeof(key2));
647 key2.dev = statbuf.st_dev;
648 key2.ino = statbuf.st_ino;
649 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
650 if( pLock==0 ){
651 struct lockInfo *pOld;
drh17435752007-08-16 04:30:38 +0000652 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000653 if( pLock==0 ){
654 rc = 1;
655 goto exit_findlockinfo;
656 }
drhbbd42a62004-05-22 17:41:58 +0000657 pLock->key = key1;
658 pLock->nRef = 1;
659 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000660 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000661 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
662 if( pOld!=0 ){
663 assert( pOld==pLock );
drh17435752007-08-16 04:30:38 +0000664 sqlite3_free(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000665 rc = 1;
666 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000667 }
668 }else{
669 pLock->nRef++;
670 }
671 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000672 if( ppOpen!=0 ){
673 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000674 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000675 struct openCnt *pOld;
drh17435752007-08-16 04:30:38 +0000676 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000677 if( pOpen==0 ){
678 releaseLockInfo(pLock);
679 rc = 1;
680 goto exit_findlockinfo;
681 }
682 pOpen->key = key2;
683 pOpen->nRef = 1;
684 pOpen->nLock = 0;
685 pOpen->nPending = 0;
686 pOpen->aPending = 0;
687 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
688 if( pOld!=0 ){
689 assert( pOld==pOpen );
drh17435752007-08-16 04:30:38 +0000690 sqlite3_free(pOpen);
drh029b44b2006-01-15 00:13:15 +0000691 releaseLockInfo(pLock);
692 rc = 1;
693 goto exit_findlockinfo;
694 }
695 }else{
696 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000697 }
drh029b44b2006-01-15 00:13:15 +0000698 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000699 }
danielk1977441b09a2006-01-05 13:48:29 +0000700
701exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000702 return rc;
drhbbd42a62004-05-22 17:41:58 +0000703}
704
drh64b1bea2006-01-15 02:30:57 +0000705#ifdef SQLITE_DEBUG
706/*
707** Helper function for printing out trace information from debugging
708** binaries. This returns the string represetation of the supplied
709** integer lock-type.
710*/
711static const char *locktypeName(int locktype){
712 switch( locktype ){
713 case NO_LOCK: return "NONE";
714 case SHARED_LOCK: return "SHARED";
715 case RESERVED_LOCK: return "RESERVED";
716 case PENDING_LOCK: return "PENDING";
717 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
718 }
719 return "ERROR";
720}
721#endif
722
drhbbd42a62004-05-22 17:41:58 +0000723/*
drh029b44b2006-01-15 00:13:15 +0000724** If we are currently in a different thread than the thread that the
725** unixFile argument belongs to, then transfer ownership of the unixFile
726** over to the current thread.
727**
728** A unixFile is only owned by a thread on systems where one thread is
729** unable to override locks created by a different thread. RedHat9 is
730** an example of such a system.
731**
732** Ownership transfer is only allowed if the unixFile is currently unlocked.
733** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000734** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000735*/
drhd677b3d2007-08-20 22:48:41 +0000736#if SQLITE_THREADSAFE
drh029b44b2006-01-15 00:13:15 +0000737static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000738 int rc;
drh029b44b2006-01-15 00:13:15 +0000739 pthread_t hSelf;
740 if( threadsOverrideEachOthersLocks ){
741 /* Ownership transfers not needed on this system */
742 return SQLITE_OK;
743 }
744 hSelf = pthread_self();
745 if( pthread_equal(pFile->tid, hSelf) ){
746 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000747 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000748 return SQLITE_OK;
749 }
750 if( pFile->locktype!=NO_LOCK ){
751 /* We cannot change ownership while we are holding a lock! */
752 return SQLITE_MISUSE;
753 }
drh4f0c5872007-03-26 22:05:01 +0000754 OSTRACE4("Transfer ownership of %d from %d to %d\n",
755 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000756 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000757 if (pFile->pLock != NULL) {
758 releaseLockInfo(pFile->pLock);
759 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000760 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000761 locktypeName(pFile->locktype),
762 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
763 return rc;
764 } else {
765 return SQLITE_OK;
766 }
drh029b44b2006-01-15 00:13:15 +0000767}
768#else
drhf1a221e2006-01-15 17:27:17 +0000769 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000770# define transferOwnership(X) SQLITE_OK
771#endif
772
773/*
danielk19772a6bdf62007-08-20 16:07:00 +0000774** Seek to the offset passed as the second argument, then read cnt
775** bytes into pBuf. Return the number of bytes actually read.
drhb912b282006-03-23 22:42:20 +0000776*/
danielk197762079062007-08-15 17:08:46 +0000777static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000778 int got;
drh8ebf6702007-02-06 11:11:08 +0000779 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000780 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000781#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000782 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000783 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +0000784#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000785 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000786 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +0000787#else
danielk197762079062007-08-15 17:08:46 +0000788 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +0000789 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +0000790 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000791 return -1;
792 }
drhb912b282006-03-23 22:42:20 +0000793 got = read(id->h, pBuf, cnt);
794#endif
drh15d00c42007-02-27 02:01:14 +0000795 TIMER_END;
danielk1977967a4a12007-08-20 14:23:44 +0000796 OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000797 return got;
798}
799
800/*
drhbbd42a62004-05-22 17:41:58 +0000801** Read data from a file into a buffer. Return SQLITE_OK if all
802** bytes were read successfully and SQLITE_IOERR if anything goes
803** wrong.
804*/
danielk197762079062007-08-15 17:08:46 +0000805static int unixRead(
806 sqlite3_file *id,
807 void *pBuf,
808 int amt,
809 sqlite3_int64 offset
810){
drhbbd42a62004-05-22 17:41:58 +0000811 int got;
drh9cbe6352005-11-29 03:13:21 +0000812 assert( id );
danielk197762079062007-08-15 17:08:46 +0000813 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000814 if( got==amt ){
815 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +0000816 }else if( got<0 ){
817 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +0000818 }else{
drhbafda092007-01-03 23:36:22 +0000819 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +0000820 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +0000821 }
822}
823
824/*
drhb912b282006-03-23 22:42:20 +0000825** Seek to the offset in id->offset then read cnt bytes into pBuf.
826** Return the number of bytes actually read. Update the offset.
827*/
danielk197762079062007-08-15 17:08:46 +0000828static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000829 int got;
drh8ebf6702007-02-06 11:11:08 +0000830 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000831 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000832#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000833 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +0000834#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000835 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +0000836#else
danielk197762079062007-08-15 17:08:46 +0000837 newOffset = lseek(id->h, offset, SEEK_SET);
838 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000839 return -1;
840 }
drhb912b282006-03-23 22:42:20 +0000841 got = write(id->h, pBuf, cnt);
842#endif
drh15d00c42007-02-27 02:01:14 +0000843 TIMER_END;
danielk197762079062007-08-15 17:08:46 +0000844 OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000845 return got;
846}
847
848
849/*
drhbbd42a62004-05-22 17:41:58 +0000850** Write data from a buffer into a file. Return SQLITE_OK on success
851** or some other error code on failure.
852*/
danielk197762079062007-08-15 17:08:46 +0000853static int unixWrite(
854 sqlite3_file *id,
855 const void *pBuf,
856 int amt,
857 sqlite3_int64 offset
858){
drhbbd42a62004-05-22 17:41:58 +0000859 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000860 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000861 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +0000862 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000863 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +0000864 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +0000865 pBuf = &((char*)pBuf)[wrote];
866 }
drh59685932006-09-14 13:47:11 +0000867 SimulateIOError(( wrote=(-1), amt=1 ));
868 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +0000869 if( amt>0 ){
drh59685932006-09-14 13:47:11 +0000870 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +0000871 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +0000872 }else{
873 return SQLITE_FULL;
874 }
drhbbd42a62004-05-22 17:41:58 +0000875 }
876 return SQLITE_OK;
877}
878
drhb851b2c2005-03-10 14:11:12 +0000879#ifdef SQLITE_TEST
880/*
881** Count the number of fullsyncs and normal syncs. This is used to test
882** that syncs and fullsyncs are occuring at the right times.
883*/
884int sqlite3_sync_count = 0;
885int sqlite3_fullsync_count = 0;
886#endif
887
drhf2f23912005-10-05 10:29:36 +0000888/*
889** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
890** Otherwise use fsync() in its place.
891*/
892#ifndef HAVE_FDATASYNC
893# define fdatasync fsync
894#endif
895
drhac530b12006-02-11 01:25:50 +0000896/*
897** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
898** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
899** only available on Mac OS X. But that could change.
900*/
901#ifdef F_FULLFSYNC
902# define HAVE_FULLFSYNC 1
903#else
904# define HAVE_FULLFSYNC 0
905#endif
906
drhb851b2c2005-03-10 14:11:12 +0000907
drhbbd42a62004-05-22 17:41:58 +0000908/*
drhdd809b02004-07-17 21:44:57 +0000909** The fsync() system call does not work as advertised on many
910** unix systems. The following procedure is an attempt to make
911** it work better.
drh1398ad32005-01-19 23:24:50 +0000912**
913** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
914** for testing when we want to run through the test suite quickly.
915** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
916** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
917** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000918*/
drheb796a72005-09-08 12:38:41 +0000919static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000920 int rc;
drhb851b2c2005-03-10 14:11:12 +0000921
922 /* Record the number of times that we do a normal fsync() and
923 ** FULLSYNC. This is used during testing to verify that this procedure
924 ** gets called with the correct arguments.
925 */
926#ifdef SQLITE_TEST
927 if( fullSync ) sqlite3_fullsync_count++;
928 sqlite3_sync_count++;
929#endif
930
931 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
932 ** no-op
933 */
934#ifdef SQLITE_NO_SYNC
935 rc = SQLITE_OK;
936#else
937
drhac530b12006-02-11 01:25:50 +0000938#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000939 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000940 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +0000941 }else{
942 rc = 1;
943 }
944 /* If the FULLFSYNC failed, fall back to attempting an fsync().
945 * It shouldn't be possible for fullfsync to fail on the local
946 * file system (on OSX), so failure indicates that FULLFSYNC
947 * isn't supported for this file system. So, attempt an fsync
948 * and (for now) ignore the overhead of a superfluous fcntl call.
949 * It'd be better to detect fullfsync support once and avoid
950 * the fcntl call every time sync is called.
951 */
952 if( rc ) rc = fsync(fd);
953
954#else
drheb796a72005-09-08 12:38:41 +0000955 if( dataOnly ){
956 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000957 }else{
drheb796a72005-09-08 12:38:41 +0000958 rc = fsync(fd);
959 }
aswiftae0943b2007-01-31 23:37:07 +0000960#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +0000961#endif /* defined(SQLITE_NO_SYNC) */
962
drhdd809b02004-07-17 21:44:57 +0000963 return rc;
964}
965
966/*
drhbbd42a62004-05-22 17:41:58 +0000967** Make sure all writes to a particular file are committed to disk.
968**
drheb796a72005-09-08 12:38:41 +0000969** If dataOnly==0 then both the file itself and its metadata (file
970** size, access time, etc) are synced. If dataOnly!=0 then only the
971** file data is synced.
972**
drhbbd42a62004-05-22 17:41:58 +0000973** Under Unix, also make sure that the directory entry for the file
974** has been created by fsync-ing the directory that contains the file.
975** If we do not do this and we encounter a power failure, the directory
976** entry for the journal might not exist after we reboot. The next
977** SQLite to access the file will not know that the journal exists (because
978** the directory entry for the journal was never created) and the transaction
979** will not roll back - possibly leading to database corruption.
980*/
danielk197790949c22007-08-17 16:50:38 +0000981static int unixSync(sqlite3_file *id, int flags){
drh59685932006-09-14 13:47:11 +0000982 int rc;
drh054889e2005-11-30 03:20:31 +0000983 unixFile *pFile = (unixFile*)id;
danielk197790949c22007-08-17 16:50:38 +0000984
danielk1977f036aef2007-08-20 05:36:51 +0000985 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
986 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
987
988 /* Check that one of SQLITE_SYNC_NORMAL, FULL or BARRIER was passed */
989 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
990 || (flags&0x0F)==SQLITE_SYNC_FULL
991 || (flags&0x0F)==SQLITE_SYNC_BARRIER
992 );
danielk197790949c22007-08-17 16:50:38 +0000993
drh054889e2005-11-30 03:20:31 +0000994 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +0000995 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +0000996 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +0000997 SimulateIOError( rc=1 );
998 if( rc ){
drh4ac285a2006-09-15 07:28:50 +0000999 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001000 }
drh054889e2005-11-30 03:20:31 +00001001 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001002 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001003 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001004#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001005 /* The directory sync is only attempted if full_fsync is
1006 ** turned off or unavailable. If a full_fsync occurred above,
1007 ** then the directory sync is superfluous.
1008 */
danielk197790949c22007-08-17 16:50:38 +00001009 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001010 /*
1011 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001012 ** errors when applied to directories on certain file systems.
1013 ** A failed directory sync is not a big deal. So it seems
1014 ** better to ignore the error. Ticket #1657
1015 */
1016 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001017 }
danielk1977d7c03f72005-11-25 10:38:22 +00001018#endif
drh054889e2005-11-30 03:20:31 +00001019 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1020 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001021 }
drha2854222004-06-17 19:04:17 +00001022 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001023}
1024
1025/*
1026** Truncate an open file to a specified size
1027*/
danielk197762079062007-08-15 17:08:46 +00001028static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001029 int rc;
drh9cbe6352005-11-29 03:13:21 +00001030 assert( id );
drh63fff5f2007-06-19 10:50:38 +00001031 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001032 SimulateIOError( rc=1 );
1033 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001034 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001035 }else{
1036 return SQLITE_OK;
1037 }
drhbbd42a62004-05-22 17:41:58 +00001038}
1039
1040/*
1041** Determine the current size of a file in bytes
1042*/
danielk197762079062007-08-15 17:08:46 +00001043static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001044 int rc;
drhbbd42a62004-05-22 17:41:58 +00001045 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001046 assert( id );
drh59685932006-09-14 13:47:11 +00001047 rc = fstat(((unixFile*)id)->h, &buf);
1048 SimulateIOError( rc=1 );
1049 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001050 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001051 }
1052 *pSize = buf.st_size;
1053 return SQLITE_OK;
1054}
1055
danielk19779a1d0ab2004-06-01 14:09:28 +00001056/*
danielk197713adf8a2004-06-03 16:08:41 +00001057** This routine checks if there is a RESERVED lock held on the specified
1058** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001059** non-zero. If the file is unlocked or holds only SHARED locks, then
1060** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001061*/
danielk197762079062007-08-15 17:08:46 +00001062static int unixCheckReservedLock(sqlite3_file *id){
danielk197713adf8a2004-06-03 16:08:41 +00001063 int r = 0;
drh054889e2005-11-30 03:20:31 +00001064 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001065
drh054889e2005-11-30 03:20:31 +00001066 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001067 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001068
1069 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001070 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001071 r = 1;
1072 }
1073
drh2ac3ee92004-06-07 16:27:46 +00001074 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001075 */
1076 if( !r ){
1077 struct flock lock;
1078 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001079 lock.l_start = RESERVED_BYTE;
1080 lock.l_len = 1;
1081 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001082 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001083 if( lock.l_type!=F_UNLCK ){
1084 r = 1;
1085 }
1086 }
1087
danielk1977b4b47412007-08-17 15:53:36 +00001088 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001089 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001090
1091 return r;
1092}
1093
1094/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001095** Lock the file with the lock specified by parameter locktype - one
1096** of the following:
1097**
drh2ac3ee92004-06-07 16:27:46 +00001098** (1) SHARED_LOCK
1099** (2) RESERVED_LOCK
1100** (3) PENDING_LOCK
1101** (4) EXCLUSIVE_LOCK
1102**
drhb3e04342004-06-08 00:47:47 +00001103** Sometimes when requesting one lock state, additional lock states
1104** are inserted in between. The locking might fail on one of the later
1105** transitions leaving the lock state different from what it started but
1106** still short of its goal. The following chart shows the allowed
1107** transitions and the inserted intermediate states:
1108**
1109** UNLOCKED -> SHARED
1110** SHARED -> RESERVED
1111** SHARED -> (PENDING) -> EXCLUSIVE
1112** RESERVED -> (PENDING) -> EXCLUSIVE
1113** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001114**
drha6abd042004-06-09 17:37:22 +00001115** This routine will only increase a lock. Use the sqlite3OsUnlock()
1116** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001117*/
danielk197762079062007-08-15 17:08:46 +00001118static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001119 /* The following describes the implementation of the various locks and
1120 ** lock transitions in terms of the POSIX advisory shared and exclusive
1121 ** lock primitives (called read-locks and write-locks below, to avoid
1122 ** confusion with SQLite lock names). The algorithms are complicated
1123 ** slightly in order to be compatible with windows systems simultaneously
1124 ** accessing the same database file, in case that is ever required.
1125 **
1126 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1127 ** byte', each single bytes at well known offsets, and the 'shared byte
1128 ** range', a range of 510 bytes at a well known offset.
1129 **
1130 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1131 ** byte'. If this is successful, a random byte from the 'shared byte
1132 ** range' is read-locked and the lock on the 'pending byte' released.
1133 **
danielk197790ba3bd2004-06-25 08:32:25 +00001134 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1135 ** A RESERVED lock is implemented by grabbing a write-lock on the
1136 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001137 **
1138 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001139 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1140 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1141 ** obtained, but existing SHARED locks are allowed to persist. A process
1142 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1143 ** This property is used by the algorithm for rolling back a journal file
1144 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001145 **
danielk197790ba3bd2004-06-25 08:32:25 +00001146 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1147 ** implemented by obtaining a write-lock on the entire 'shared byte
1148 ** range'. Since all other locks require a read-lock on one of the bytes
1149 ** within this range, this ensures that no other locks are held on the
1150 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001151 **
1152 ** The reason a single byte cannot be used instead of the 'shared byte
1153 ** range' is that some versions of windows do not support read-locks. By
1154 ** locking a random byte from a range, concurrent SHARED locks may exist
1155 ** even if the locking primitive used is always a write-lock.
1156 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001157 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001158 unixFile *pFile = (unixFile*)id;
1159 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001160 struct flock lock;
1161 int s;
1162
drh054889e2005-11-30 03:20:31 +00001163 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001164 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001165 locktypeName(locktype), locktypeName(pFile->locktype),
1166 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001167
1168 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001169 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001170 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001171 */
drh054889e2005-11-30 03:20:31 +00001172 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001173 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001174 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001175 return SQLITE_OK;
1176 }
1177
drhb3e04342004-06-08 00:47:47 +00001178 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001179 */
drh054889e2005-11-30 03:20:31 +00001180 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001181 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001182 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001183
drh054889e2005-11-30 03:20:31 +00001184 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001185 */
danielk1977b4b47412007-08-17 15:53:36 +00001186 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001187
drh029b44b2006-01-15 00:13:15 +00001188 /* Make sure the current thread owns the pFile.
1189 */
1190 rc = transferOwnership(pFile);
1191 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001192 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001193 return rc;
1194 }
drh64b1bea2006-01-15 02:30:57 +00001195 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001196
danielk1977ad94b582007-08-20 06:44:22 +00001197 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001198 ** handle that precludes the requested lock, return BUSY.
1199 */
drh054889e2005-11-30 03:20:31 +00001200 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001201 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001202 ){
1203 rc = SQLITE_BUSY;
1204 goto end_lock;
1205 }
1206
1207 /* If a SHARED lock is requested, and some thread using this PID already
1208 ** has a SHARED or RESERVED lock, then increment reference counts and
1209 ** return SQLITE_OK.
1210 */
1211 if( locktype==SHARED_LOCK &&
1212 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1213 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001214 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001215 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001216 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001217 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001218 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001219 goto end_lock;
1220 }
1221
danielk197713adf8a2004-06-03 16:08:41 +00001222 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001223
danielk19779a1d0ab2004-06-01 14:09:28 +00001224 lock.l_whence = SEEK_SET;
1225
drh3cde3bb2004-06-12 02:17:14 +00001226 /* A PENDING lock is needed before acquiring a SHARED lock and before
1227 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1228 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001229 */
drh3cde3bb2004-06-12 02:17:14 +00001230 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001231 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001232 ){
danielk1977489468c2004-06-28 08:25:47 +00001233 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001234 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001235 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001236 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001237 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1238 goto end_lock;
1239 }
drh3cde3bb2004-06-12 02:17:14 +00001240 }
1241
1242
1243 /* If control gets to this point, then actually go ahead and make
1244 ** operating system calls for the specified lock.
1245 */
1246 if( locktype==SHARED_LOCK ){
1247 assert( pLock->cnt==0 );
1248 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001249
drh2ac3ee92004-06-07 16:27:46 +00001250 /* Now get the read-lock */
1251 lock.l_start = SHARED_FIRST;
1252 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001253 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001254
1255 /* Drop the temporary PENDING lock */
1256 lock.l_start = PENDING_BYTE;
1257 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001258 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001259 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001260 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001261 goto end_lock;
1262 }
drhe2396a12007-03-29 20:19:58 +00001263 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001264 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1265 }else{
drh054889e2005-11-30 03:20:31 +00001266 pFile->locktype = SHARED_LOCK;
1267 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001268 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001269 }
drh3cde3bb2004-06-12 02:17:14 +00001270 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1271 /* We are trying for an exclusive lock but another thread in this
1272 ** same process is still holding a shared lock. */
1273 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001274 }else{
drh3cde3bb2004-06-12 02:17:14 +00001275 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001276 ** assumed that there is a SHARED or greater lock on the file
1277 ** already.
1278 */
drh054889e2005-11-30 03:20:31 +00001279 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001280 lock.l_type = F_WRLCK;
1281 switch( locktype ){
1282 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001283 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001284 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001285 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001286 lock.l_start = SHARED_FIRST;
1287 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001288 break;
1289 default:
1290 assert(0);
1291 }
drh054889e2005-11-30 03:20:31 +00001292 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001293 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1295 }
drhbbd42a62004-05-22 17:41:58 +00001296 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001297
danielk1977ecb2a962004-06-02 06:30:16 +00001298 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001299 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001300 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001301 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001302 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001303 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001304 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001305
1306end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001307 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001308 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001309 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001310 return rc;
1311}
1312
1313/*
drh054889e2005-11-30 03:20:31 +00001314** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001315** must be either NO_LOCK or SHARED_LOCK.
1316**
1317** If the locking level of the file descriptor is already at or below
1318** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001319*/
danielk197762079062007-08-15 17:08:46 +00001320static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001321 struct lockInfo *pLock;
1322 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001323 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001324 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001325
drh054889e2005-11-30 03:20:31 +00001326 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001327 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001328 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001329
1330 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001331 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001332 return SQLITE_OK;
1333 }
drhf1a221e2006-01-15 17:27:17 +00001334 if( CHECK_THREADID(pFile) ){
1335 return SQLITE_MISUSE;
1336 }
danielk1977b4b47412007-08-17 15:53:36 +00001337 enterMutex();
drh054889e2005-11-30 03:20:31 +00001338 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001339 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001340 if( pFile->locktype>SHARED_LOCK ){
1341 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001342 if( locktype==SHARED_LOCK ){
1343 lock.l_type = F_RDLCK;
1344 lock.l_whence = SEEK_SET;
1345 lock.l_start = SHARED_FIRST;
1346 lock.l_len = SHARED_SIZE;
drhe2396a12007-03-29 20:19:58 +00001347 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
drh9c105bb2004-10-02 20:38:28 +00001348 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001349 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001350 }
1351 }
drhbbd42a62004-05-22 17:41:58 +00001352 lock.l_type = F_UNLCK;
1353 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001354 lock.l_start = PENDING_BYTE;
1355 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drhe2396a12007-03-29 20:19:58 +00001356 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001357 pLock->locktype = SHARED_LOCK;
1358 }else{
drh4ac285a2006-09-15 07:28:50 +00001359 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001360 }
drhbbd42a62004-05-22 17:41:58 +00001361 }
drha6abd042004-06-09 17:37:22 +00001362 if( locktype==NO_LOCK ){
1363 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001364
drha6abd042004-06-09 17:37:22 +00001365 /* Decrement the shared lock counter. Release the lock using an
1366 ** OS call only when all threads in this same process have released
1367 ** the lock.
1368 */
1369 pLock->cnt--;
1370 if( pLock->cnt==0 ){
1371 lock.l_type = F_UNLCK;
1372 lock.l_whence = SEEK_SET;
1373 lock.l_start = lock.l_len = 0L;
drhe2396a12007-03-29 20:19:58 +00001374 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001375 pLock->locktype = NO_LOCK;
1376 }else{
drh4ac285a2006-09-15 07:28:50 +00001377 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001378 }
drha6abd042004-06-09 17:37:22 +00001379 }
1380
drhbbd42a62004-05-22 17:41:58 +00001381 /* Decrement the count of locks against this same file. When the
1382 ** count reaches zero, close any other file descriptors whose close
1383 ** was deferred because of outstanding locks.
1384 */
drh054889e2005-11-30 03:20:31 +00001385 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001386 pOpen->nLock--;
1387 assert( pOpen->nLock>=0 );
1388 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1389 int i;
1390 for(i=0; i<pOpen->nPending; i++){
1391 close(pOpen->aPending[i]);
1392 }
drh64b1bea2006-01-15 02:30:57 +00001393 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001394 pOpen->nPending = 0;
1395 pOpen->aPending = 0;
1396 }
1397 }
danielk1977b4b47412007-08-17 15:53:36 +00001398 leaveMutex();
drh054889e2005-11-30 03:20:31 +00001399 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001400 return rc;
drhbbd42a62004-05-22 17:41:58 +00001401}
1402
1403/*
danielk1977e3026632004-06-22 11:29:02 +00001404** Close a file.
1405*/
danielk197762079062007-08-15 17:08:46 +00001406static int unixClose(sqlite3_file *id){
1407 unixFile *pFile = (unixFile *)id;
1408 if( !pFile ) return SQLITE_OK;
1409 unixUnlock(id, NO_LOCK);
1410 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1411 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001412 enterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001413
danielk197762079062007-08-15 17:08:46 +00001414 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001415 /* If there are outstanding locks, do not actually close the file just
1416 ** yet because that would clear those locks. Instead, add the file
1417 ** descriptor to pOpen->aPending. It will be automatically closed when
1418 ** the last lock is cleared.
1419 */
1420 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001421 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001422 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001423 if( aNew==0 ){
1424 /* If a malloc fails, just leak the file descriptor */
1425 }else{
1426 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001427 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001428 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001429 }
1430 }else{
1431 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001432 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001433 }
danielk197762079062007-08-15 17:08:46 +00001434 releaseLockInfo(pFile->pLock);
1435 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001436
danielk1977b4b47412007-08-17 15:53:36 +00001437 leaveMutex();
danielk197762079062007-08-15 17:08:46 +00001438 pFile->isOpen = 0;
1439 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001440 OpenCounter(-1);
danielk1977b4b47412007-08-17 15:53:36 +00001441 memset(pFile, 0, sizeof(unixFile));
drh02afc862006-01-20 18:10:57 +00001442 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001443}
1444
drhbfe66312006-10-03 17:40:40 +00001445
1446#ifdef SQLITE_ENABLE_LOCKING_STYLE
1447#pragma mark AFP Support
1448
1449/*
1450 ** The afpLockingContext structure contains all afp lock specific state
1451 */
1452typedef struct afpLockingContext afpLockingContext;
1453struct afpLockingContext {
1454 unsigned long long sharedLockByte;
1455 char *filePath;
1456};
1457
1458struct ByteRangeLockPB2
1459{
1460 unsigned long long offset; /* offset to first byte to lock */
1461 unsigned long long length; /* nbr of bytes to lock */
1462 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1463 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1464 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1465 int fd; /* file desc to assoc this lock with */
1466};
1467
drhfd131da2007-08-07 17:13:03 +00001468#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001469
danielk1977ad94b582007-08-20 06:44:22 +00001470/*
1471** Return 0 on success, 1 on failure. To match the behavior of the
1472** normal posix file locking (used in unixLock for example), we should
1473** provide 'richer' return codes - specifically to differentiate between
1474** 'file busy' and 'file system error' results.
1475*/
1476static int _AFPFSSetLock(
1477 const char *path,
1478 int fd,
1479 unsigned long long offset,
1480 unsigned long long length,
1481 int setLockFlag
1482){
drhfd131da2007-08-07 17:13:03 +00001483 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001484 int err;
1485
1486 pb.unLockFlag = setLockFlag ? 0 : 1;
1487 pb.startEndFlag = 0;
1488 pb.offset = offset;
1489 pb.length = length;
1490 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001491 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001492 (setLockFlag?"ON":"OFF"), fd, offset, length);
1493 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1494 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001495 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001496 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001497 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001498 } else {
1499 return 0;
1500 }
1501}
1502
1503/*
1504 ** This routine checks if there is a RESERVED lock held on the specified
1505 ** file by this or any other process. If such a lock is held, return
1506 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1507 ** return zero.
1508 */
danielk1977ad94b582007-08-20 06:44:22 +00001509static int afpUnixCheckReservedLock(sqlite3_file *id){
drhbfe66312006-10-03 17:40:40 +00001510 int r = 0;
1511 unixFile *pFile = (unixFile*)id;
1512
1513 assert( pFile );
1514 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1515
1516 /* Check if a thread in this process holds such a lock */
1517 if( pFile->locktype>SHARED_LOCK ){
1518 r = 1;
1519 }
1520
1521 /* Otherwise see if some other process holds it.
1522 */
1523 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001524 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001525 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1526 if (failed) {
1527 /* if we failed to get the lock then someone else must have it */
1528 r = 1;
1529 } else {
1530 /* if we succeeded in taking the reserved lock, unlock it to restore
1531 ** the original state */
1532 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1533 }
1534 }
drh4f0c5872007-03-26 22:05:01 +00001535 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001536
1537 return r;
1538}
1539
1540/* AFP-style locking following the behavior of unixLock, see the unixLock
1541** function comments for details of lock management. */
danielk1977ad94b582007-08-20 06:44:22 +00001542static int afpUnixLock(sqlite3_file *id, int locktype)
drhbfe66312006-10-03 17:40:40 +00001543{
1544 int rc = SQLITE_OK;
1545 unixFile *pFile = (unixFile*)id;
1546 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1547 int gotPendingLock = 0;
1548
1549 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001550 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001551 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1552 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001553 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001554 ** enterMutex() hasn't been called yet.
drhbfe66312006-10-03 17:40:40 +00001555 */
1556 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001557 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001558 locktypeName(locktype));
1559 return SQLITE_OK;
1560 }
1561
1562 /* Make sure the locking sequence is correct
1563 */
1564 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1565 assert( locktype!=PENDING_LOCK );
1566 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1567
1568 /* This mutex is needed because pFile->pLock is shared across threads
1569 */
danielk1977b4b47412007-08-17 15:53:36 +00001570 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001571
1572 /* Make sure the current thread owns the pFile.
1573 */
1574 rc = transferOwnership(pFile);
1575 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001576 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001577 return rc;
1578 }
1579
1580 /* A PENDING lock is needed before acquiring a SHARED lock and before
1581 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1582 ** be released.
1583 */
1584 if( locktype==SHARED_LOCK
1585 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
1586 ){
1587 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1588 PENDING_BYTE, 1, 1);
1589 if (failed) {
1590 rc = SQLITE_BUSY;
1591 goto afp_end_lock;
1592 }
1593 }
1594
1595 /* If control gets to this point, then actually go ahead and make
1596 ** operating system calls for the specified lock.
1597 */
1598 if( locktype==SHARED_LOCK ){
1599 int lk, failed;
1600 int tries = 0;
1601
1602 /* Now get the read-lock */
1603 /* note that the quality of the randomness doesn't matter that much */
1604 lk = random();
1605 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1606 failed = _AFPFSSetLock(context->filePath, pFile->h,
1607 SHARED_FIRST+context->sharedLockByte, 1, 1);
1608
1609 /* Drop the temporary PENDING lock */
1610 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1611 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1612 goto afp_end_lock;
1613 }
1614
1615 if( failed ){
1616 rc = SQLITE_BUSY;
1617 } else {
1618 pFile->locktype = SHARED_LOCK;
1619 }
1620 }else{
1621 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1622 ** assumed that there is a SHARED or greater lock on the file
1623 ** already.
1624 */
1625 int failed = 0;
1626 assert( 0!=pFile->locktype );
1627 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1628 /* Acquire a RESERVED lock */
1629 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1630 }
1631 if (!failed && locktype == EXCLUSIVE_LOCK) {
1632 /* Acquire an EXCLUSIVE lock */
1633
1634 /* Remove the shared lock before trying the range. we'll need to
1635 ** reestablish the shared lock if we can't get the afpUnixUnlock
1636 */
1637 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1638 context->sharedLockByte, 1, 0)) {
1639 /* now attemmpt to get the exclusive lock range */
1640 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1641 SHARED_SIZE, 1);
1642 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1643 context->sharedLockByte, 1, 1)) {
1644 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1645 }
1646 } else {
1647 /* */
1648 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1649 }
1650 }
1651 if( failed && rc == SQLITE_OK){
1652 rc = SQLITE_BUSY;
1653 }
1654 }
1655
1656 if( rc==SQLITE_OK ){
1657 pFile->locktype = locktype;
1658 }else if( locktype==EXCLUSIVE_LOCK ){
1659 pFile->locktype = PENDING_LOCK;
1660 }
1661
1662afp_end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001663 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001664 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001665 rc==SQLITE_OK ? "ok" : "failed");
1666 return rc;
1667}
1668
1669/*
1670 ** Lower the locking level on file descriptor pFile to locktype. locktype
1671 ** must be either NO_LOCK or SHARED_LOCK.
1672 **
1673 ** If the locking level of the file descriptor is already at or below
1674 ** the requested locking level, this routine is a no-op.
1675 */
danielk1977ad94b582007-08-20 06:44:22 +00001676static int afpUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001677 struct flock lock;
1678 int rc = SQLITE_OK;
1679 unixFile *pFile = (unixFile*)id;
1680 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1681
1682 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001683 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001684 pFile->locktype, getpid());
1685
1686 assert( locktype<=SHARED_LOCK );
1687 if( pFile->locktype<=locktype ){
1688 return SQLITE_OK;
1689 }
1690 if( CHECK_THREADID(pFile) ){
1691 return SQLITE_MISUSE;
1692 }
danielk1977b4b47412007-08-17 15:53:36 +00001693 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001694 if( pFile->locktype>SHARED_LOCK ){
1695 if( locktype==SHARED_LOCK ){
1696 int failed = 0;
1697
1698 /* unlock the exclusive range - then re-establish the shared lock */
1699 if (pFile->locktype==EXCLUSIVE_LOCK) {
1700 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1701 SHARED_SIZE, 0);
1702 if (!failed) {
1703 /* successfully removed the exclusive lock */
1704 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1705 context->sharedLockByte, 1, 1)) {
1706 /* failed to re-establish our shared lock */
1707 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1708 }
1709 } else {
1710 /* This should never happen - failed to unlock the exclusive range */
1711 rc = SQLITE_IOERR_UNLOCK;
1712 }
1713 }
1714 }
1715 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1716 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1717 /* failed to release the pending lock */
1718 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1719 }
1720 }
1721 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1722 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1723 /* failed to release the reserved lock */
1724 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1725 }
1726 }
1727 }
1728 if( locktype==NO_LOCK ){
1729 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1730 SHARED_FIRST + context->sharedLockByte, 1, 0);
1731 if (failed) {
1732 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1733 }
1734 }
1735 if (rc == SQLITE_OK)
1736 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001737 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001738 return rc;
1739}
1740
1741/*
1742 ** Close a file & cleanup AFP specific locking context
1743 */
danielk1977ad94b582007-08-20 06:44:22 +00001744static int afpUnixClose(sqlite3_file *id) {
1745 unixFile *pFile = (unixFile*)pId;
1746
1747 if( !pFile ) return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001748 afpUnixUnlock(*pId, NO_LOCK);
1749 /* free the AFP locking structure */
danielk1977ad94b582007-08-20 06:44:22 +00001750 if (pFile->lockingContext != NULL) {
1751 if (((afpLockingContext *)pFile->lockingContext)->filePath != NULL)
1752 sqlite3_free(((afpLockingContext*)pFile->lockingContext)->filePath);
1753 sqlite3_free(pFile->lockingContext);
drhbfe66312006-10-03 17:40:40 +00001754 }
danielk1977ad94b582007-08-20 06:44:22 +00001755
1756 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1757 pFile->dirfd = -1;
1758 close(pFile->h);
1759 pFile->isOpen = 0;
1760 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001761 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00001762 return SQLITE_OK;
1763}
1764
1765
1766#pragma mark flock() style locking
1767
1768/*
1769 ** The flockLockingContext is not used
1770 */
1771typedef void flockLockingContext;
1772
danielk1977ad94b582007-08-20 06:44:22 +00001773static int flockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001774 unixFile *pFile = (unixFile*)id;
1775
1776 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001777 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001778 } else {
drh3b62b2f2007-06-08 18:27:03 +00001779 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001780 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1781 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001782 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001783 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00001784 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001785 }
drh3b62b2f2007-06-08 18:27:03 +00001786 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00001787 }
1788}
1789
danielk1977ad94b582007-08-20 06:44:22 +00001790static int flockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001791 unixFile *pFile = (unixFile*)id;
1792
drh3b62b2f2007-06-08 18:27:03 +00001793 /* if we already have a lock, it is exclusive.
1794 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001795 if (pFile->locktype > NO_LOCK) {
1796 pFile->locktype = locktype;
1797 return SQLITE_OK;
1798 }
1799
drh3b62b2f2007-06-08 18:27:03 +00001800 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001801 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1802 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00001803 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00001804 return SQLITE_BUSY;
1805 } else {
drh3b62b2f2007-06-08 18:27:03 +00001806 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001807 pFile->locktype = locktype;
1808 return SQLITE_OK;
1809 }
1810}
1811
danielk1977ad94b582007-08-20 06:44:22 +00001812static int flockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001813 unixFile *pFile = (unixFile*)id;
1814
1815 assert( locktype<=SHARED_LOCK );
1816
drh3b62b2f2007-06-08 18:27:03 +00001817 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001818 if( pFile->locktype==locktype ){
1819 return SQLITE_OK;
1820 }
1821
drh3b62b2f2007-06-08 18:27:03 +00001822 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001823 if (locktype==SHARED_LOCK) {
1824 pFile->locktype = locktype;
1825 return SQLITE_OK;
1826 }
1827
drh3b62b2f2007-06-08 18:27:03 +00001828 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001829 int rc = flock(pFile->h, LOCK_UN);
1830 if (rc)
1831 return SQLITE_IOERR_UNLOCK;
1832 else {
1833 pFile->locktype = NO_LOCK;
1834 return SQLITE_OK;
1835 }
1836}
1837
1838/*
1839 ** Close a file.
1840 */
danielk1977ad94b582007-08-20 06:44:22 +00001841static int flockUnixClose(sqlite3_file *pId) {
1842 unixFile *pFile = (unixFile*)*pId;
drhbfe66312006-10-03 17:40:40 +00001843
danielk1977ad94b582007-08-20 06:44:22 +00001844 if( !pFile ) return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001845 flockUnixUnlock(*pId, NO_LOCK);
1846
danielk1977ad94b582007-08-20 06:44:22 +00001847 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1848 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001849 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001850
danielk1977ad94b582007-08-20 06:44:22 +00001851 close(pFile->h);
danielk1977b4b47412007-08-17 15:53:36 +00001852 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001853 pFile->isOpen = 0;
1854 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001855 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00001856 return SQLITE_OK;
1857}
1858
1859#pragma mark Old-School .lock file based locking
1860
1861/*
1862 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
1863 ** specific state
1864 */
1865typedef struct dotlockLockingContext dotlockLockingContext;
1866struct dotlockLockingContext {
1867 char *lockPath;
1868};
1869
1870
danielk1977ad94b582007-08-20 06:44:22 +00001871static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001872 unixFile *pFile = (unixFile*)id;
1873 dotlockLockingContext *context =
1874 (dotlockLockingContext *) pFile->lockingContext;
1875
1876 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001877 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001878 } else {
1879 struct stat statBuf;
1880 if (lstat(context->lockPath,&statBuf) == 0)
drh3b62b2f2007-06-08 18:27:03 +00001881 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00001882 return 1;
1883 else
drh3b62b2f2007-06-08 18:27:03 +00001884 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00001885 return 0;
1886 }
1887}
1888
danielk1977ad94b582007-08-20 06:44:22 +00001889static int dotlockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001890 unixFile *pFile = (unixFile*)id;
1891 dotlockLockingContext *context =
1892 (dotlockLockingContext *) pFile->lockingContext;
1893
drh3b62b2f2007-06-08 18:27:03 +00001894 /* if we already have a lock, it is exclusive.
1895 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001896 if (pFile->locktype > NO_LOCK) {
1897 pFile->locktype = locktype;
1898
1899 /* Always update the timestamp on the old file */
1900 utimes(context->lockPath,NULL);
1901 return SQLITE_OK;
1902 }
1903
drh3b62b2f2007-06-08 18:27:03 +00001904 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00001905 struct stat statBuf;
1906 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001907 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00001908 }
1909
drh3b62b2f2007-06-08 18:27:03 +00001910 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001911 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
1912 if (fd < 0) {
drh3b62b2f2007-06-08 18:27:03 +00001913 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00001914 return SQLITE_BUSY;
1915 }
1916 close(fd);
1917
drh3b62b2f2007-06-08 18:27:03 +00001918 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001919 pFile->locktype = locktype;
1920 return SQLITE_OK;
1921}
1922
danielk1977ad94b582007-08-20 06:44:22 +00001923static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001924 unixFile *pFile = (unixFile*)id;
1925 dotlockLockingContext *context =
1926 (dotlockLockingContext *) pFile->lockingContext;
1927
1928 assert( locktype<=SHARED_LOCK );
1929
drh3b62b2f2007-06-08 18:27:03 +00001930 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001931 if( pFile->locktype==locktype ){
1932 return SQLITE_OK;
1933 }
1934
drh3b62b2f2007-06-08 18:27:03 +00001935 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001936 if (locktype==SHARED_LOCK) {
1937 pFile->locktype = locktype;
1938 return SQLITE_OK;
1939 }
1940
drh3b62b2f2007-06-08 18:27:03 +00001941 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001942 unlink(context->lockPath);
1943 pFile->locktype = NO_LOCK;
1944 return SQLITE_OK;
1945}
1946
1947/*
1948 ** Close a file.
1949 */
danielk1977ad94b582007-08-20 06:44:22 +00001950static int dotlockUnixClose(sqlite3_file *id) {
1951 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001952
danielk1977ad94b582007-08-20 06:44:22 +00001953 if( !pFile ) return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001954 dotlockUnixUnlock(*pId, NO_LOCK);
1955 /* free the dotlock locking structure */
danielk1977ad94b582007-08-20 06:44:22 +00001956 if (pFile->lockingContext != NULL) {
1957 if (((dotlockLockingContext *)pFile->lockingContext)->lockPath != NULL)
drh17435752007-08-16 04:30:38 +00001958 sqlite3_free( ( (dotlockLockingContext *)
danielk1977ad94b582007-08-20 06:44:22 +00001959 pFile->lockingContext)->lockPath);
1960 sqlite3_free(pFile->lockingContext);
drhbfe66312006-10-03 17:40:40 +00001961 }
1962
danielk1977ad94b582007-08-20 06:44:22 +00001963 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1964 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001965 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001966
danielk1977ad94b582007-08-20 06:44:22 +00001967 close(pFile->h);
drhbfe66312006-10-03 17:40:40 +00001968
danielk1977b4b47412007-08-17 15:53:36 +00001969 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001970 pFile->isOpen = 0;
1971 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001972 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00001973 return SQLITE_OK;
1974}
1975
1976
1977#pragma mark No locking
1978
1979/*
1980 ** The nolockLockingContext is void
1981 */
1982typedef void nolockLockingContext;
1983
danielk1977ad94b582007-08-20 06:44:22 +00001984static int nolockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001985 return 0;
1986}
1987
danielk1977ad94b582007-08-20 06:44:22 +00001988static int nolockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001989 return SQLITE_OK;
1990}
1991
danielk1977ad94b582007-08-20 06:44:22 +00001992static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001993 return SQLITE_OK;
1994}
1995
1996/*
1997 ** Close a file.
1998 */
danielk1977ad94b582007-08-20 06:44:22 +00001999static int nolockUnixClose(sqlite3_file *id) {
2000 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00002001
danielk1977ad94b582007-08-20 06:44:22 +00002002 if( !pFile ) return SQLITE_OK;
2003 if( pFile->dirfd>=0 ) close(pFile->dirfd);
2004 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00002005 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002006
danielk1977ad94b582007-08-20 06:44:22 +00002007 close(pFile->h);
drhbfe66312006-10-03 17:40:40 +00002008
danielk1977b4b47412007-08-17 15:53:36 +00002009 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002010 pFile->isOpen = 0;
2011 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00002012 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00002013 return SQLITE_OK;
2014}
2015
2016#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2017
danielk1977ad94b582007-08-20 06:44:22 +00002018
danielk1977e3026632004-06-22 11:29:02 +00002019/*
danielk1977ad94b582007-08-20 06:44:22 +00002020** TODO: xBreakLock() for this vfs.
drh18839212005-11-26 03:43:23 +00002021*/
danielk1977ad94b582007-08-20 06:44:22 +00002022static int unixBreakLock(sqlite3_file *id){
2023 assert(!"TODO: unixBreakLock()");
2024 return 0;
drh9cbe6352005-11-29 03:13:21 +00002025}
2026
2027/*
danielk1977ad94b582007-08-20 06:44:22 +00002028** Return an integer that indices the type of lock currently held
2029** by this handle. (Used for testing and analysis only.)
drh9cbe6352005-11-29 03:13:21 +00002030*/
danielk1977ad94b582007-08-20 06:44:22 +00002031static int unixLockState(sqlite3_file *id){
2032 return ((unixFile*)id)->locktype;
drh9cbe6352005-11-29 03:13:21 +00002033}
2034
drh9c06c952005-11-26 00:25:00 +00002035/*
danielk1977a3d4c882007-03-23 10:08:38 +00002036** Return the sector size in bytes of the underlying block device for
2037** the specified file. This is almost always 512 bytes, but may be
2038** larger for some devices.
2039**
2040** SQLite code assumes this function cannot fail. It also assumes that
2041** if two files are created in the same file-system directory (i.e.
2042** a database and it's journal file) that the sector size will be the
2043** same for both.
2044*/
danielk197762079062007-08-15 17:08:46 +00002045static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002046 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002047}
2048
danielk197790949c22007-08-17 16:50:38 +00002049/*
2050** Return the device characteristics for the file. This is always 0.
2051*/
danielk197762079062007-08-15 17:08:46 +00002052static int unixDeviceCharacteristics(sqlite3_file *id){
2053 return 0;
2054}
2055
danielk1977a3d4c882007-03-23 10:08:38 +00002056/*
danielk1977ad94b582007-08-20 06:44:22 +00002057** This vector defines all the methods that can operate on an sqlite3_file
drh054889e2005-11-30 03:20:31 +00002058** for unix.
drh9c06c952005-11-26 00:25:00 +00002059*/
danielk197762079062007-08-15 17:08:46 +00002060static const sqlite3_io_methods sqlite3UnixIoMethod = {
2061 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002062 unixClose,
2063 unixRead,
2064 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002065 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002066 unixSync,
drh054889e2005-11-30 03:20:31 +00002067 unixFileSize,
2068 unixLock,
2069 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002070 unixCheckReservedLock,
danielk197762079062007-08-15 17:08:46 +00002071 unixBreakLock,
danielk197790949c22007-08-17 16:50:38 +00002072 unixLockState,
danielk1977a3d4c882007-03-23 10:08:38 +00002073 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002074 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002075};
2076
drhbfe66312006-10-03 17:40:40 +00002077#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002078/*
danielk1977ad94b582007-08-20 06:44:22 +00002079** This vector defines all the methods that can operate on an sqlite3_file
2080** for unix with AFP style file locking.
2081*/
2082static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
2083 1, /* iVersion */
2084 unixClose,
drhbfe66312006-10-03 17:40:40 +00002085 unixRead,
2086 unixWrite,
drhbfe66312006-10-03 17:40:40 +00002087 unixTruncate,
2088 unixSync,
danielk1977ad94b582007-08-20 06:44:22 +00002089 unixFileSize,
2090 afpUnixLock,
2091 afpUnixUnlock,
2092 afpUnixCheckReservedLock,
2093 unixBreakLock,
2094 unixLockState,
2095 unixSectorSize,
2096 unixDeviceCharacteristics
2097};
2098
2099/*
2100** This vector defines all the methods that can operate on an sqlite3_file
2101** for unix with flock() style file locking.
2102*/
2103static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
2104 1, /* iVersion */
2105 flockUnixClose,
2106 unixRead,
2107 unixWrite,
2108 unixTruncate,
2109 unixSync,
2110 unixFileSize,
2111 flockUnixLock,
2112 flockUnixUnlock,
2113 flockUnixCheckReservedLock,
2114 unixBreakLock,
2115 unixLockState,
2116 unixSectorSize,
2117 unixDeviceCharacteristics
2118};
2119
2120/*
2121** This vector defines all the methods that can operate on an sqlite3_file
2122** for unix with dotlock style file locking.
2123*/
2124static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
2125 1, /* iVersion */
2126 dotlockUnixClose,
2127 unixRead,
2128 unixWrite,
2129 unixTruncate,
2130 unixSync,
2131 unixFileSize,
2132 dotlockUnixLock,
2133 dotlockUnixUnlock,
2134 dotlockUnixCheckReservedLock,
2135 unixBreakLock,
2136 unixLockState,
2137 unixSectorSize,
2138 unixDeviceCharacteristics
2139};
2140
2141/*
2142** This vector defines all the methods that can operate on an sqlite3_file
2143** for unix with dotlock style file locking.
2144*/
2145static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
2146 1, /* iVersion */
2147 nolockUnixClose,
2148 unixRead,
2149 unixWrite,
2150 unixTruncate,
2151 unixSync,
drhbfe66312006-10-03 17:40:40 +00002152 unixFileSize,
2153 nolockUnixLock,
2154 nolockUnixUnlock,
drhbfe66312006-10-03 17:40:40 +00002155 nolockUnixCheckReservedLock,
danielk1977ad94b582007-08-20 06:44:22 +00002156 unixBreakLock,
2157 unixLockState,
danielk1977a3d4c882007-03-23 10:08:38 +00002158 unixSectorSize,
danielk1977ad94b582007-08-20 06:44:22 +00002159 unixDeviceCharacteristics
drhbfe66312006-10-03 17:40:40 +00002160};
2161
2162#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2163
2164/*
2165** Allocate memory for a new unixFile and initialize that unixFile.
2166** Write a pointer to the new unixFile into *pId.
2167** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002168*/
drhbfe66312006-10-03 17:40:40 +00002169#ifdef SQLITE_ENABLE_LOCKING_STYLE
2170/*
danielk1977ad94b582007-08-20 06:44:22 +00002171** When locking extensions are enabled, the filepath and locking style
2172** are needed to determine the unixFile pMethod to use for locking operations.
2173** The locking-style specific lockingContext data structure is created
2174** and assigned here also.
2175*/
2176static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002177 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002178 int dirfd, /* Directory file descriptor */
2179 sqlite3_file *pId, /* Write completed initialization here */
drhbfe66312006-10-03 17:40:40 +00002180 const char *zFilename, /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002181){
aswift108bc322006-10-11 17:19:46 +00002182 sqlite3LockingStyle lockingStyle;
danielk1977ad94b582007-08-20 06:44:22 +00002183 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002184 int rc;
2185
danielk1977ad94b582007-08-20 06:44:22 +00002186 memset(pNew, 0, sizeof(unixFile));
aswift448aa6f2006-11-11 01:31:58 +00002187 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drhbfe66312006-10-03 17:40:40 +00002188 if ( lockingStyle == posixLockingStyle ) {
danielk1977b4b47412007-08-17 15:53:36 +00002189 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002190 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002191 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002192 if( rc ){
2193 close(h);
2194 unlink(zFilename);
2195 return SQLITE_NOMEM;
2196 }
2197 } else {
drh3b62b2f2007-06-08 18:27:03 +00002198 /* pLock and pOpen are only used for posix advisory locking */
danielk1977ad94b582007-08-20 06:44:22 +00002199 pNew->pLock = NULL;
2200 pNew->pOpen = NULL;
drhbfe66312006-10-03 17:40:40 +00002201 }
danielk1977ad94b582007-08-20 06:44:22 +00002202 pNew->dirfd = -1;
2203 pNew->h = h;
2204 SET_THREADID(pNew);
drh17435752007-08-16 04:30:38 +00002205 pNew = sqlite3_malloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00002206 if( pNew==0 ){
drhbfe66312006-10-03 17:40:40 +00002207 close(h);
danielk1977b4b47412007-08-17 15:53:36 +00002208 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002209 releaseLockInfo(pNew->pLock);
2210 releaseOpenCnt(pNew->pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002211 leaveMutex();
drh054889e2005-11-30 03:20:31 +00002212 return SQLITE_NOMEM;
2213 }else{
aswift108bc322006-10-11 17:19:46 +00002214 switch(lockingStyle) {
drh5bb3eb92007-05-04 13:15:55 +00002215 case afpLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002216 /* afp locking uses the file path so it needs to be included in
2217 ** the afpLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002218 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002219 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
2220 pNew->lockingContext =
drh17435752007-08-16 04:30:38 +00002221 sqlite3_malloc(sizeof(afpLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002222 nFilename = strlen(zFilename)+1;
drhbfe66312006-10-03 17:40:40 +00002223 ((afpLockingContext *)pNew->lockingContext)->filePath =
drh17435752007-08-16 04:30:38 +00002224 sqlite3_malloc(nFilename);
drh5bb3eb92007-05-04 13:15:55 +00002225 memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
2226 zFilename, nFilename);
drhbfe66312006-10-03 17:40:40 +00002227 srandomdev();
2228 break;
drh5bb3eb92007-05-04 13:15:55 +00002229 }
drhbfe66312006-10-03 17:40:40 +00002230 case flockLockingStyle:
2231 /* flock locking doesn't need additional lockingContext information */
2232 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2233 break;
drh5bb3eb92007-05-04 13:15:55 +00002234 case dotlockLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002235 /* dotlock locking uses the file path so it needs to be included in
2236 ** the dotlockLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002237 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002238 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh17435752007-08-16 04:30:38 +00002239 pNew->lockingContext = sqlite3_malloc(
drhbfe66312006-10-03 17:40:40 +00002240 sizeof(dotlockLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002241 nFilename = strlen(zFilename) + 6;
drhbfe66312006-10-03 17:40:40 +00002242 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
drh17435752007-08-16 04:30:38 +00002243 sqlite3_malloc( nFilename );
drh5bb3eb92007-05-04 13:15:55 +00002244 sqlite3_snprintf(nFilename,
2245 ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
drhbfe66312006-10-03 17:40:40 +00002246 "%s.lock", zFilename);
2247 break;
drh5bb3eb92007-05-04 13:15:55 +00002248 }
drhbfe66312006-10-03 17:40:40 +00002249 case posixLockingStyle:
2250 /* posix locking doesn't need additional lockingContext information */
2251 pNew->pMethod = &sqlite3UnixIoMethod;
2252 break;
2253 case noLockingStyle:
2254 case unsupportedLockingStyle:
2255 default:
2256 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
2257 }
drhbfe66312006-10-03 17:40:40 +00002258 OpenCounter(+1);
2259 return SQLITE_OK;
2260 }
2261}
2262#else /* SQLITE_ENABLE_LOCKING_STYLE */
danielk1977b4b47412007-08-17 15:53:36 +00002263static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002264 int h, /* Open file descriptor on file being opened */
danielk1977fee2d252007-08-18 10:59:19 +00002265 int dirfd,
danielk1977b4b47412007-08-17 15:53:36 +00002266 sqlite3_file *pId, /* Write to the unixFile structure here */
2267 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002268){
danielk1977b4b47412007-08-17 15:53:36 +00002269 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002270 int rc;
2271
drhe78669b2007-06-29 12:04:26 +00002272#ifdef FD_CLOEXEC
2273 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2274#endif
danielk1977b4b47412007-08-17 15:53:36 +00002275
2276 enterMutex();
2277 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2278 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002279 if( rc ){
2280 close(h);
2281 return SQLITE_NOMEM;
2282 }
danielk1977b4b47412007-08-17 15:53:36 +00002283
drh4f0c5872007-03-26 22:05:01 +00002284 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977b4b47412007-08-17 15:53:36 +00002285 pNew->dirfd = -1;
2286 pNew->h = h;
danielk1977fee2d252007-08-18 10:59:19 +00002287 pNew->dirfd = dirfd;
danielk1977b4b47412007-08-17 15:53:36 +00002288 SET_THREADID(pNew);
2289
2290 pNew->pMethod = &sqlite3UnixIoMethod;
2291 OpenCounter(+1);
2292 return SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00002293}
drhbfe66312006-10-03 17:40:40 +00002294#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002295
danielk1977ad94b582007-08-20 06:44:22 +00002296/*
2297** Open a file descriptor to the directory containing file zFilename.
2298** If successful, *pFd is set to the opened file descriptor and
2299** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2300** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2301** value.
2302**
2303** If SQLITE_OK is returned, the caller is responsible for closing
2304** the file descriptor *pFd using close().
2305*/
danielk1977fee2d252007-08-18 10:59:19 +00002306static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002307 int ii;
2308 int fd;
drhf3a65f72007-08-22 20:18:21 +00002309 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002310
drh153c62c2007-08-24 03:51:33 +00002311 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002312 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2313 if( ii>0 ){
2314 zDirname[ii] = '\0';
2315 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
2316 if( fd>0 ){
2317#ifdef FD_CLOEXEC
2318 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2319#endif
2320 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2321 }
2322 }
danielk1977fee2d252007-08-18 10:59:19 +00002323 *pFd = fd;
2324 return (fd>0?SQLITE_OK:SQLITE_CANTOPEN);
2325}
2326
danielk1977b4b47412007-08-17 15:53:36 +00002327/*
danielk1977ad94b582007-08-20 06:44:22 +00002328** Open the file zPath.
2329**
danielk1977b4b47412007-08-17 15:53:36 +00002330** Previously, the SQLite OS layer used three functions in place of this
2331** one:
2332**
2333** sqlite3OsOpenReadWrite();
2334** sqlite3OsOpenReadOnly();
2335** sqlite3OsOpenExclusive();
2336**
2337** These calls correspond to the following combinations of flags:
2338**
2339** ReadWrite() -> (READWRITE | CREATE)
2340** ReadOnly() -> (READONLY)
2341** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2342**
2343** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2344** true, the file was configured to be automatically deleted when the
2345** file handle closed. To achieve the same effect using this new
2346** interface, add the DELETEONCLOSE flag to those specified above for
2347** OpenExclusive().
2348*/
2349static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00002350 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00002351 const char *zPath,
2352 sqlite3_file *pFile,
2353 int flags,
2354 int *pOutFlags
2355){
danielk1977fee2d252007-08-18 10:59:19 +00002356 int fd = 0; /* File descriptor returned by open() */
2357 int dirfd = -1; /* Directory file descriptor */
2358 int oflags = 0; /* Flags to pass to open() */
2359 int eType = flags&0xFFFFFF00; /* Type of file to open */
danielk1977b4b47412007-08-17 15:53:36 +00002360
2361 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2362 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2363 int isCreate = (flags & SQLITE_OPEN_CREATE);
2364 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2365 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2366
danielk1977fee2d252007-08-18 10:59:19 +00002367 /* If creating a master or main-file journal, this function will open
2368 ** a file-descriptor on the directory too. The first time unixSync()
2369 ** is called the directory file descriptor will be fsync()ed and close()d.
2370 */
2371 int isOpenDirectory = (isCreate &&
2372 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
2373 );
2374
2375 /* Check the following statements are true:
2376 **
2377 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2378 ** (b) if CREATE is set, then READWRITE must also be set, and
2379 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
2380 */
danielk1977b4b47412007-08-17 15:53:36 +00002381 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00002382 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00002383 assert(isExclusive==0 || isCreate);
2384
danielk1977fee2d252007-08-18 10:59:19 +00002385 /* Assert that the upper layer has set one of the "file-type" flags. */
2386 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2387 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2388 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
2389 );
2390
danielk1977b4b47412007-08-17 15:53:36 +00002391 if( isReadonly ) oflags |= O_RDONLY;
2392 if( isReadWrite ) oflags |= O_RDWR;
2393 if( isCreate ) oflags |= O_CREAT;
2394 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2395 oflags |= (O_LARGEFILE|O_BINARY);
2396
2397 memset(pFile, 0, sizeof(unixFile));
2398 fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
2399 if( fd<0 && isReadWrite && !isExclusive ){
2400 /* Failed to open the file for read/write access. Try read-only. */
2401 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2402 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00002403 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00002404 }
2405 if( fd<0 ){
2406 return SQLITE_CANTOPEN;
2407 }
2408 if( isDelete ){
2409 unlink(zPath);
2410 }
2411 if( pOutFlags ){
2412 *pOutFlags = flags;
2413 }
2414
2415 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00002416 if( isOpenDirectory ){
2417 int rc = openDirectory(zPath, &dirfd);
2418 if( rc!=SQLITE_OK ){
2419 close(fd);
2420 return rc;
2421 }
2422 }
2423 return fillInUnixFile(fd, dirfd, pFile, zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002424}
2425
2426/*
danielk1977fee2d252007-08-18 10:59:19 +00002427** Delete the file at zPath. If the dirSync argument is true, fsync()
2428** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00002429*/
drh153c62c2007-08-24 03:51:33 +00002430static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00002431 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002432 SimulateIOError(return SQLITE_IOERR_DELETE);
2433 unlink(zPath);
danielk1977fee2d252007-08-18 10:59:19 +00002434 if( dirSync ){
2435 int fd;
2436 rc = openDirectory(zPath, &fd);
2437 if( rc==SQLITE_OK ){
2438 if( fsync(fd) ){
2439 rc = SQLITE_IOERR_DIR_FSYNC;
2440 }
2441 close(fd);
2442 }
2443 }
2444 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00002445}
2446
danielk197790949c22007-08-17 16:50:38 +00002447/*
2448** Test the existance of or access permissions of file zPath. The
2449** test performed depends on the value of flags:
2450**
2451** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2452** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2453** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2454**
2455** Otherwise return 0.
2456*/
drh153c62c2007-08-24 03:51:33 +00002457static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
danielk1977b4b47412007-08-17 15:53:36 +00002458 int amode;
2459 switch( flags ){
2460 case SQLITE_ACCESS_EXISTS:
2461 amode = F_OK;
2462 break;
2463 case SQLITE_ACCESS_READWRITE:
2464 amode = W_OK|R_OK;
2465 break;
2466 case SQLITE_ACCESS_READONLY:
2467 amode = R_OK;
2468 break;
2469
2470 default:
2471 assert(!"Invalid flags argument");
2472 }
2473 return (access(zPath, amode)==0);
2474}
2475
2476/*
drh153c62c2007-08-24 03:51:33 +00002477** Create a temporary file name in zBuf. zBuf must be allocated
2478** by the calling process and must be big enough to hold at least
2479** pVfs->mxPathname bytes.
danielk1977b4b47412007-08-17 15:53:36 +00002480*/
drh153c62c2007-08-24 03:51:33 +00002481static int unixGetTempName(sqlite3_vfs *pVfs, char *zBuf){
danielk1977b4b47412007-08-17 15:53:36 +00002482 static const char *azDirs[] = {
2483 0,
2484 "/var/tmp",
2485 "/usr/tmp",
2486 "/tmp",
2487 ".",
2488 };
2489 static const unsigned char zChars[] =
2490 "abcdefghijklmnopqrstuvwxyz"
2491 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2492 "0123456789";
2493 int i, j;
2494 struct stat buf;
2495 const char *zDir = ".";
2496 azDirs[0] = sqlite3_temp_directory;
2497 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2498 if( azDirs[i]==0 ) continue;
2499 if( stat(azDirs[i], &buf) ) continue;
2500 if( !S_ISDIR(buf.st_mode) ) continue;
2501 if( access(azDirs[i], 07) ) continue;
2502 zDir = azDirs[i];
2503 break;
2504 }
2505 do{
drh153c62c2007-08-24 03:51:33 +00002506 assert( pVfs->mxPathname==MAX_PATHNAME );
2507 sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
danielk1977b4b47412007-08-17 15:53:36 +00002508 j = strlen(zBuf);
2509 sqlite3Randomness(15, &zBuf[j]);
2510 for(i=0; i<15; i++, j++){
2511 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2512 }
2513 zBuf[j] = 0;
2514 }while( access(zBuf,0)==0 );
2515 return SQLITE_OK;
2516}
2517
2518
2519/*
2520** Turn a relative pathname into a full pathname. The relative path
2521** is stored as a nul-terminated string in the buffer pointed to by
2522** zPath.
2523**
2524** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2525** (in this case, MAX_PATHNAME bytes). The full-path is written to
2526** this buffer before returning.
2527*/
drh153c62c2007-08-24 03:51:33 +00002528static int unixFullPathname(sqlite3_vfs *pVfs, const char *zPath, char *zOut){
2529 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977b4b47412007-08-17 15:53:36 +00002530 zOut[MAX_PATHNAME-1] = '\0';
2531 if( zPath[0]=='/' ){
drh153c62c2007-08-24 03:51:33 +00002532 sqlite3_snprintf(MAX_PATHNAME, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002533 }else{
2534 int nCwd;
2535 if( getcwd(zOut, MAX_PATHNAME-1)==0 ){
2536 return SQLITE_ERROR;
2537 }
2538 nCwd = strlen(zOut);
drh153c62c2007-08-24 03:51:33 +00002539 sqlite3_snprintf(MAX_PATHNAME-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002540 }
2541 return SQLITE_OK;
2542
2543#if 0
2544 /*
2545 ** Remove "/./" path elements and convert "/A/./" path elements
2546 ** to just "/".
2547 */
2548 if( zFull ){
2549 int i, j;
2550 for(i=j=0; zFull[i]; i++){
2551 if( zFull[i]=='/' ){
2552 if( zFull[i+1]=='/' ) continue;
2553 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2554 i += 1;
2555 continue;
2556 }
2557 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2558 while( j>0 && zFull[j-1]!='/' ){ j--; }
2559 i += 3;
2560 continue;
2561 }
2562 }
2563 zFull[j++] = zFull[i];
2564 }
2565 zFull[j] = 0;
2566 }
2567#endif
2568}
2569
drh0ccebe72005-06-07 22:22:50 +00002570
drh761df872006-12-21 01:29:22 +00002571#ifndef SQLITE_OMIT_LOAD_EXTENSION
2572/*
2573** Interfaces for opening a shared library, finding entry points
2574** within the shared library, and closing the shared library.
2575*/
2576#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00002577static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002578 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2579}
drh153c62c2007-08-24 03:51:33 +00002580static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00002581 char *zErr;
2582 enterMutex();
2583 zErr = dlerror();
2584 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00002585 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00002586 }else if(nBuf>0) {
2587 zBufOut[0] = '\0';
2588 }
2589 leaveMutex();
2590}
drh153c62c2007-08-24 03:51:33 +00002591void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002592 return dlsym(pHandle, zSymbol);
2593}
drh153c62c2007-08-24 03:51:33 +00002594void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00002595 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002596}
danielk1977b4b47412007-08-17 15:53:36 +00002597#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2598 #define unixDlOpen 0
2599 #define unixDlError 0
2600 #define unixDlSym 0
2601 #define unixDlClose 0
2602#endif
2603
2604/*
danielk197790949c22007-08-17 16:50:38 +00002605** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002606*/
drh153c62c2007-08-24 03:51:33 +00002607static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002608
2609 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2610
drhbbd42a62004-05-22 17:41:58 +00002611 /* We have to initialize zBuf to prevent valgrind from reporting
2612 ** errors. The reports issued by valgrind are incorrect - we would
2613 ** prefer that the randomness be increased by making use of the
2614 ** uninitialized space in zBuf - but valgrind errors tend to worry
2615 ** some users. Rather than argue, it seems easier just to initialize
2616 ** the whole array and silence valgrind, even if that means less randomness
2617 ** in the random seed.
2618 **
2619 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002620 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002621 ** tests repeatable.
2622 */
danielk1977b4b47412007-08-17 15:53:36 +00002623 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002624#if !defined(SQLITE_TEST)
2625 {
drh842b8642005-01-21 17:53:17 +00002626 int pid, fd;
2627 fd = open("/dev/urandom", O_RDONLY);
2628 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002629 time_t t;
2630 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002631 memcpy(zBuf, &t, sizeof(t));
2632 pid = getpid();
2633 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002634 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002635 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002636 close(fd);
2637 }
drhbbd42a62004-05-22 17:41:58 +00002638 }
2639#endif
2640 return SQLITE_OK;
2641}
2642
danielk1977b4b47412007-08-17 15:53:36 +00002643
drhbbd42a62004-05-22 17:41:58 +00002644/*
2645** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002646** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00002647** The return value is the number of microseconds of sleep actually
2648** requested from the underlying operating system, a number which
2649** might be greater than or equal to the argument, but not less
2650** than the argument.
drhbbd42a62004-05-22 17:41:58 +00002651*/
drh153c62c2007-08-24 03:51:33 +00002652static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002653#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002654 usleep(microseconds);
2655 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002656#else
danielk1977b4b47412007-08-17 15:53:36 +00002657 int seconds = (microseconds+999999)/1000000;
2658 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00002659 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00002660#endif
drh88f474a2006-01-02 20:00:12 +00002661}
2662
2663/*
drhbbd42a62004-05-22 17:41:58 +00002664** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002665** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002666*/
2667#ifdef SQLITE_TEST
2668int sqlite3_current_time = 0;
2669#endif
2670
2671/*
2672** Find the current time (in Universal Coordinated Time). Write the
2673** current time and date as a Julian Day number into *prNow and
2674** return 0. Return 1 if the time and date cannot be found.
2675*/
drh153c62c2007-08-24 03:51:33 +00002676static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002677#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002678 time_t t;
2679 time(&t);
2680 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002681#else
2682 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002683 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002684 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2685#endif
drhbbd42a62004-05-22 17:41:58 +00002686#ifdef SQLITE_TEST
2687 if( sqlite3_current_time ){
2688 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2689 }
2690#endif
2691 return 0;
2692}
danielk1977b4b47412007-08-17 15:53:36 +00002693
drh153c62c2007-08-24 03:51:33 +00002694/*
2695** Return a pointer to the sqlite3DefaultVfs structure. We use
2696** a function rather than give the structure global scope because
2697** some compilers (MSVC) do not allow forward declarations of
2698** initialized structures.
2699*/
2700sqlite3_vfs *sqlite3OsDefaultVfs(void){
2701 static sqlite3_vfs unixVfs = {
2702 1, /* iVersion */
2703 sizeof(unixFile), /* szOsFile */
2704 MAX_PATHNAME, /* mxPathname */
drh153c62c2007-08-24 03:51:33 +00002705 0, /* pNext */
2706 "unix", /* zName */
2707 0, /* pAppData */
2708
2709 unixOpen, /* xOpen */
2710 unixDelete, /* xDelete */
2711 unixAccess, /* xAccess */
2712 unixGetTempName, /* xGetTempName */
2713 unixFullPathname, /* xFullPathname */
2714 unixDlOpen, /* xDlOpen */
2715 unixDlError, /* xDlError */
2716 unixDlSym, /* xDlSym */
2717 unixDlClose, /* xDlClose */
2718 unixRandomness, /* xRandomness */
2719 unixSleep, /* xSleep */
2720 unixCurrentTime /* xCurrentTime */
2721 };
2722
2723 return &unixVfs;
2724}
drhdce8bdb2007-08-16 13:01:44 +00002725
drhbbd42a62004-05-22 17:41:58 +00002726#endif /* OS_UNIX */