blob: a1a0041e9b2d9e0782608e6e7a54b85e7583e296 [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
danielk1977c16d4632007-08-30 14:49:58 +0000988 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
danielk1977f036aef2007-08-20 05:36:51 +0000989 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
990 || (flags&0x0F)==SQLITE_SYNC_FULL
danielk1977f036aef2007-08-20 05:36:51 +0000991 );
danielk197790949c22007-08-17 16:50:38 +0000992
drh054889e2005-11-30 03:20:31 +0000993 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +0000994 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +0000995 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +0000996 SimulateIOError( rc=1 );
997 if( rc ){
drh4ac285a2006-09-15 07:28:50 +0000998 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +0000999 }
drh054889e2005-11-30 03:20:31 +00001000 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001001 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001002 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001003#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001004 /* The directory sync is only attempted if full_fsync is
1005 ** turned off or unavailable. If a full_fsync occurred above,
1006 ** then the directory sync is superfluous.
1007 */
danielk197790949c22007-08-17 16:50:38 +00001008 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001009 /*
1010 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001011 ** errors when applied to directories on certain file systems.
1012 ** A failed directory sync is not a big deal. So it seems
1013 ** better to ignore the error. Ticket #1657
1014 */
1015 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001016 }
danielk1977d7c03f72005-11-25 10:38:22 +00001017#endif
drh054889e2005-11-30 03:20:31 +00001018 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1019 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001020 }
drha2854222004-06-17 19:04:17 +00001021 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001022}
1023
1024/*
1025** Truncate an open file to a specified size
1026*/
danielk197762079062007-08-15 17:08:46 +00001027static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001028 int rc;
drh9cbe6352005-11-29 03:13:21 +00001029 assert( id );
drh63fff5f2007-06-19 10:50:38 +00001030 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001031 SimulateIOError( rc=1 );
1032 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001033 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001034 }else{
1035 return SQLITE_OK;
1036 }
drhbbd42a62004-05-22 17:41:58 +00001037}
1038
1039/*
1040** Determine the current size of a file in bytes
1041*/
danielk197762079062007-08-15 17:08:46 +00001042static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001043 int rc;
drhbbd42a62004-05-22 17:41:58 +00001044 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001045 assert( id );
drh59685932006-09-14 13:47:11 +00001046 rc = fstat(((unixFile*)id)->h, &buf);
1047 SimulateIOError( rc=1 );
1048 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001049 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001050 }
1051 *pSize = buf.st_size;
1052 return SQLITE_OK;
1053}
1054
danielk19779a1d0ab2004-06-01 14:09:28 +00001055/*
danielk197713adf8a2004-06-03 16:08:41 +00001056** This routine checks if there is a RESERVED lock held on the specified
1057** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001058** non-zero. If the file is unlocked or holds only SHARED locks, then
1059** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001060*/
danielk197762079062007-08-15 17:08:46 +00001061static int unixCheckReservedLock(sqlite3_file *id){
danielk197713adf8a2004-06-03 16:08:41 +00001062 int r = 0;
drh054889e2005-11-30 03:20:31 +00001063 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001064
drh054889e2005-11-30 03:20:31 +00001065 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001066 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001067
1068 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001069 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001070 r = 1;
1071 }
1072
drh2ac3ee92004-06-07 16:27:46 +00001073 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001074 */
1075 if( !r ){
1076 struct flock lock;
1077 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001078 lock.l_start = RESERVED_BYTE;
1079 lock.l_len = 1;
1080 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001081 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001082 if( lock.l_type!=F_UNLCK ){
1083 r = 1;
1084 }
1085 }
1086
danielk1977b4b47412007-08-17 15:53:36 +00001087 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001088 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001089
1090 return r;
1091}
1092
1093/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001094** Lock the file with the lock specified by parameter locktype - one
1095** of the following:
1096**
drh2ac3ee92004-06-07 16:27:46 +00001097** (1) SHARED_LOCK
1098** (2) RESERVED_LOCK
1099** (3) PENDING_LOCK
1100** (4) EXCLUSIVE_LOCK
1101**
drhb3e04342004-06-08 00:47:47 +00001102** Sometimes when requesting one lock state, additional lock states
1103** are inserted in between. The locking might fail on one of the later
1104** transitions leaving the lock state different from what it started but
1105** still short of its goal. The following chart shows the allowed
1106** transitions and the inserted intermediate states:
1107**
1108** UNLOCKED -> SHARED
1109** SHARED -> RESERVED
1110** SHARED -> (PENDING) -> EXCLUSIVE
1111** RESERVED -> (PENDING) -> EXCLUSIVE
1112** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001113**
drha6abd042004-06-09 17:37:22 +00001114** This routine will only increase a lock. Use the sqlite3OsUnlock()
1115** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001116*/
danielk197762079062007-08-15 17:08:46 +00001117static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001118 /* The following describes the implementation of the various locks and
1119 ** lock transitions in terms of the POSIX advisory shared and exclusive
1120 ** lock primitives (called read-locks and write-locks below, to avoid
1121 ** confusion with SQLite lock names). The algorithms are complicated
1122 ** slightly in order to be compatible with windows systems simultaneously
1123 ** accessing the same database file, in case that is ever required.
1124 **
1125 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1126 ** byte', each single bytes at well known offsets, and the 'shared byte
1127 ** range', a range of 510 bytes at a well known offset.
1128 **
1129 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1130 ** byte'. If this is successful, a random byte from the 'shared byte
1131 ** range' is read-locked and the lock on the 'pending byte' released.
1132 **
danielk197790ba3bd2004-06-25 08:32:25 +00001133 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1134 ** A RESERVED lock is implemented by grabbing a write-lock on the
1135 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001136 **
1137 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001138 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1139 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1140 ** obtained, but existing SHARED locks are allowed to persist. A process
1141 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1142 ** This property is used by the algorithm for rolling back a journal file
1143 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001144 **
danielk197790ba3bd2004-06-25 08:32:25 +00001145 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1146 ** implemented by obtaining a write-lock on the entire 'shared byte
1147 ** range'. Since all other locks require a read-lock on one of the bytes
1148 ** within this range, this ensures that no other locks are held on the
1149 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001150 **
1151 ** The reason a single byte cannot be used instead of the 'shared byte
1152 ** range' is that some versions of windows do not support read-locks. By
1153 ** locking a random byte from a range, concurrent SHARED locks may exist
1154 ** even if the locking primitive used is always a write-lock.
1155 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001156 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001157 unixFile *pFile = (unixFile*)id;
1158 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001159 struct flock lock;
1160 int s;
1161
drh054889e2005-11-30 03:20:31 +00001162 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001163 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001164 locktypeName(locktype), locktypeName(pFile->locktype),
1165 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001166
1167 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001168 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001169 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001170 */
drh054889e2005-11-30 03:20:31 +00001171 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001172 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001173 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001174 return SQLITE_OK;
1175 }
1176
drhb3e04342004-06-08 00:47:47 +00001177 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001178 */
drh054889e2005-11-30 03:20:31 +00001179 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001180 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001181 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001182
drh054889e2005-11-30 03:20:31 +00001183 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001184 */
danielk1977b4b47412007-08-17 15:53:36 +00001185 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001186
drh029b44b2006-01-15 00:13:15 +00001187 /* Make sure the current thread owns the pFile.
1188 */
1189 rc = transferOwnership(pFile);
1190 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001191 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001192 return rc;
1193 }
drh64b1bea2006-01-15 02:30:57 +00001194 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001195
danielk1977ad94b582007-08-20 06:44:22 +00001196 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001197 ** handle that precludes the requested lock, return BUSY.
1198 */
drh054889e2005-11-30 03:20:31 +00001199 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001200 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001201 ){
1202 rc = SQLITE_BUSY;
1203 goto end_lock;
1204 }
1205
1206 /* If a SHARED lock is requested, and some thread using this PID already
1207 ** has a SHARED or RESERVED lock, then increment reference counts and
1208 ** return SQLITE_OK.
1209 */
1210 if( locktype==SHARED_LOCK &&
1211 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1212 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001213 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001214 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001215 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001216 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001217 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001218 goto end_lock;
1219 }
1220
danielk197713adf8a2004-06-03 16:08:41 +00001221 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001222
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 lock.l_whence = SEEK_SET;
1224
drh3cde3bb2004-06-12 02:17:14 +00001225 /* A PENDING lock is needed before acquiring a SHARED lock and before
1226 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1227 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 */
drh3cde3bb2004-06-12 02:17:14 +00001229 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001230 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001231 ){
danielk1977489468c2004-06-28 08:25:47 +00001232 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001233 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001234 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001235 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001236 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1237 goto end_lock;
1238 }
drh3cde3bb2004-06-12 02:17:14 +00001239 }
1240
1241
1242 /* If control gets to this point, then actually go ahead and make
1243 ** operating system calls for the specified lock.
1244 */
1245 if( locktype==SHARED_LOCK ){
1246 assert( pLock->cnt==0 );
1247 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001248
drh2ac3ee92004-06-07 16:27:46 +00001249 /* Now get the read-lock */
1250 lock.l_start = SHARED_FIRST;
1251 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001252 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001253
1254 /* Drop the temporary PENDING lock */
1255 lock.l_start = PENDING_BYTE;
1256 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001257 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001258 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001259 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001260 goto end_lock;
1261 }
drhe2396a12007-03-29 20:19:58 +00001262 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001263 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1264 }else{
drh054889e2005-11-30 03:20:31 +00001265 pFile->locktype = SHARED_LOCK;
1266 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001267 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001268 }
drh3cde3bb2004-06-12 02:17:14 +00001269 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1270 /* We are trying for an exclusive lock but another thread in this
1271 ** same process is still holding a shared lock. */
1272 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001273 }else{
drh3cde3bb2004-06-12 02:17:14 +00001274 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001275 ** assumed that there is a SHARED or greater lock on the file
1276 ** already.
1277 */
drh054889e2005-11-30 03:20:31 +00001278 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001279 lock.l_type = F_WRLCK;
1280 switch( locktype ){
1281 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001282 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001283 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001284 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001285 lock.l_start = SHARED_FIRST;
1286 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001287 break;
1288 default:
1289 assert(0);
1290 }
drh054889e2005-11-30 03:20:31 +00001291 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001292 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001293 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1294 }
drhbbd42a62004-05-22 17:41:58 +00001295 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001296
danielk1977ecb2a962004-06-02 06:30:16 +00001297 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001298 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001299 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001300 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001301 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001302 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001303 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001304
1305end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001306 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001307 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001308 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001309 return rc;
1310}
1311
1312/*
drh054889e2005-11-30 03:20:31 +00001313** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001314** must be either NO_LOCK or SHARED_LOCK.
1315**
1316** If the locking level of the file descriptor is already at or below
1317** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001318*/
danielk197762079062007-08-15 17:08:46 +00001319static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001320 struct lockInfo *pLock;
1321 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001322 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001323 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001324
drh054889e2005-11-30 03:20:31 +00001325 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001326 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001327 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001328
1329 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001330 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001331 return SQLITE_OK;
1332 }
drhf1a221e2006-01-15 17:27:17 +00001333 if( CHECK_THREADID(pFile) ){
1334 return SQLITE_MISUSE;
1335 }
danielk1977b4b47412007-08-17 15:53:36 +00001336 enterMutex();
drh054889e2005-11-30 03:20:31 +00001337 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001338 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001339 if( pFile->locktype>SHARED_LOCK ){
1340 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001341 if( locktype==SHARED_LOCK ){
1342 lock.l_type = F_RDLCK;
1343 lock.l_whence = SEEK_SET;
1344 lock.l_start = SHARED_FIRST;
1345 lock.l_len = SHARED_SIZE;
drhe2396a12007-03-29 20:19:58 +00001346 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
drh9c105bb2004-10-02 20:38:28 +00001347 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001348 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001349 }
1350 }
drhbbd42a62004-05-22 17:41:58 +00001351 lock.l_type = F_UNLCK;
1352 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001353 lock.l_start = PENDING_BYTE;
1354 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drhe2396a12007-03-29 20:19:58 +00001355 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001356 pLock->locktype = SHARED_LOCK;
1357 }else{
drh4ac285a2006-09-15 07:28:50 +00001358 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001359 }
drhbbd42a62004-05-22 17:41:58 +00001360 }
drha6abd042004-06-09 17:37:22 +00001361 if( locktype==NO_LOCK ){
1362 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001363
drha6abd042004-06-09 17:37:22 +00001364 /* Decrement the shared lock counter. Release the lock using an
1365 ** OS call only when all threads in this same process have released
1366 ** the lock.
1367 */
1368 pLock->cnt--;
1369 if( pLock->cnt==0 ){
1370 lock.l_type = F_UNLCK;
1371 lock.l_whence = SEEK_SET;
1372 lock.l_start = lock.l_len = 0L;
drhe2396a12007-03-29 20:19:58 +00001373 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001374 pLock->locktype = NO_LOCK;
1375 }else{
drh4ac285a2006-09-15 07:28:50 +00001376 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001377 }
drha6abd042004-06-09 17:37:22 +00001378 }
1379
drhbbd42a62004-05-22 17:41:58 +00001380 /* Decrement the count of locks against this same file. When the
1381 ** count reaches zero, close any other file descriptors whose close
1382 ** was deferred because of outstanding locks.
1383 */
drh054889e2005-11-30 03:20:31 +00001384 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001385 pOpen->nLock--;
1386 assert( pOpen->nLock>=0 );
1387 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1388 int i;
1389 for(i=0; i<pOpen->nPending; i++){
1390 close(pOpen->aPending[i]);
1391 }
drh64b1bea2006-01-15 02:30:57 +00001392 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001393 pOpen->nPending = 0;
1394 pOpen->aPending = 0;
1395 }
1396 }
danielk1977b4b47412007-08-17 15:53:36 +00001397 leaveMutex();
drh054889e2005-11-30 03:20:31 +00001398 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001399 return rc;
drhbbd42a62004-05-22 17:41:58 +00001400}
1401
1402/*
danielk1977e3026632004-06-22 11:29:02 +00001403** Close a file.
1404*/
danielk197762079062007-08-15 17:08:46 +00001405static int unixClose(sqlite3_file *id){
1406 unixFile *pFile = (unixFile *)id;
1407 if( !pFile ) return SQLITE_OK;
1408 unixUnlock(id, NO_LOCK);
1409 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1410 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001411 enterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001412
danielk197762079062007-08-15 17:08:46 +00001413 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001414 /* If there are outstanding locks, do not actually close the file just
1415 ** yet because that would clear those locks. Instead, add the file
1416 ** descriptor to pOpen->aPending. It will be automatically closed when
1417 ** the last lock is cleared.
1418 */
1419 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001420 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001421 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001422 if( aNew==0 ){
1423 /* If a malloc fails, just leak the file descriptor */
1424 }else{
1425 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001426 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001427 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001428 }
1429 }else{
1430 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001431 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001432 }
danielk197762079062007-08-15 17:08:46 +00001433 releaseLockInfo(pFile->pLock);
1434 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001435
danielk1977b4b47412007-08-17 15:53:36 +00001436 leaveMutex();
danielk197762079062007-08-15 17:08:46 +00001437 pFile->isOpen = 0;
1438 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001439 OpenCounter(-1);
danielk1977b4b47412007-08-17 15:53:36 +00001440 memset(pFile, 0, sizeof(unixFile));
drh02afc862006-01-20 18:10:57 +00001441 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001442}
1443
drhbfe66312006-10-03 17:40:40 +00001444
1445#ifdef SQLITE_ENABLE_LOCKING_STYLE
1446#pragma mark AFP Support
1447
1448/*
1449 ** The afpLockingContext structure contains all afp lock specific state
1450 */
1451typedef struct afpLockingContext afpLockingContext;
1452struct afpLockingContext {
1453 unsigned long long sharedLockByte;
1454 char *filePath;
1455};
1456
1457struct ByteRangeLockPB2
1458{
1459 unsigned long long offset; /* offset to first byte to lock */
1460 unsigned long long length; /* nbr of bytes to lock */
1461 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1462 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1463 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1464 int fd; /* file desc to assoc this lock with */
1465};
1466
drhfd131da2007-08-07 17:13:03 +00001467#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001468
danielk1977ad94b582007-08-20 06:44:22 +00001469/*
1470** Return 0 on success, 1 on failure. To match the behavior of the
1471** normal posix file locking (used in unixLock for example), we should
1472** provide 'richer' return codes - specifically to differentiate between
1473** 'file busy' and 'file system error' results.
1474*/
1475static int _AFPFSSetLock(
1476 const char *path,
1477 int fd,
1478 unsigned long long offset,
1479 unsigned long long length,
1480 int setLockFlag
1481){
drhfd131da2007-08-07 17:13:03 +00001482 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001483 int err;
1484
1485 pb.unLockFlag = setLockFlag ? 0 : 1;
1486 pb.startEndFlag = 0;
1487 pb.offset = offset;
1488 pb.length = length;
1489 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001490 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001491 (setLockFlag?"ON":"OFF"), fd, offset, length);
1492 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1493 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001494 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001495 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001496 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001497 } else {
1498 return 0;
1499 }
1500}
1501
1502/*
1503 ** This routine checks if there is a RESERVED lock held on the specified
1504 ** file by this or any other process. If such a lock is held, return
1505 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1506 ** return zero.
1507 */
danielk1977ad94b582007-08-20 06:44:22 +00001508static int afpUnixCheckReservedLock(sqlite3_file *id){
drhbfe66312006-10-03 17:40:40 +00001509 int r = 0;
1510 unixFile *pFile = (unixFile*)id;
1511
1512 assert( pFile );
1513 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1514
1515 /* Check if a thread in this process holds such a lock */
1516 if( pFile->locktype>SHARED_LOCK ){
1517 r = 1;
1518 }
1519
1520 /* Otherwise see if some other process holds it.
1521 */
1522 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001523 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001524 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1525 if (failed) {
1526 /* if we failed to get the lock then someone else must have it */
1527 r = 1;
1528 } else {
1529 /* if we succeeded in taking the reserved lock, unlock it to restore
1530 ** the original state */
1531 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1532 }
1533 }
drh4f0c5872007-03-26 22:05:01 +00001534 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001535
1536 return r;
1537}
1538
1539/* AFP-style locking following the behavior of unixLock, see the unixLock
1540** function comments for details of lock management. */
danielk1977ad94b582007-08-20 06:44:22 +00001541static int afpUnixLock(sqlite3_file *id, int locktype)
drhbfe66312006-10-03 17:40:40 +00001542{
1543 int rc = SQLITE_OK;
1544 unixFile *pFile = (unixFile*)id;
1545 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1546 int gotPendingLock = 0;
1547
1548 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001549 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001550 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1551 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001552 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001553 ** enterMutex() hasn't been called yet.
drhbfe66312006-10-03 17:40:40 +00001554 */
1555 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001556 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001557 locktypeName(locktype));
1558 return SQLITE_OK;
1559 }
1560
1561 /* Make sure the locking sequence is correct
1562 */
1563 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1564 assert( locktype!=PENDING_LOCK );
1565 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1566
1567 /* This mutex is needed because pFile->pLock is shared across threads
1568 */
danielk1977b4b47412007-08-17 15:53:36 +00001569 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001570
1571 /* Make sure the current thread owns the pFile.
1572 */
1573 rc = transferOwnership(pFile);
1574 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001575 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001576 return rc;
1577 }
1578
1579 /* A PENDING lock is needed before acquiring a SHARED lock and before
1580 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1581 ** be released.
1582 */
1583 if( locktype==SHARED_LOCK
1584 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
1585 ){
1586 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1587 PENDING_BYTE, 1, 1);
1588 if (failed) {
1589 rc = SQLITE_BUSY;
1590 goto afp_end_lock;
1591 }
1592 }
1593
1594 /* If control gets to this point, then actually go ahead and make
1595 ** operating system calls for the specified lock.
1596 */
1597 if( locktype==SHARED_LOCK ){
1598 int lk, failed;
1599 int tries = 0;
1600
1601 /* Now get the read-lock */
1602 /* note that the quality of the randomness doesn't matter that much */
1603 lk = random();
1604 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1605 failed = _AFPFSSetLock(context->filePath, pFile->h,
1606 SHARED_FIRST+context->sharedLockByte, 1, 1);
1607
1608 /* Drop the temporary PENDING lock */
1609 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1610 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1611 goto afp_end_lock;
1612 }
1613
1614 if( failed ){
1615 rc = SQLITE_BUSY;
1616 } else {
1617 pFile->locktype = SHARED_LOCK;
1618 }
1619 }else{
1620 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1621 ** assumed that there is a SHARED or greater lock on the file
1622 ** already.
1623 */
1624 int failed = 0;
1625 assert( 0!=pFile->locktype );
1626 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1627 /* Acquire a RESERVED lock */
1628 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1629 }
1630 if (!failed && locktype == EXCLUSIVE_LOCK) {
1631 /* Acquire an EXCLUSIVE lock */
1632
1633 /* Remove the shared lock before trying the range. we'll need to
1634 ** reestablish the shared lock if we can't get the afpUnixUnlock
1635 */
1636 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1637 context->sharedLockByte, 1, 0)) {
1638 /* now attemmpt to get the exclusive lock range */
1639 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1640 SHARED_SIZE, 1);
1641 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1642 context->sharedLockByte, 1, 1)) {
1643 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1644 }
1645 } else {
1646 /* */
1647 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1648 }
1649 }
1650 if( failed && rc == SQLITE_OK){
1651 rc = SQLITE_BUSY;
1652 }
1653 }
1654
1655 if( rc==SQLITE_OK ){
1656 pFile->locktype = locktype;
1657 }else if( locktype==EXCLUSIVE_LOCK ){
1658 pFile->locktype = PENDING_LOCK;
1659 }
1660
1661afp_end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001662 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001663 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001664 rc==SQLITE_OK ? "ok" : "failed");
1665 return rc;
1666}
1667
1668/*
1669 ** Lower the locking level on file descriptor pFile to locktype. locktype
1670 ** must be either NO_LOCK or SHARED_LOCK.
1671 **
1672 ** If the locking level of the file descriptor is already at or below
1673 ** the requested locking level, this routine is a no-op.
1674 */
danielk1977ad94b582007-08-20 06:44:22 +00001675static int afpUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001676 struct flock lock;
1677 int rc = SQLITE_OK;
1678 unixFile *pFile = (unixFile*)id;
1679 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1680
1681 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001682 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001683 pFile->locktype, getpid());
1684
1685 assert( locktype<=SHARED_LOCK );
1686 if( pFile->locktype<=locktype ){
1687 return SQLITE_OK;
1688 }
1689 if( CHECK_THREADID(pFile) ){
1690 return SQLITE_MISUSE;
1691 }
danielk1977b4b47412007-08-17 15:53:36 +00001692 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001693 if( pFile->locktype>SHARED_LOCK ){
1694 if( locktype==SHARED_LOCK ){
1695 int failed = 0;
1696
1697 /* unlock the exclusive range - then re-establish the shared lock */
1698 if (pFile->locktype==EXCLUSIVE_LOCK) {
1699 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1700 SHARED_SIZE, 0);
1701 if (!failed) {
1702 /* successfully removed the exclusive lock */
1703 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1704 context->sharedLockByte, 1, 1)) {
1705 /* failed to re-establish our shared lock */
1706 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1707 }
1708 } else {
1709 /* This should never happen - failed to unlock the exclusive range */
1710 rc = SQLITE_IOERR_UNLOCK;
1711 }
1712 }
1713 }
1714 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1715 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1716 /* failed to release the pending lock */
1717 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1718 }
1719 }
1720 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1721 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1722 /* failed to release the reserved lock */
1723 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1724 }
1725 }
1726 }
1727 if( locktype==NO_LOCK ){
1728 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1729 SHARED_FIRST + context->sharedLockByte, 1, 0);
1730 if (failed) {
1731 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1732 }
1733 }
1734 if (rc == SQLITE_OK)
1735 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001736 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001737 return rc;
1738}
1739
1740/*
1741 ** Close a file & cleanup AFP specific locking context
1742 */
danielk1977ad94b582007-08-20 06:44:22 +00001743static int afpUnixClose(sqlite3_file *id) {
1744 unixFile *pFile = (unixFile*)pId;
1745
1746 if( !pFile ) return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001747 afpUnixUnlock(*pId, NO_LOCK);
1748 /* free the AFP locking structure */
danielk1977ad94b582007-08-20 06:44:22 +00001749 if (pFile->lockingContext != NULL) {
1750 if (((afpLockingContext *)pFile->lockingContext)->filePath != NULL)
1751 sqlite3_free(((afpLockingContext*)pFile->lockingContext)->filePath);
1752 sqlite3_free(pFile->lockingContext);
drhbfe66312006-10-03 17:40:40 +00001753 }
danielk1977ad94b582007-08-20 06:44:22 +00001754
1755 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1756 pFile->dirfd = -1;
1757 close(pFile->h);
1758 pFile->isOpen = 0;
1759 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001760 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00001761 return SQLITE_OK;
1762}
1763
1764
1765#pragma mark flock() style locking
1766
1767/*
1768 ** The flockLockingContext is not used
1769 */
1770typedef void flockLockingContext;
1771
danielk1977ad94b582007-08-20 06:44:22 +00001772static int flockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001773 unixFile *pFile = (unixFile*)id;
1774
1775 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001776 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001777 } else {
drh3b62b2f2007-06-08 18:27:03 +00001778 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001779 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1780 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001781 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001782 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00001783 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001784 }
drh3b62b2f2007-06-08 18:27:03 +00001785 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00001786 }
1787}
1788
danielk1977ad94b582007-08-20 06:44:22 +00001789static int flockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001790 unixFile *pFile = (unixFile*)id;
1791
drh3b62b2f2007-06-08 18:27:03 +00001792 /* if we already have a lock, it is exclusive.
1793 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001794 if (pFile->locktype > NO_LOCK) {
1795 pFile->locktype = locktype;
1796 return SQLITE_OK;
1797 }
1798
drh3b62b2f2007-06-08 18:27:03 +00001799 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001800 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1801 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00001802 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00001803 return SQLITE_BUSY;
1804 } else {
drh3b62b2f2007-06-08 18:27:03 +00001805 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001806 pFile->locktype = locktype;
1807 return SQLITE_OK;
1808 }
1809}
1810
danielk1977ad94b582007-08-20 06:44:22 +00001811static int flockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001812 unixFile *pFile = (unixFile*)id;
1813
1814 assert( locktype<=SHARED_LOCK );
1815
drh3b62b2f2007-06-08 18:27:03 +00001816 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001817 if( pFile->locktype==locktype ){
1818 return SQLITE_OK;
1819 }
1820
drh3b62b2f2007-06-08 18:27:03 +00001821 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001822 if (locktype==SHARED_LOCK) {
1823 pFile->locktype = locktype;
1824 return SQLITE_OK;
1825 }
1826
drh3b62b2f2007-06-08 18:27:03 +00001827 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001828 int rc = flock(pFile->h, LOCK_UN);
1829 if (rc)
1830 return SQLITE_IOERR_UNLOCK;
1831 else {
1832 pFile->locktype = NO_LOCK;
1833 return SQLITE_OK;
1834 }
1835}
1836
1837/*
1838 ** Close a file.
1839 */
danielk1977ad94b582007-08-20 06:44:22 +00001840static int flockUnixClose(sqlite3_file *pId) {
1841 unixFile *pFile = (unixFile*)*pId;
drhbfe66312006-10-03 17:40:40 +00001842
danielk1977ad94b582007-08-20 06:44:22 +00001843 if( !pFile ) return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001844 flockUnixUnlock(*pId, NO_LOCK);
1845
danielk1977ad94b582007-08-20 06:44:22 +00001846 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1847 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001848 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001849
danielk1977ad94b582007-08-20 06:44:22 +00001850 close(pFile->h);
danielk1977b4b47412007-08-17 15:53:36 +00001851 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001852 pFile->isOpen = 0;
1853 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001854 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00001855 return SQLITE_OK;
1856}
1857
1858#pragma mark Old-School .lock file based locking
1859
1860/*
1861 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
1862 ** specific state
1863 */
1864typedef struct dotlockLockingContext dotlockLockingContext;
1865struct dotlockLockingContext {
1866 char *lockPath;
1867};
1868
1869
danielk1977ad94b582007-08-20 06:44:22 +00001870static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001871 unixFile *pFile = (unixFile*)id;
1872 dotlockLockingContext *context =
1873 (dotlockLockingContext *) pFile->lockingContext;
1874
1875 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001876 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001877 } else {
1878 struct stat statBuf;
1879 if (lstat(context->lockPath,&statBuf) == 0)
drh3b62b2f2007-06-08 18:27:03 +00001880 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00001881 return 1;
1882 else
drh3b62b2f2007-06-08 18:27:03 +00001883 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00001884 return 0;
1885 }
1886}
1887
danielk1977ad94b582007-08-20 06:44:22 +00001888static int dotlockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001889 unixFile *pFile = (unixFile*)id;
1890 dotlockLockingContext *context =
1891 (dotlockLockingContext *) pFile->lockingContext;
1892
drh3b62b2f2007-06-08 18:27:03 +00001893 /* if we already have a lock, it is exclusive.
1894 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001895 if (pFile->locktype > NO_LOCK) {
1896 pFile->locktype = locktype;
1897
1898 /* Always update the timestamp on the old file */
1899 utimes(context->lockPath,NULL);
1900 return SQLITE_OK;
1901 }
1902
drh3b62b2f2007-06-08 18:27:03 +00001903 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00001904 struct stat statBuf;
1905 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001906 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00001907 }
1908
drh3b62b2f2007-06-08 18:27:03 +00001909 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001910 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
1911 if (fd < 0) {
drh3b62b2f2007-06-08 18:27:03 +00001912 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00001913 return SQLITE_BUSY;
1914 }
1915 close(fd);
1916
drh3b62b2f2007-06-08 18:27:03 +00001917 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001918 pFile->locktype = locktype;
1919 return SQLITE_OK;
1920}
1921
danielk1977ad94b582007-08-20 06:44:22 +00001922static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001923 unixFile *pFile = (unixFile*)id;
1924 dotlockLockingContext *context =
1925 (dotlockLockingContext *) pFile->lockingContext;
1926
1927 assert( locktype<=SHARED_LOCK );
1928
drh3b62b2f2007-06-08 18:27:03 +00001929 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001930 if( pFile->locktype==locktype ){
1931 return SQLITE_OK;
1932 }
1933
drh3b62b2f2007-06-08 18:27:03 +00001934 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001935 if (locktype==SHARED_LOCK) {
1936 pFile->locktype = locktype;
1937 return SQLITE_OK;
1938 }
1939
drh3b62b2f2007-06-08 18:27:03 +00001940 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001941 unlink(context->lockPath);
1942 pFile->locktype = NO_LOCK;
1943 return SQLITE_OK;
1944}
1945
1946/*
1947 ** Close a file.
1948 */
danielk1977ad94b582007-08-20 06:44:22 +00001949static int dotlockUnixClose(sqlite3_file *id) {
1950 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001951
danielk1977ad94b582007-08-20 06:44:22 +00001952 if( !pFile ) return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001953 dotlockUnixUnlock(*pId, NO_LOCK);
1954 /* free the dotlock locking structure */
danielk1977ad94b582007-08-20 06:44:22 +00001955 if (pFile->lockingContext != NULL) {
1956 if (((dotlockLockingContext *)pFile->lockingContext)->lockPath != NULL)
drh17435752007-08-16 04:30:38 +00001957 sqlite3_free( ( (dotlockLockingContext *)
danielk1977ad94b582007-08-20 06:44:22 +00001958 pFile->lockingContext)->lockPath);
1959 sqlite3_free(pFile->lockingContext);
drhbfe66312006-10-03 17:40:40 +00001960 }
1961
danielk1977ad94b582007-08-20 06:44:22 +00001962 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1963 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001964 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001965
danielk1977ad94b582007-08-20 06:44:22 +00001966 close(pFile->h);
drhbfe66312006-10-03 17:40:40 +00001967
danielk1977b4b47412007-08-17 15:53:36 +00001968 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001969 pFile->isOpen = 0;
1970 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001971 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00001972 return SQLITE_OK;
1973}
1974
1975
1976#pragma mark No locking
1977
1978/*
1979 ** The nolockLockingContext is void
1980 */
1981typedef void nolockLockingContext;
1982
danielk1977ad94b582007-08-20 06:44:22 +00001983static int nolockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001984 return 0;
1985}
1986
danielk1977ad94b582007-08-20 06:44:22 +00001987static int nolockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001988 return SQLITE_OK;
1989}
1990
danielk1977ad94b582007-08-20 06:44:22 +00001991static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001992 return SQLITE_OK;
1993}
1994
1995/*
1996 ** Close a file.
1997 */
danielk1977ad94b582007-08-20 06:44:22 +00001998static int nolockUnixClose(sqlite3_file *id) {
1999 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00002000
danielk1977ad94b582007-08-20 06:44:22 +00002001 if( !pFile ) return SQLITE_OK;
2002 if( pFile->dirfd>=0 ) close(pFile->dirfd);
2003 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00002004 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002005
danielk1977ad94b582007-08-20 06:44:22 +00002006 close(pFile->h);
drhbfe66312006-10-03 17:40:40 +00002007
danielk1977b4b47412007-08-17 15:53:36 +00002008 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002009 pFile->isOpen = 0;
2010 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00002011 OpenCounter(-1);
drhbfe66312006-10-03 17:40:40 +00002012 return SQLITE_OK;
2013}
2014
2015#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2016
danielk1977ad94b582007-08-20 06:44:22 +00002017
danielk1977e3026632004-06-22 11:29:02 +00002018/*
danielk1977ad94b582007-08-20 06:44:22 +00002019** TODO: xBreakLock() for this vfs.
drh18839212005-11-26 03:43:23 +00002020*/
danielk1977ad94b582007-08-20 06:44:22 +00002021static int unixBreakLock(sqlite3_file *id){
2022 assert(!"TODO: unixBreakLock()");
2023 return 0;
drh9cbe6352005-11-29 03:13:21 +00002024}
2025
2026/*
danielk1977ad94b582007-08-20 06:44:22 +00002027** Return an integer that indices the type of lock currently held
2028** by this handle. (Used for testing and analysis only.)
drh9cbe6352005-11-29 03:13:21 +00002029*/
danielk1977ad94b582007-08-20 06:44:22 +00002030static int unixLockState(sqlite3_file *id){
2031 return ((unixFile*)id)->locktype;
drh9cbe6352005-11-29 03:13:21 +00002032}
2033
drh9c06c952005-11-26 00:25:00 +00002034/*
danielk1977a3d4c882007-03-23 10:08:38 +00002035** Return the sector size in bytes of the underlying block device for
2036** the specified file. This is almost always 512 bytes, but may be
2037** larger for some devices.
2038**
2039** SQLite code assumes this function cannot fail. It also assumes that
2040** if two files are created in the same file-system directory (i.e.
2041** a database and it's journal file) that the sector size will be the
2042** same for both.
2043*/
danielk197762079062007-08-15 17:08:46 +00002044static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002045 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002046}
2047
danielk197790949c22007-08-17 16:50:38 +00002048/*
2049** Return the device characteristics for the file. This is always 0.
2050*/
danielk197762079062007-08-15 17:08:46 +00002051static int unixDeviceCharacteristics(sqlite3_file *id){
2052 return 0;
2053}
2054
danielk1977a3d4c882007-03-23 10:08:38 +00002055/*
danielk1977ad94b582007-08-20 06:44:22 +00002056** This vector defines all the methods that can operate on an sqlite3_file
drh054889e2005-11-30 03:20:31 +00002057** for unix.
drh9c06c952005-11-26 00:25:00 +00002058*/
danielk197762079062007-08-15 17:08:46 +00002059static const sqlite3_io_methods sqlite3UnixIoMethod = {
2060 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002061 unixClose,
2062 unixRead,
2063 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002064 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002065 unixSync,
drh054889e2005-11-30 03:20:31 +00002066 unixFileSize,
2067 unixLock,
2068 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002069 unixCheckReservedLock,
danielk197762079062007-08-15 17:08:46 +00002070 unixBreakLock,
danielk197790949c22007-08-17 16:50:38 +00002071 unixLockState,
danielk1977a3d4c882007-03-23 10:08:38 +00002072 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002073 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002074};
2075
drhbfe66312006-10-03 17:40:40 +00002076#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002077/*
danielk1977ad94b582007-08-20 06:44:22 +00002078** This vector defines all the methods that can operate on an sqlite3_file
2079** for unix with AFP style file locking.
2080*/
2081static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
2082 1, /* iVersion */
2083 unixClose,
drhbfe66312006-10-03 17:40:40 +00002084 unixRead,
2085 unixWrite,
drhbfe66312006-10-03 17:40:40 +00002086 unixTruncate,
2087 unixSync,
danielk1977ad94b582007-08-20 06:44:22 +00002088 unixFileSize,
2089 afpUnixLock,
2090 afpUnixUnlock,
2091 afpUnixCheckReservedLock,
2092 unixBreakLock,
2093 unixLockState,
2094 unixSectorSize,
2095 unixDeviceCharacteristics
2096};
2097
2098/*
2099** This vector defines all the methods that can operate on an sqlite3_file
2100** for unix with flock() style file locking.
2101*/
2102static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
2103 1, /* iVersion */
2104 flockUnixClose,
2105 unixRead,
2106 unixWrite,
2107 unixTruncate,
2108 unixSync,
2109 unixFileSize,
2110 flockUnixLock,
2111 flockUnixUnlock,
2112 flockUnixCheckReservedLock,
2113 unixBreakLock,
2114 unixLockState,
2115 unixSectorSize,
2116 unixDeviceCharacteristics
2117};
2118
2119/*
2120** This vector defines all the methods that can operate on an sqlite3_file
2121** for unix with dotlock style file locking.
2122*/
2123static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
2124 1, /* iVersion */
2125 dotlockUnixClose,
2126 unixRead,
2127 unixWrite,
2128 unixTruncate,
2129 unixSync,
2130 unixFileSize,
2131 dotlockUnixLock,
2132 dotlockUnixUnlock,
2133 dotlockUnixCheckReservedLock,
2134 unixBreakLock,
2135 unixLockState,
2136 unixSectorSize,
2137 unixDeviceCharacteristics
2138};
2139
2140/*
2141** This vector defines all the methods that can operate on an sqlite3_file
2142** for unix with dotlock style file locking.
2143*/
2144static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
2145 1, /* iVersion */
2146 nolockUnixClose,
2147 unixRead,
2148 unixWrite,
2149 unixTruncate,
2150 unixSync,
drhbfe66312006-10-03 17:40:40 +00002151 unixFileSize,
2152 nolockUnixLock,
2153 nolockUnixUnlock,
drhbfe66312006-10-03 17:40:40 +00002154 nolockUnixCheckReservedLock,
danielk1977ad94b582007-08-20 06:44:22 +00002155 unixBreakLock,
2156 unixLockState,
danielk1977a3d4c882007-03-23 10:08:38 +00002157 unixSectorSize,
danielk1977ad94b582007-08-20 06:44:22 +00002158 unixDeviceCharacteristics
drhbfe66312006-10-03 17:40:40 +00002159};
2160
2161#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2162
2163/*
2164** Allocate memory for a new unixFile and initialize that unixFile.
2165** Write a pointer to the new unixFile into *pId.
2166** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002167*/
drhbfe66312006-10-03 17:40:40 +00002168#ifdef SQLITE_ENABLE_LOCKING_STYLE
2169/*
danielk1977ad94b582007-08-20 06:44:22 +00002170** When locking extensions are enabled, the filepath and locking style
2171** are needed to determine the unixFile pMethod to use for locking operations.
2172** The locking-style specific lockingContext data structure is created
2173** and assigned here also.
2174*/
2175static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002176 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002177 int dirfd, /* Directory file descriptor */
2178 sqlite3_file *pId, /* Write completed initialization here */
drhbfe66312006-10-03 17:40:40 +00002179 const char *zFilename, /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002180){
aswift108bc322006-10-11 17:19:46 +00002181 sqlite3LockingStyle lockingStyle;
danielk1977ad94b582007-08-20 06:44:22 +00002182 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002183 int rc;
2184
danielk1977ad94b582007-08-20 06:44:22 +00002185 memset(pNew, 0, sizeof(unixFile));
aswift448aa6f2006-11-11 01:31:58 +00002186 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drhbfe66312006-10-03 17:40:40 +00002187 if ( lockingStyle == posixLockingStyle ) {
danielk1977b4b47412007-08-17 15:53:36 +00002188 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002189 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002190 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002191 if( rc ){
2192 close(h);
2193 unlink(zFilename);
2194 return SQLITE_NOMEM;
2195 }
2196 } else {
drh3b62b2f2007-06-08 18:27:03 +00002197 /* pLock and pOpen are only used for posix advisory locking */
danielk1977ad94b582007-08-20 06:44:22 +00002198 pNew->pLock = NULL;
2199 pNew->pOpen = NULL;
drhbfe66312006-10-03 17:40:40 +00002200 }
danielk1977ad94b582007-08-20 06:44:22 +00002201 pNew->dirfd = -1;
2202 pNew->h = h;
2203 SET_THREADID(pNew);
drh17435752007-08-16 04:30:38 +00002204 pNew = sqlite3_malloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00002205 if( pNew==0 ){
drhbfe66312006-10-03 17:40:40 +00002206 close(h);
danielk1977b4b47412007-08-17 15:53:36 +00002207 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002208 releaseLockInfo(pNew->pLock);
2209 releaseOpenCnt(pNew->pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002210 leaveMutex();
drh054889e2005-11-30 03:20:31 +00002211 return SQLITE_NOMEM;
2212 }else{
aswift108bc322006-10-11 17:19:46 +00002213 switch(lockingStyle) {
drh5bb3eb92007-05-04 13:15:55 +00002214 case afpLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002215 /* afp locking uses the file path so it needs to be included in
2216 ** the afpLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002217 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002218 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
2219 pNew->lockingContext =
drh17435752007-08-16 04:30:38 +00002220 sqlite3_malloc(sizeof(afpLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002221 nFilename = strlen(zFilename)+1;
drhbfe66312006-10-03 17:40:40 +00002222 ((afpLockingContext *)pNew->lockingContext)->filePath =
drh17435752007-08-16 04:30:38 +00002223 sqlite3_malloc(nFilename);
drh5bb3eb92007-05-04 13:15:55 +00002224 memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
2225 zFilename, nFilename);
drhbfe66312006-10-03 17:40:40 +00002226 srandomdev();
2227 break;
drh5bb3eb92007-05-04 13:15:55 +00002228 }
drhbfe66312006-10-03 17:40:40 +00002229 case flockLockingStyle:
2230 /* flock locking doesn't need additional lockingContext information */
2231 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2232 break;
drh5bb3eb92007-05-04 13:15:55 +00002233 case dotlockLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002234 /* dotlock locking uses the file path so it needs to be included in
2235 ** the dotlockLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002236 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002237 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh17435752007-08-16 04:30:38 +00002238 pNew->lockingContext = sqlite3_malloc(
drhbfe66312006-10-03 17:40:40 +00002239 sizeof(dotlockLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002240 nFilename = strlen(zFilename) + 6;
drhbfe66312006-10-03 17:40:40 +00002241 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
drh17435752007-08-16 04:30:38 +00002242 sqlite3_malloc( nFilename );
drh5bb3eb92007-05-04 13:15:55 +00002243 sqlite3_snprintf(nFilename,
2244 ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
drhbfe66312006-10-03 17:40:40 +00002245 "%s.lock", zFilename);
2246 break;
drh5bb3eb92007-05-04 13:15:55 +00002247 }
drhbfe66312006-10-03 17:40:40 +00002248 case posixLockingStyle:
2249 /* posix locking doesn't need additional lockingContext information */
2250 pNew->pMethod = &sqlite3UnixIoMethod;
2251 break;
2252 case noLockingStyle:
2253 case unsupportedLockingStyle:
2254 default:
2255 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
2256 }
drhbfe66312006-10-03 17:40:40 +00002257 OpenCounter(+1);
2258 return SQLITE_OK;
2259 }
2260}
2261#else /* SQLITE_ENABLE_LOCKING_STYLE */
danielk1977b4b47412007-08-17 15:53:36 +00002262static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002263 int h, /* Open file descriptor on file being opened */
danielk1977fee2d252007-08-18 10:59:19 +00002264 int dirfd,
danielk1977b4b47412007-08-17 15:53:36 +00002265 sqlite3_file *pId, /* Write to the unixFile structure here */
2266 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002267){
danielk1977b4b47412007-08-17 15:53:36 +00002268 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002269 int rc;
2270
drhe78669b2007-06-29 12:04:26 +00002271#ifdef FD_CLOEXEC
2272 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2273#endif
danielk1977b4b47412007-08-17 15:53:36 +00002274
2275 enterMutex();
2276 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2277 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002278 if( rc ){
2279 close(h);
2280 return SQLITE_NOMEM;
2281 }
danielk1977b4b47412007-08-17 15:53:36 +00002282
drh4f0c5872007-03-26 22:05:01 +00002283 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977b4b47412007-08-17 15:53:36 +00002284 pNew->dirfd = -1;
2285 pNew->h = h;
danielk1977fee2d252007-08-18 10:59:19 +00002286 pNew->dirfd = dirfd;
danielk1977b4b47412007-08-17 15:53:36 +00002287 SET_THREADID(pNew);
2288
2289 pNew->pMethod = &sqlite3UnixIoMethod;
2290 OpenCounter(+1);
2291 return SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00002292}
drhbfe66312006-10-03 17:40:40 +00002293#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002294
danielk1977ad94b582007-08-20 06:44:22 +00002295/*
2296** Open a file descriptor to the directory containing file zFilename.
2297** If successful, *pFd is set to the opened file descriptor and
2298** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2299** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2300** value.
2301**
2302** If SQLITE_OK is returned, the caller is responsible for closing
2303** the file descriptor *pFd using close().
2304*/
danielk1977fee2d252007-08-18 10:59:19 +00002305static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002306 int ii;
2307 int fd;
drhf3a65f72007-08-22 20:18:21 +00002308 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002309
drh153c62c2007-08-24 03:51:33 +00002310 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002311 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2312 if( ii>0 ){
2313 zDirname[ii] = '\0';
2314 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
2315 if( fd>0 ){
2316#ifdef FD_CLOEXEC
2317 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2318#endif
2319 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2320 }
2321 }
danielk1977fee2d252007-08-18 10:59:19 +00002322 *pFd = fd;
2323 return (fd>0?SQLITE_OK:SQLITE_CANTOPEN);
2324}
2325
danielk1977b4b47412007-08-17 15:53:36 +00002326/*
danielk1977ad94b582007-08-20 06:44:22 +00002327** Open the file zPath.
2328**
danielk1977b4b47412007-08-17 15:53:36 +00002329** Previously, the SQLite OS layer used three functions in place of this
2330** one:
2331**
2332** sqlite3OsOpenReadWrite();
2333** sqlite3OsOpenReadOnly();
2334** sqlite3OsOpenExclusive();
2335**
2336** These calls correspond to the following combinations of flags:
2337**
2338** ReadWrite() -> (READWRITE | CREATE)
2339** ReadOnly() -> (READONLY)
2340** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2341**
2342** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2343** true, the file was configured to be automatically deleted when the
2344** file handle closed. To achieve the same effect using this new
2345** interface, add the DELETEONCLOSE flag to those specified above for
2346** OpenExclusive().
2347*/
2348static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00002349 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00002350 const char *zPath,
2351 sqlite3_file *pFile,
2352 int flags,
2353 int *pOutFlags
2354){
danielk1977fee2d252007-08-18 10:59:19 +00002355 int fd = 0; /* File descriptor returned by open() */
2356 int dirfd = -1; /* Directory file descriptor */
2357 int oflags = 0; /* Flags to pass to open() */
2358 int eType = flags&0xFFFFFF00; /* Type of file to open */
danielk1977b4b47412007-08-17 15:53:36 +00002359
2360 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2361 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2362 int isCreate = (flags & SQLITE_OPEN_CREATE);
2363 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2364 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2365
danielk1977fee2d252007-08-18 10:59:19 +00002366 /* If creating a master or main-file journal, this function will open
2367 ** a file-descriptor on the directory too. The first time unixSync()
2368 ** is called the directory file descriptor will be fsync()ed and close()d.
2369 */
2370 int isOpenDirectory = (isCreate &&
2371 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
2372 );
2373
2374 /* Check the following statements are true:
2375 **
2376 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2377 ** (b) if CREATE is set, then READWRITE must also be set, and
2378 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
2379 */
danielk1977b4b47412007-08-17 15:53:36 +00002380 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00002381 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00002382 assert(isExclusive==0 || isCreate);
2383
danielk1977fee2d252007-08-18 10:59:19 +00002384 /* Assert that the upper layer has set one of the "file-type" flags. */
2385 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2386 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2387 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
2388 );
2389
danielk1977b4b47412007-08-17 15:53:36 +00002390 if( isReadonly ) oflags |= O_RDONLY;
2391 if( isReadWrite ) oflags |= O_RDWR;
2392 if( isCreate ) oflags |= O_CREAT;
2393 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2394 oflags |= (O_LARGEFILE|O_BINARY);
2395
2396 memset(pFile, 0, sizeof(unixFile));
2397 fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
2398 if( fd<0 && isReadWrite && !isExclusive ){
2399 /* Failed to open the file for read/write access. Try read-only. */
2400 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2401 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00002402 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00002403 }
2404 if( fd<0 ){
2405 return SQLITE_CANTOPEN;
2406 }
2407 if( isDelete ){
2408 unlink(zPath);
2409 }
2410 if( pOutFlags ){
2411 *pOutFlags = flags;
2412 }
2413
2414 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00002415 if( isOpenDirectory ){
2416 int rc = openDirectory(zPath, &dirfd);
2417 if( rc!=SQLITE_OK ){
2418 close(fd);
2419 return rc;
2420 }
2421 }
2422 return fillInUnixFile(fd, dirfd, pFile, zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002423}
2424
2425/*
danielk1977fee2d252007-08-18 10:59:19 +00002426** Delete the file at zPath. If the dirSync argument is true, fsync()
2427** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00002428*/
drh153c62c2007-08-24 03:51:33 +00002429static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00002430 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002431 SimulateIOError(return SQLITE_IOERR_DELETE);
2432 unlink(zPath);
danielk1977fee2d252007-08-18 10:59:19 +00002433 if( dirSync ){
2434 int fd;
2435 rc = openDirectory(zPath, &fd);
2436 if( rc==SQLITE_OK ){
2437 if( fsync(fd) ){
2438 rc = SQLITE_IOERR_DIR_FSYNC;
2439 }
2440 close(fd);
2441 }
2442 }
2443 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00002444}
2445
danielk197790949c22007-08-17 16:50:38 +00002446/*
2447** Test the existance of or access permissions of file zPath. The
2448** test performed depends on the value of flags:
2449**
2450** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2451** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2452** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2453**
2454** Otherwise return 0.
2455*/
drh153c62c2007-08-24 03:51:33 +00002456static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
danielk1977b4b47412007-08-17 15:53:36 +00002457 int amode;
2458 switch( flags ){
2459 case SQLITE_ACCESS_EXISTS:
2460 amode = F_OK;
2461 break;
2462 case SQLITE_ACCESS_READWRITE:
2463 amode = W_OK|R_OK;
2464 break;
drh50d3f902007-08-27 21:10:36 +00002465 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00002466 amode = R_OK;
2467 break;
2468
2469 default:
2470 assert(!"Invalid flags argument");
2471 }
2472 return (access(zPath, amode)==0);
2473}
2474
2475/*
drh153c62c2007-08-24 03:51:33 +00002476** Create a temporary file name in zBuf. zBuf must be allocated
2477** by the calling process and must be big enough to hold at least
2478** pVfs->mxPathname bytes.
danielk1977b4b47412007-08-17 15:53:36 +00002479*/
drh153c62c2007-08-24 03:51:33 +00002480static int unixGetTempName(sqlite3_vfs *pVfs, char *zBuf){
danielk1977b4b47412007-08-17 15:53:36 +00002481 static const char *azDirs[] = {
2482 0,
2483 "/var/tmp",
2484 "/usr/tmp",
2485 "/tmp",
2486 ".",
2487 };
2488 static const unsigned char zChars[] =
2489 "abcdefghijklmnopqrstuvwxyz"
2490 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2491 "0123456789";
2492 int i, j;
2493 struct stat buf;
2494 const char *zDir = ".";
2495 azDirs[0] = sqlite3_temp_directory;
2496 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2497 if( azDirs[i]==0 ) continue;
2498 if( stat(azDirs[i], &buf) ) continue;
2499 if( !S_ISDIR(buf.st_mode) ) continue;
2500 if( access(azDirs[i], 07) ) continue;
2501 zDir = azDirs[i];
2502 break;
2503 }
2504 do{
drh153c62c2007-08-24 03:51:33 +00002505 assert( pVfs->mxPathname==MAX_PATHNAME );
2506 sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
danielk1977b4b47412007-08-17 15:53:36 +00002507 j = strlen(zBuf);
2508 sqlite3Randomness(15, &zBuf[j]);
2509 for(i=0; i<15; i++, j++){
2510 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2511 }
2512 zBuf[j] = 0;
2513 }while( access(zBuf,0)==0 );
2514 return SQLITE_OK;
2515}
2516
2517
2518/*
2519** Turn a relative pathname into a full pathname. The relative path
2520** is stored as a nul-terminated string in the buffer pointed to by
2521** zPath.
2522**
2523** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2524** (in this case, MAX_PATHNAME bytes). The full-path is written to
2525** this buffer before returning.
2526*/
drh153c62c2007-08-24 03:51:33 +00002527static int unixFullPathname(sqlite3_vfs *pVfs, const char *zPath, char *zOut){
2528 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977b4b47412007-08-17 15:53:36 +00002529 zOut[MAX_PATHNAME-1] = '\0';
2530 if( zPath[0]=='/' ){
drh153c62c2007-08-24 03:51:33 +00002531 sqlite3_snprintf(MAX_PATHNAME, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002532 }else{
2533 int nCwd;
2534 if( getcwd(zOut, MAX_PATHNAME-1)==0 ){
2535 return SQLITE_ERROR;
2536 }
2537 nCwd = strlen(zOut);
drh153c62c2007-08-24 03:51:33 +00002538 sqlite3_snprintf(MAX_PATHNAME-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002539 }
2540 return SQLITE_OK;
2541
2542#if 0
2543 /*
2544 ** Remove "/./" path elements and convert "/A/./" path elements
2545 ** to just "/".
2546 */
2547 if( zFull ){
2548 int i, j;
2549 for(i=j=0; zFull[i]; i++){
2550 if( zFull[i]=='/' ){
2551 if( zFull[i+1]=='/' ) continue;
2552 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2553 i += 1;
2554 continue;
2555 }
2556 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2557 while( j>0 && zFull[j-1]!='/' ){ j--; }
2558 i += 3;
2559 continue;
2560 }
2561 }
2562 zFull[j++] = zFull[i];
2563 }
2564 zFull[j] = 0;
2565 }
2566#endif
2567}
2568
drh0ccebe72005-06-07 22:22:50 +00002569
drh761df872006-12-21 01:29:22 +00002570#ifndef SQLITE_OMIT_LOAD_EXTENSION
2571/*
2572** Interfaces for opening a shared library, finding entry points
2573** within the shared library, and closing the shared library.
2574*/
2575#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00002576static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002577 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2578}
drh153c62c2007-08-24 03:51:33 +00002579static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00002580 char *zErr;
2581 enterMutex();
2582 zErr = dlerror();
2583 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00002584 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00002585 }else if(nBuf>0) {
2586 zBufOut[0] = '\0';
2587 }
2588 leaveMutex();
2589}
drh46c99e02007-08-27 23:26:59 +00002590static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002591 return dlsym(pHandle, zSymbol);
2592}
drh46c99e02007-08-27 23:26:59 +00002593static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00002594 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002595}
danielk1977b4b47412007-08-17 15:53:36 +00002596#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2597 #define unixDlOpen 0
2598 #define unixDlError 0
2599 #define unixDlSym 0
2600 #define unixDlClose 0
2601#endif
2602
2603/*
danielk197790949c22007-08-17 16:50:38 +00002604** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002605*/
drh153c62c2007-08-24 03:51:33 +00002606static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002607
2608 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2609
drhbbd42a62004-05-22 17:41:58 +00002610 /* We have to initialize zBuf to prevent valgrind from reporting
2611 ** errors. The reports issued by valgrind are incorrect - we would
2612 ** prefer that the randomness be increased by making use of the
2613 ** uninitialized space in zBuf - but valgrind errors tend to worry
2614 ** some users. Rather than argue, it seems easier just to initialize
2615 ** the whole array and silence valgrind, even if that means less randomness
2616 ** in the random seed.
2617 **
2618 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002619 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002620 ** tests repeatable.
2621 */
danielk1977b4b47412007-08-17 15:53:36 +00002622 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002623#if !defined(SQLITE_TEST)
2624 {
drh842b8642005-01-21 17:53:17 +00002625 int pid, fd;
2626 fd = open("/dev/urandom", O_RDONLY);
2627 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002628 time_t t;
2629 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002630 memcpy(zBuf, &t, sizeof(t));
2631 pid = getpid();
2632 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002633 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002634 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002635 close(fd);
2636 }
drhbbd42a62004-05-22 17:41:58 +00002637 }
2638#endif
2639 return SQLITE_OK;
2640}
2641
danielk1977b4b47412007-08-17 15:53:36 +00002642
drhbbd42a62004-05-22 17:41:58 +00002643/*
2644** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002645** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00002646** The return value is the number of microseconds of sleep actually
2647** requested from the underlying operating system, a number which
2648** might be greater than or equal to the argument, but not less
2649** than the argument.
drhbbd42a62004-05-22 17:41:58 +00002650*/
drh153c62c2007-08-24 03:51:33 +00002651static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002652#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002653 usleep(microseconds);
2654 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002655#else
danielk1977b4b47412007-08-17 15:53:36 +00002656 int seconds = (microseconds+999999)/1000000;
2657 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00002658 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00002659#endif
drh88f474a2006-01-02 20:00:12 +00002660}
2661
2662/*
drhbbd42a62004-05-22 17:41:58 +00002663** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002664** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002665*/
2666#ifdef SQLITE_TEST
2667int sqlite3_current_time = 0;
2668#endif
2669
2670/*
2671** Find the current time (in Universal Coordinated Time). Write the
2672** current time and date as a Julian Day number into *prNow and
2673** return 0. Return 1 if the time and date cannot be found.
2674*/
drh153c62c2007-08-24 03:51:33 +00002675static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002676#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002677 time_t t;
2678 time(&t);
2679 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002680#else
2681 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002682 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002683 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2684#endif
drhbbd42a62004-05-22 17:41:58 +00002685#ifdef SQLITE_TEST
2686 if( sqlite3_current_time ){
2687 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2688 }
2689#endif
2690 return 0;
2691}
danielk1977b4b47412007-08-17 15:53:36 +00002692
drh153c62c2007-08-24 03:51:33 +00002693/*
2694** Return a pointer to the sqlite3DefaultVfs structure. We use
2695** a function rather than give the structure global scope because
2696** some compilers (MSVC) do not allow forward declarations of
2697** initialized structures.
2698*/
2699sqlite3_vfs *sqlite3OsDefaultVfs(void){
2700 static sqlite3_vfs unixVfs = {
2701 1, /* iVersion */
2702 sizeof(unixFile), /* szOsFile */
2703 MAX_PATHNAME, /* mxPathname */
drh153c62c2007-08-24 03:51:33 +00002704 0, /* pNext */
2705 "unix", /* zName */
2706 0, /* pAppData */
2707
2708 unixOpen, /* xOpen */
2709 unixDelete, /* xDelete */
2710 unixAccess, /* xAccess */
2711 unixGetTempName, /* xGetTempName */
2712 unixFullPathname, /* xFullPathname */
2713 unixDlOpen, /* xDlOpen */
2714 unixDlError, /* xDlError */
2715 unixDlSym, /* xDlSym */
2716 unixDlClose, /* xDlClose */
2717 unixRandomness, /* xRandomness */
2718 unixSleep, /* xSleep */
2719 unixCurrentTime /* xCurrentTime */
2720 };
2721
2722 return &unixVfs;
2723}
drhdce8bdb2007-08-16 13:01:44 +00002724
drhbbd42a62004-05-22 17:41:58 +00002725#endif /* OS_UNIX */