blob: bf11e678afc4e06d0ad65db0c36b2483591fefb7 [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**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000209 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000210 int lastErrno; /* The unix errno from last I/O error */
211 void *lockingContext; /* Locking style specific state */
212 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
drh77197112011-03-15 19:08:48 +0000250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
drha7e61d82011-03-12 17:02:57 +0000251
252/*
drh198bf392006-01-06 21:52:49 +0000253** Include code that is common to all os_*.c files
254*/
255#include "os_common.h"
256
257/*
drh0ccebe72005-06-07 22:22:50 +0000258** Define various macros that are missing from some systems.
259*/
drhbbd42a62004-05-22 17:41:58 +0000260#ifndef O_LARGEFILE
261# define O_LARGEFILE 0
262#endif
263#ifdef SQLITE_DISABLE_LFS
264# undef O_LARGEFILE
265# define O_LARGEFILE 0
266#endif
267#ifndef O_NOFOLLOW
268# define O_NOFOLLOW 0
269#endif
270#ifndef O_BINARY
271# define O_BINARY 0
272#endif
273
274/*
drh2b4b5962005-06-15 17:47:55 +0000275** The threadid macro resolves to the thread-id or to 0. Used for
276** testing and debugging only.
277*/
drhd677b3d2007-08-20 22:48:41 +0000278#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000279#define threadid pthread_self()
280#else
281#define threadid 0
282#endif
283
drh99ab3b12011-03-02 15:09:07 +0000284/*
285** Many system calls are accessed through pointer-to-functions so that
286** they may be overridden at runtime to facilitate fault injection during
287** testing and sandboxing. The following array holds the names and pointers
288** to all overrideable system calls.
289*/
290static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000291 const char *zName; /* Name of the sytem call */
292 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
293 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000294} aSyscall[] = {
drh58ad5802011-03-23 22:02:23 +0000295 { "open", (sqlite3_syscall_ptr)open, 0 },
drh99ab3b12011-03-02 15:09:07 +0000296#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
297
drh58ad5802011-03-23 22:02:23 +0000298 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000299#define osClose ((int(*)(int))aSyscall[1].pCurrent)
300
drh58ad5802011-03-23 22:02:23 +0000301 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000302#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
303
drh58ad5802011-03-23 22:02:23 +0000304 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000305#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
306
drh58ad5802011-03-23 22:02:23 +0000307 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000308#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
309
310/*
311** The DJGPP compiler environment looks mostly like Unix, but it
312** lacks the fcntl() system call. So redefine fcntl() to be something
313** that always succeeds. This means that locking does not occur under
314** DJGPP. But it is DOS - what did you expect?
315*/
316#ifdef __DJGPP__
317 { "fstat", 0, 0 },
318#define osFstat(a,b,c) 0
319#else
drh58ad5802011-03-23 22:02:23 +0000320 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000321#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
322#endif
323
drh58ad5802011-03-23 22:02:23 +0000324 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
326
drh58ad5802011-03-23 22:02:23 +0000327 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000328#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000329
drh58ad5802011-03-23 22:02:23 +0000330 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000331#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
332
333#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
drh58ad5802011-03-23 22:02:23 +0000334 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000335#else
drh58ad5802011-03-23 22:02:23 +0000336 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000337#endif
338#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
339
340#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000341 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000342#else
drh58ad5802011-03-23 22:02:23 +0000343 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000344#endif
345#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000348#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
349
350#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
drh58ad5802011-03-23 22:02:23 +0000351 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000352#else
drh58ad5802011-03-23 22:02:23 +0000353 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000354#endif
355#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
356 aSyscall[12].pCurrent)
357
358#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000359 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000360#else
drh58ad5802011-03-23 22:02:23 +0000361 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000362#endif
363#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
364 aSyscall[13].pCurrent)
365
drh58ad5802011-03-23 22:02:23 +0000366 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drhe562be52011-03-02 18:01:10 +0000367#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
368
369#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000370 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000371#else
drh58ad5802011-03-23 22:02:23 +0000372 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000373#endif
dan0fd7d862011-03-29 10:04:23 +0000374#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000375
376}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000377
378/*
379** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000380** "unix" VFSes. Return SQLITE_OK opon successfully updating the
381** system call pointer, or SQLITE_NOTFOUND if there is no configurable
382** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000383*/
384static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000385 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
386 const char *zName, /* Name of system call to override */
387 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000388){
drh58ad5802011-03-23 22:02:23 +0000389 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000390 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000391
392 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000393 if( zName==0 ){
394 /* If no zName is given, restore all system calls to their default
395 ** settings and return NULL
396 */
397 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
398 if( aSyscall[i].pDefault ){
399 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh1df30962011-03-02 19:06:42 +0000400 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000401 }
402 }
403 }else{
404 /* If zName is specified, operate on only the one system call
405 ** specified.
406 */
407 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
408 if( strcmp(zName, aSyscall[i].zName)==0 ){
409 if( aSyscall[i].pDefault==0 ){
410 aSyscall[i].pDefault = aSyscall[i].pCurrent;
411 }
drh1df30962011-03-02 19:06:42 +0000412 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000413 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
414 aSyscall[i].pCurrent = pNewFunc;
415 break;
416 }
417 }
418 }
419 return rc;
420}
421
drh1df30962011-03-02 19:06:42 +0000422/*
423** Return the value of a system call. Return NULL if zName is not a
424** recognized system call name. NULL is also returned if the system call
425** is currently undefined.
426*/
drh58ad5802011-03-23 22:02:23 +0000427static sqlite3_syscall_ptr unixGetSystemCall(
428 sqlite3_vfs *pNotUsed,
429 const char *zName
430){
431 unsigned int i;
432
433 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000434 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
435 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
436 }
437 return 0;
438}
439
440/*
441** Return the name of the first system call after zName. If zName==NULL
442** then return the name of the first system call. Return NULL if zName
443** is the last system call or if zName is not the name of a valid
444** system call.
445*/
446static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000447 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000448
449 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000450 if( zName ){
451 for(i=0; i<ArraySize(aSyscall)-1; i++){
452 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000453 }
454 }
dan0fd7d862011-03-29 10:04:23 +0000455 for(i++; i<ArraySize(aSyscall); i++){
456 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000457 }
458 return 0;
459}
460
drhad4f1e52011-03-04 15:43:57 +0000461/*
462** Retry open() calls that fail due to EINTR
463*/
464static int robust_open(const char *z, int f, int m){
465 int rc;
466 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
467 return rc;
468}
danielk197713adf8a2004-06-03 16:08:41 +0000469
drh107886a2008-11-21 22:21:50 +0000470/*
dan9359c7b2009-08-21 08:29:10 +0000471** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000472** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000473** vxworksFileId objects used by this file, all of which may be
474** shared by multiple threads.
475**
476** Function unixMutexHeld() is used to assert() that the global mutex
477** is held when required. This function is only used as part of assert()
478** statements. e.g.
479**
480** unixEnterMutex()
481** assert( unixMutexHeld() );
482** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000483*/
484static void unixEnterMutex(void){
485 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
486}
487static void unixLeaveMutex(void){
488 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
489}
dan9359c7b2009-08-21 08:29:10 +0000490#ifdef SQLITE_DEBUG
491static int unixMutexHeld(void) {
492 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
493}
494#endif
drh107886a2008-11-21 22:21:50 +0000495
drh734c9862008-11-28 15:37:20 +0000496
497#ifdef SQLITE_DEBUG
498/*
499** Helper function for printing out trace information from debugging
500** binaries. This returns the string represetation of the supplied
501** integer lock-type.
502*/
drh308c2a52010-05-14 11:30:18 +0000503static const char *azFileLock(int eFileLock){
504 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000505 case NO_LOCK: return "NONE";
506 case SHARED_LOCK: return "SHARED";
507 case RESERVED_LOCK: return "RESERVED";
508 case PENDING_LOCK: return "PENDING";
509 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000510 }
511 return "ERROR";
512}
513#endif
514
515#ifdef SQLITE_LOCK_TRACE
516/*
517** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000518**
drh734c9862008-11-28 15:37:20 +0000519** This routine is used for troubleshooting locks on multithreaded
520** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
521** command-line option on the compiler. This code is normally
522** turned off.
523*/
524static int lockTrace(int fd, int op, struct flock *p){
525 char *zOpName, *zType;
526 int s;
527 int savedErrno;
528 if( op==F_GETLK ){
529 zOpName = "GETLK";
530 }else if( op==F_SETLK ){
531 zOpName = "SETLK";
532 }else{
drh99ab3b12011-03-02 15:09:07 +0000533 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000534 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
535 return s;
536 }
537 if( p->l_type==F_RDLCK ){
538 zType = "RDLCK";
539 }else if( p->l_type==F_WRLCK ){
540 zType = "WRLCK";
541 }else if( p->l_type==F_UNLCK ){
542 zType = "UNLCK";
543 }else{
544 assert( 0 );
545 }
546 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000547 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000548 savedErrno = errno;
549 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
550 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
551 (int)p->l_pid, s);
552 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
553 struct flock l2;
554 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000555 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000556 if( l2.l_type==F_RDLCK ){
557 zType = "RDLCK";
558 }else if( l2.l_type==F_WRLCK ){
559 zType = "WRLCK";
560 }else if( l2.l_type==F_UNLCK ){
561 zType = "UNLCK";
562 }else{
563 assert( 0 );
564 }
565 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
566 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
567 }
568 errno = savedErrno;
569 return s;
570}
drh99ab3b12011-03-02 15:09:07 +0000571#undef osFcntl
572#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000573#endif /* SQLITE_LOCK_TRACE */
574
drhff812312011-02-23 13:33:46 +0000575/*
576** Retry ftruncate() calls that fail due to EINTR
577*/
drhff812312011-02-23 13:33:46 +0000578static int robust_ftruncate(int h, sqlite3_int64 sz){
579 int rc;
drh99ab3b12011-03-02 15:09:07 +0000580 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000581 return rc;
582}
drh734c9862008-11-28 15:37:20 +0000583
584/*
585** This routine translates a standard POSIX errno code into something
586** useful to the clients of the sqlite3 functions. Specifically, it is
587** intended to translate a variety of "try again" errors into SQLITE_BUSY
588** and a variety of "please close the file descriptor NOW" errors into
589** SQLITE_IOERR
590**
591** Errors during initialization of locks, or file system support for locks,
592** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
593*/
594static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
595 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000596#if 0
597 /* At one point this code was not commented out. In theory, this branch
598 ** should never be hit, as this function should only be called after
599 ** a locking-related function (i.e. fcntl()) has returned non-zero with
600 ** the value of errno as the first argument. Since a system call has failed,
601 ** errno should be non-zero.
602 **
603 ** Despite this, if errno really is zero, we still don't want to return
604 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
605 ** propagated back to the caller. Commenting this branch out means errno==0
606 ** will be handled by the "default:" case below.
607 */
drh734c9862008-11-28 15:37:20 +0000608 case 0:
609 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000610#endif
611
drh734c9862008-11-28 15:37:20 +0000612 case EAGAIN:
613 case ETIMEDOUT:
614 case EBUSY:
615 case EINTR:
616 case ENOLCK:
617 /* random NFS retry error, unless during file system support
618 * introspection, in which it actually means what it says */
619 return SQLITE_BUSY;
620
621 case EACCES:
622 /* EACCES is like EAGAIN during locking operations, but not any other time*/
623 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
624 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
625 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
626 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
627 return SQLITE_BUSY;
628 }
629 /* else fall through */
630 case EPERM:
631 return SQLITE_PERM;
632
633 case EDEADLK:
634 return SQLITE_IOERR_BLOCKED;
635
636#if EOPNOTSUPP!=ENOTSUP
637 case EOPNOTSUPP:
638 /* something went terribly awry, unless during file system support
639 * introspection, in which it actually means what it says */
640#endif
641#ifdef ENOTSUP
642 case ENOTSUP:
643 /* invalid fd, unless during file system support introspection, in which
644 * it actually means what it says */
645#endif
646 case EIO:
647 case EBADF:
648 case EINVAL:
649 case ENOTCONN:
650 case ENODEV:
651 case ENXIO:
652 case ENOENT:
653 case ESTALE:
654 case ENOSYS:
655 /* these should force the client to close the file and reconnect */
656
657 default:
658 return sqliteIOErr;
659 }
660}
661
662
663
664/******************************************************************************
665****************** Begin Unique File ID Utility Used By VxWorks ***************
666**
667** On most versions of unix, we can get a unique ID for a file by concatenating
668** the device number and the inode number. But this does not work on VxWorks.
669** On VxWorks, a unique file id must be based on the canonical filename.
670**
671** A pointer to an instance of the following structure can be used as a
672** unique file ID in VxWorks. Each instance of this structure contains
673** a copy of the canonical filename. There is also a reference count.
674** The structure is reclaimed when the number of pointers to it drops to
675** zero.
676**
677** There are never very many files open at one time and lookups are not
678** a performance-critical path, so it is sufficient to put these
679** structures on a linked list.
680*/
681struct vxworksFileId {
682 struct vxworksFileId *pNext; /* Next in a list of them all */
683 int nRef; /* Number of references to this one */
684 int nName; /* Length of the zCanonicalName[] string */
685 char *zCanonicalName; /* Canonical filename */
686};
687
688#if OS_VXWORKS
689/*
drh9b35ea62008-11-29 02:20:26 +0000690** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000691** variable:
692*/
693static struct vxworksFileId *vxworksFileList = 0;
694
695/*
696** Simplify a filename into its canonical form
697** by making the following changes:
698**
699** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000700** * convert /./ into just /
701** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000702**
703** Changes are made in-place. Return the new name length.
704**
705** The original filename is in z[0..n-1]. Return the number of
706** characters in the simplified name.
707*/
708static int vxworksSimplifyName(char *z, int n){
709 int i, j;
710 while( n>1 && z[n-1]=='/' ){ n--; }
711 for(i=j=0; i<n; i++){
712 if( z[i]=='/' ){
713 if( z[i+1]=='/' ) continue;
714 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
715 i += 1;
716 continue;
717 }
718 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
719 while( j>0 && z[j-1]!='/' ){ j--; }
720 if( j>0 ){ j--; }
721 i += 2;
722 continue;
723 }
724 }
725 z[j++] = z[i];
726 }
727 z[j] = 0;
728 return j;
729}
730
731/*
732** Find a unique file ID for the given absolute pathname. Return
733** a pointer to the vxworksFileId object. This pointer is the unique
734** file ID.
735**
736** The nRef field of the vxworksFileId object is incremented before
737** the object is returned. A new vxworksFileId object is created
738** and added to the global list if necessary.
739**
740** If a memory allocation error occurs, return NULL.
741*/
742static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
743 struct vxworksFileId *pNew; /* search key and new file ID */
744 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
745 int n; /* Length of zAbsoluteName string */
746
747 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000748 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000749 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
750 if( pNew==0 ) return 0;
751 pNew->zCanonicalName = (char*)&pNew[1];
752 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
753 n = vxworksSimplifyName(pNew->zCanonicalName, n);
754
755 /* Search for an existing entry that matching the canonical name.
756 ** If found, increment the reference count and return a pointer to
757 ** the existing file ID.
758 */
759 unixEnterMutex();
760 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
761 if( pCandidate->nName==n
762 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
763 ){
764 sqlite3_free(pNew);
765 pCandidate->nRef++;
766 unixLeaveMutex();
767 return pCandidate;
768 }
769 }
770
771 /* No match was found. We will make a new file ID */
772 pNew->nRef = 1;
773 pNew->nName = n;
774 pNew->pNext = vxworksFileList;
775 vxworksFileList = pNew;
776 unixLeaveMutex();
777 return pNew;
778}
779
780/*
781** Decrement the reference count on a vxworksFileId object. Free
782** the object when the reference count reaches zero.
783*/
784static void vxworksReleaseFileId(struct vxworksFileId *pId){
785 unixEnterMutex();
786 assert( pId->nRef>0 );
787 pId->nRef--;
788 if( pId->nRef==0 ){
789 struct vxworksFileId **pp;
790 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
791 assert( *pp==pId );
792 *pp = pId->pNext;
793 sqlite3_free(pId);
794 }
795 unixLeaveMutex();
796}
797#endif /* OS_VXWORKS */
798/*************** End of Unique File ID Utility Used By VxWorks ****************
799******************************************************************************/
800
801
802/******************************************************************************
803*************************** Posix Advisory Locking ****************************
804**
drh9b35ea62008-11-29 02:20:26 +0000805** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000806** section 6.5.2.2 lines 483 through 490 specify that when a process
807** sets or clears a lock, that operation overrides any prior locks set
808** by the same process. It does not explicitly say so, but this implies
809** that it overrides locks set by the same process using a different
810** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000811**
812** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000813** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
814**
815** Suppose ./file1 and ./file2 are really the same file (because
816** one is a hard or symbolic link to the other) then if you set
817** an exclusive lock on fd1, then try to get an exclusive lock
818** on fd2, it works. I would have expected the second lock to
819** fail since there was already a lock on the file due to fd1.
820** But not so. Since both locks came from the same process, the
821** second overrides the first, even though they were on different
822** file descriptors opened on different file names.
823**
drh734c9862008-11-28 15:37:20 +0000824** This means that we cannot use POSIX locks to synchronize file access
825** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000826** to synchronize access for threads in separate processes, but not
827** threads within the same process.
828**
829** To work around the problem, SQLite has to manage file locks internally
830** on its own. Whenever a new database is opened, we have to find the
831** specific inode of the database file (the inode is determined by the
832** st_dev and st_ino fields of the stat structure that fstat() fills in)
833** and check for locks already existing on that inode. When locks are
834** created or removed, we have to look at our own internal record of the
835** locks to see if another thread has previously set a lock on that same
836** inode.
837**
drh9b35ea62008-11-29 02:20:26 +0000838** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
839** For VxWorks, we have to use the alternative unique ID system based on
840** canonical filename and implemented in the previous division.)
841**
danielk1977ad94b582007-08-20 06:44:22 +0000842** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000843** descriptor. It is now a structure that holds the integer file
844** descriptor and a pointer to a structure that describes the internal
845** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000846** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000847** point to the same locking structure. The locking structure keeps
848** a reference count (so we will know when to delete it) and a "cnt"
849** field that tells us its internal lock status. cnt==0 means the
850** file is unlocked. cnt==-1 means the file has an exclusive lock.
851** cnt>0 means there are cnt shared locks on the file.
852**
853** Any attempt to lock or unlock a file first checks the locking
854** structure. The fcntl() system call is only invoked to set a
855** POSIX lock if the internal lock structure transitions between
856** a locked and an unlocked state.
857**
drh734c9862008-11-28 15:37:20 +0000858** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000859**
860** If you close a file descriptor that points to a file that has locks,
861** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000862** released. To work around this problem, each unixInodeInfo object
863** maintains a count of the number of pending locks on tha inode.
864** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000865** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000866** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000867** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000868** be closed and that list is walked (and cleared) when the last lock
869** clears.
870**
drh9b35ea62008-11-29 02:20:26 +0000871** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000872**
drh9b35ea62008-11-29 02:20:26 +0000873** Many older versions of linux use the LinuxThreads library which is
874** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000875** A cannot be modified or overridden by a different thread B.
876** Only thread A can modify the lock. Locking behavior is correct
877** if the appliation uses the newer Native Posix Thread Library (NPTL)
878** on linux - with NPTL a lock created by thread A can override locks
879** in thread B. But there is no way to know at compile-time which
880** threading library is being used. So there is no way to know at
881** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000882** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000883** current process.
drh5fdae772004-06-29 03:29:00 +0000884**
drh8af6c222010-05-14 12:43:01 +0000885** SQLite used to support LinuxThreads. But support for LinuxThreads
886** was dropped beginning with version 3.7.0. SQLite will still work with
887** LinuxThreads provided that (1) there is no more than one connection
888** per database file in the same process and (2) database connections
889** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000890*/
891
892/*
893** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000894** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000895*/
896struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000897 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000898#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000899 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000900#else
drh107886a2008-11-21 22:21:50 +0000901 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000902#endif
903};
904
905/*
drhbbd42a62004-05-22 17:41:58 +0000906** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000907** inode. Or, on LinuxThreads, there is one of these structures for
908** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000909**
danielk1977ad94b582007-08-20 06:44:22 +0000910** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000911** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000912** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000913*/
drh8af6c222010-05-14 12:43:01 +0000914struct unixInodeInfo {
915 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000916 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000917 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
918 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000919 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000920 unixShmNode *pShmNode; /* Shared memory associated with this inode */
921 int nLock; /* Number of outstanding file locks */
922 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
923 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
924 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000925#if defined(SQLITE_ENABLE_LOCKING_STYLE)
926 unsigned long long sharedByte; /* for AFP simulated shared lock */
927#endif
drh6c7d5c52008-11-21 20:32:33 +0000928#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000929 sem_t *pSem; /* Named POSIX semaphore */
930 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000931#endif
drhbbd42a62004-05-22 17:41:58 +0000932};
933
drhda0e7682008-07-30 15:27:54 +0000934/*
drh8af6c222010-05-14 12:43:01 +0000935** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000936*/
drhd91c68f2010-05-14 14:52:25 +0000937static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000938
drh5fdae772004-06-29 03:29:00 +0000939/*
dane18d4952011-02-21 11:46:24 +0000940**
941** This function - unixLogError_x(), is only ever called via the macro
942** unixLogError().
943**
944** It is invoked after an error occurs in an OS function and errno has been
945** set. It logs a message using sqlite3_log() containing the current value of
946** errno and, if possible, the human-readable equivalent from strerror() or
947** strerror_r().
948**
949** The first argument passed to the macro should be the error code that
950** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
951** The two subsequent arguments should be the name of the OS function that
952** failed (e.g. "unlink", "open") and the the associated file-system path,
953** if any.
954*/
drh0e9365c2011-03-02 02:08:13 +0000955#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
956static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000957 int errcode, /* SQLite error code */
958 const char *zFunc, /* Name of OS function that failed */
959 const char *zPath, /* File path associated with error */
960 int iLine /* Source line number where error occurred */
961){
962 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000963 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000964
965 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
966 ** the strerror() function to obtain the human-readable error message
967 ** equivalent to errno. Otherwise, use strerror_r().
968 */
969#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
970 char aErr[80];
971 memset(aErr, 0, sizeof(aErr));
972 zErr = aErr;
973
974 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
975 ** assume that the system provides the the GNU version of strerror_r() that
976 ** returns a pointer to a buffer containing the error message. That pointer
977 ** may point to aErr[], or it may point to some static storage somewhere.
978 ** Otherwise, assume that the system provides the POSIX version of
979 ** strerror_r(), which always writes an error message into aErr[].
980 **
981 ** If the code incorrectly assumes that it is the POSIX version that is
982 ** available, the error message will often be an empty string. Not a
983 ** huge problem. Incorrectly concluding that the GNU version is available
984 ** could lead to a segfault though.
985 */
986#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
987 zErr =
988# endif
drh0e9365c2011-03-02 02:08:13 +0000989 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000990
991#elif SQLITE_THREADSAFE
992 /* This is a threadsafe build, but strerror_r() is not available. */
993 zErr = "";
994#else
995 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000996 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000997#endif
998
999 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001000 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001001 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001002 "os_unix.c:%d: (%d) %s(%s) - %s",
1003 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001004 );
1005
1006 return errcode;
1007}
1008
drh0e9365c2011-03-02 02:08:13 +00001009/*
1010** Close a file descriptor.
1011**
1012** We assume that close() almost always works, since it is only in a
1013** very sick application or on a very sick platform that it might fail.
1014** If it does fail, simply leak the file descriptor, but do log the
1015** error.
1016**
1017** Note that it is not safe to retry close() after EINTR since the
1018** file descriptor might have already been reused by another thread.
1019** So we don't even try to recover from an EINTR. Just log the error
1020** and move on.
1021*/
1022static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001023 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001024 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1025 pFile ? pFile->zPath : 0, lineno);
1026 }
1027}
dane18d4952011-02-21 11:46:24 +00001028
1029/*
danb0ac3e32010-06-16 10:55:42 +00001030** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001031*/
drh0e9365c2011-03-02 02:08:13 +00001032static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001033 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001034 UnixUnusedFd *p;
1035 UnixUnusedFd *pNext;
1036 for(p=pInode->pUnused; p; p=pNext){
1037 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001038 robust_close(pFile, p->fd, __LINE__);
1039 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001040 }
drh0e9365c2011-03-02 02:08:13 +00001041 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001042}
1043
1044/*
drh8af6c222010-05-14 12:43:01 +00001045** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001046**
1047** The mutex entered using the unixEnterMutex() function must be held
1048** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001049*/
danb0ac3e32010-06-16 10:55:42 +00001050static void releaseInodeInfo(unixFile *pFile){
1051 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001052 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001053 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001054 pInode->nRef--;
1055 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001056 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001057 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001058 if( pInode->pPrev ){
1059 assert( pInode->pPrev->pNext==pInode );
1060 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001061 }else{
drh8af6c222010-05-14 12:43:01 +00001062 assert( inodeList==pInode );
1063 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001064 }
drh8af6c222010-05-14 12:43:01 +00001065 if( pInode->pNext ){
1066 assert( pInode->pNext->pPrev==pInode );
1067 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001068 }
drh8af6c222010-05-14 12:43:01 +00001069 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001070 }
drhbbd42a62004-05-22 17:41:58 +00001071 }
1072}
1073
1074/*
drh8af6c222010-05-14 12:43:01 +00001075** Given a file descriptor, locate the unixInodeInfo object that
1076** describes that file descriptor. Create a new one if necessary. The
1077** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001078**
dan9359c7b2009-08-21 08:29:10 +00001079** The mutex entered using the unixEnterMutex() function must be held
1080** when this function is called.
1081**
drh6c7d5c52008-11-21 20:32:33 +00001082** Return an appropriate error code.
1083*/
drh8af6c222010-05-14 12:43:01 +00001084static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001085 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001086 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001087){
1088 int rc; /* System call return code */
1089 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001090 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1091 struct stat statbuf; /* Low-level file information */
1092 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001093
dan9359c7b2009-08-21 08:29:10 +00001094 assert( unixMutexHeld() );
1095
drh6c7d5c52008-11-21 20:32:33 +00001096 /* Get low-level information about the file that we can used to
1097 ** create a unique name for the file.
1098 */
1099 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001100 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001101 if( rc!=0 ){
1102 pFile->lastErrno = errno;
1103#ifdef EOVERFLOW
1104 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1105#endif
1106 return SQLITE_IOERR;
1107 }
1108
drheb0d74f2009-02-03 15:27:02 +00001109#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001110 /* On OS X on an msdos filesystem, the inode number is reported
1111 ** incorrectly for zero-size files. See ticket #3260. To work
1112 ** around this problem (we consider it a bug in OS X, not SQLite)
1113 ** we always increase the file size to 1 by writing a single byte
1114 ** prior to accessing the inode number. The one byte written is
1115 ** an ASCII 'S' character which also happens to be the first byte
1116 ** in the header of every SQLite database. In this way, if there
1117 ** is a race condition such that another thread has already populated
1118 ** the first page of the database, no damage is done.
1119 */
drh7ed97b92010-01-20 13:07:21 +00001120 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001121 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001122 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001123 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001124 return SQLITE_IOERR;
1125 }
drh99ab3b12011-03-02 15:09:07 +00001126 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001127 if( rc!=0 ){
1128 pFile->lastErrno = errno;
1129 return SQLITE_IOERR;
1130 }
1131 }
drheb0d74f2009-02-03 15:27:02 +00001132#endif
drh6c7d5c52008-11-21 20:32:33 +00001133
drh8af6c222010-05-14 12:43:01 +00001134 memset(&fileId, 0, sizeof(fileId));
1135 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001136#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001137 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001138#else
drh8af6c222010-05-14 12:43:01 +00001139 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001140#endif
drh8af6c222010-05-14 12:43:01 +00001141 pInode = inodeList;
1142 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1143 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001144 }
drh8af6c222010-05-14 12:43:01 +00001145 if( pInode==0 ){
1146 pInode = sqlite3_malloc( sizeof(*pInode) );
1147 if( pInode==0 ){
1148 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001149 }
drh8af6c222010-05-14 12:43:01 +00001150 memset(pInode, 0, sizeof(*pInode));
1151 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1152 pInode->nRef = 1;
1153 pInode->pNext = inodeList;
1154 pInode->pPrev = 0;
1155 if( inodeList ) inodeList->pPrev = pInode;
1156 inodeList = pInode;
1157 }else{
1158 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001159 }
drh8af6c222010-05-14 12:43:01 +00001160 *ppInode = pInode;
1161 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001162}
drh6c7d5c52008-11-21 20:32:33 +00001163
aswift5b1a2562008-08-22 00:22:35 +00001164
1165/*
danielk197713adf8a2004-06-03 16:08:41 +00001166** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001167** file by this or any other process. If such a lock is held, set *pResOut
1168** to a non-zero value otherwise *pResOut is set to zero. The return value
1169** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001170*/
danielk1977861f7452008-06-05 11:39:11 +00001171static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001172 int rc = SQLITE_OK;
1173 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001174 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001175
danielk1977861f7452008-06-05 11:39:11 +00001176 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1177
drh054889e2005-11-30 03:20:31 +00001178 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001179 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001180
1181 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001182 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001183 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001184 }
1185
drh2ac3ee92004-06-07 16:27:46 +00001186 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001187 */
danielk197709480a92009-02-09 05:32:32 +00001188#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001189 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001190 struct flock lock;
1191 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001192 lock.l_start = RESERVED_BYTE;
1193 lock.l_len = 1;
1194 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001195 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001196 int tErrno = errno;
1197 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1198 pFile->lastErrno = tErrno;
1199 } else if( lock.l_type!=F_UNLCK ){
1200 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001201 }
1202 }
danielk197709480a92009-02-09 05:32:32 +00001203#endif
danielk197713adf8a2004-06-03 16:08:41 +00001204
drh6c7d5c52008-11-21 20:32:33 +00001205 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001206 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001207
aswift5b1a2562008-08-22 00:22:35 +00001208 *pResOut = reserved;
1209 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001210}
1211
1212/*
drha7e61d82011-03-12 17:02:57 +00001213** Attempt to set a system-lock on the file pFile. The lock is
1214** described by pLock.
1215**
drh77197112011-03-15 19:08:48 +00001216** If the pFile was opened read/write from unix-excl, then the only lock
1217** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001218** the first time any lock is attempted. All subsequent system locking
1219** operations become no-ops. Locking operations still happen internally,
1220** in order to coordinate access between separate database connections
1221** within this process, but all of that is handled in memory and the
1222** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001223**
1224** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1225** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1226** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001227**
1228** Zero is returned if the call completes successfully, or -1 if a call
1229** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001230*/
1231static int unixFileLock(unixFile *pFile, struct flock *pLock){
1232 int rc;
drh3cb93392011-03-12 18:10:44 +00001233 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001234 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001235 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001236 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1237 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1238 ){
drh3cb93392011-03-12 18:10:44 +00001239 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001240 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001241 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001242 lock.l_whence = SEEK_SET;
1243 lock.l_start = SHARED_FIRST;
1244 lock.l_len = SHARED_SIZE;
1245 lock.l_type = F_WRLCK;
1246 rc = osFcntl(pFile->h, F_SETLK, &lock);
1247 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001248 pInode->bProcessLock = 1;
1249 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001250 }else{
1251 rc = 0;
1252 }
1253 }else{
1254 rc = osFcntl(pFile->h, F_SETLK, pLock);
1255 }
1256 return rc;
1257}
1258
1259/*
drh308c2a52010-05-14 11:30:18 +00001260** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001261** of the following:
1262**
drh2ac3ee92004-06-07 16:27:46 +00001263** (1) SHARED_LOCK
1264** (2) RESERVED_LOCK
1265** (3) PENDING_LOCK
1266** (4) EXCLUSIVE_LOCK
1267**
drhb3e04342004-06-08 00:47:47 +00001268** Sometimes when requesting one lock state, additional lock states
1269** are inserted in between. The locking might fail on one of the later
1270** transitions leaving the lock state different from what it started but
1271** still short of its goal. The following chart shows the allowed
1272** transitions and the inserted intermediate states:
1273**
1274** UNLOCKED -> SHARED
1275** SHARED -> RESERVED
1276** SHARED -> (PENDING) -> EXCLUSIVE
1277** RESERVED -> (PENDING) -> EXCLUSIVE
1278** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001279**
drha6abd042004-06-09 17:37:22 +00001280** This routine will only increase a lock. Use the sqlite3OsUnlock()
1281** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001282*/
drh308c2a52010-05-14 11:30:18 +00001283static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001284 /* The following describes the implementation of the various locks and
1285 ** lock transitions in terms of the POSIX advisory shared and exclusive
1286 ** lock primitives (called read-locks and write-locks below, to avoid
1287 ** confusion with SQLite lock names). The algorithms are complicated
1288 ** slightly in order to be compatible with windows systems simultaneously
1289 ** accessing the same database file, in case that is ever required.
1290 **
1291 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1292 ** byte', each single bytes at well known offsets, and the 'shared byte
1293 ** range', a range of 510 bytes at a well known offset.
1294 **
1295 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1296 ** byte'. If this is successful, a random byte from the 'shared byte
1297 ** range' is read-locked and the lock on the 'pending byte' released.
1298 **
danielk197790ba3bd2004-06-25 08:32:25 +00001299 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1300 ** A RESERVED lock is implemented by grabbing a write-lock on the
1301 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001302 **
1303 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001304 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1305 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1306 ** obtained, but existing SHARED locks are allowed to persist. A process
1307 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1308 ** This property is used by the algorithm for rolling back a journal file
1309 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001310 **
danielk197790ba3bd2004-06-25 08:32:25 +00001311 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1312 ** implemented by obtaining a write-lock on the entire 'shared byte
1313 ** range'. Since all other locks require a read-lock on one of the bytes
1314 ** within this range, this ensures that no other locks are held on the
1315 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001316 **
1317 ** The reason a single byte cannot be used instead of the 'shared byte
1318 ** range' is that some versions of windows do not support read-locks. By
1319 ** locking a random byte from a range, concurrent SHARED locks may exist
1320 ** even if the locking primitive used is always a write-lock.
1321 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001322 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001323 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001324 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001325 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001326 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001327
drh054889e2005-11-30 03:20:31 +00001328 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001329 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1330 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001331 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001332
1333 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001334 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001335 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001336 */
drh308c2a52010-05-14 11:30:18 +00001337 if( pFile->eFileLock>=eFileLock ){
1338 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1339 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001340 return SQLITE_OK;
1341 }
1342
drh0c2694b2009-09-03 16:23:44 +00001343 /* Make sure the locking sequence is correct.
1344 ** (1) We never move from unlocked to anything higher than shared lock.
1345 ** (2) SQLite never explicitly requests a pendig lock.
1346 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001347 */
drh308c2a52010-05-14 11:30:18 +00001348 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1349 assert( eFileLock!=PENDING_LOCK );
1350 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001351
drh8af6c222010-05-14 12:43:01 +00001352 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001353 */
drh6c7d5c52008-11-21 20:32:33 +00001354 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001355 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001356
danielk1977ad94b582007-08-20 06:44:22 +00001357 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 ** handle that precludes the requested lock, return BUSY.
1359 */
drh8af6c222010-05-14 12:43:01 +00001360 if( (pFile->eFileLock!=pInode->eFileLock &&
1361 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001362 ){
1363 rc = SQLITE_BUSY;
1364 goto end_lock;
1365 }
1366
1367 /* If a SHARED lock is requested, and some thread using this PID already
1368 ** has a SHARED or RESERVED lock, then increment reference counts and
1369 ** return SQLITE_OK.
1370 */
drh308c2a52010-05-14 11:30:18 +00001371 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001372 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001373 assert( eFileLock==SHARED_LOCK );
1374 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001375 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001376 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001377 pInode->nShared++;
1378 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001379 goto end_lock;
1380 }
1381
danielk19779a1d0ab2004-06-01 14:09:28 +00001382
drh3cde3bb2004-06-12 02:17:14 +00001383 /* A PENDING lock is needed before acquiring a SHARED lock and before
1384 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1385 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001386 */
drh0c2694b2009-09-03 16:23:44 +00001387 lock.l_len = 1L;
1388 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001389 if( eFileLock==SHARED_LOCK
1390 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001391 ){
drh308c2a52010-05-14 11:30:18 +00001392 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001393 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001394 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001395 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001396 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001397 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001398 pFile->lastErrno = tErrno;
1399 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001400 goto end_lock;
1401 }
drh3cde3bb2004-06-12 02:17:14 +00001402 }
1403
1404
1405 /* If control gets to this point, then actually go ahead and make
1406 ** operating system calls for the specified lock.
1407 */
drh308c2a52010-05-14 11:30:18 +00001408 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001409 assert( pInode->nShared==0 );
1410 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001411 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001412
drh2ac3ee92004-06-07 16:27:46 +00001413 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001414 lock.l_start = SHARED_FIRST;
1415 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001416 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001417 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001418 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001419 }
dan661d71a2011-03-30 19:08:03 +00001420
drh2ac3ee92004-06-07 16:27:46 +00001421 /* Drop the temporary PENDING lock */
1422 lock.l_start = PENDING_BYTE;
1423 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001424 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001425 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1426 /* This could happen with a network mount */
1427 tErrno = errno;
1428 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
drh2b4b5962005-06-15 17:47:55 +00001429 }
dan661d71a2011-03-30 19:08:03 +00001430
1431 if( rc ){
1432 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001433 pFile->lastErrno = tErrno;
1434 }
dan661d71a2011-03-30 19:08:03 +00001435 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001436 }else{
drh308c2a52010-05-14 11:30:18 +00001437 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001438 pInode->nLock++;
1439 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001440 }
drh8af6c222010-05-14 12:43:01 +00001441 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001442 /* We are trying for an exclusive lock but another thread in this
1443 ** same process is still holding a shared lock. */
1444 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001445 }else{
drh3cde3bb2004-06-12 02:17:14 +00001446 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001447 ** assumed that there is a SHARED or greater lock on the file
1448 ** already.
1449 */
drh308c2a52010-05-14 11:30:18 +00001450 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001451 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001452
1453 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1454 if( eFileLock==RESERVED_LOCK ){
1455 lock.l_start = RESERVED_BYTE;
1456 lock.l_len = 1L;
1457 }else{
1458 lock.l_start = SHARED_FIRST;
1459 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001460 }
dan661d71a2011-03-30 19:08:03 +00001461
1462 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001463 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001464 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001465 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001466 pFile->lastErrno = tErrno;
1467 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001468 }
drhbbd42a62004-05-22 17:41:58 +00001469 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001470
drh8f941bc2009-01-14 23:03:40 +00001471
1472#ifndef NDEBUG
1473 /* Set up the transaction-counter change checking flags when
1474 ** transitioning from a SHARED to a RESERVED lock. The change
1475 ** from SHARED to RESERVED marks the beginning of a normal
1476 ** write operation (not a hot journal rollback).
1477 */
1478 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001479 && pFile->eFileLock<=SHARED_LOCK
1480 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001481 ){
1482 pFile->transCntrChng = 0;
1483 pFile->dbUpdate = 0;
1484 pFile->inNormalWrite = 1;
1485 }
1486#endif
1487
1488
danielk1977ecb2a962004-06-02 06:30:16 +00001489 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001490 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001491 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001492 }else if( eFileLock==EXCLUSIVE_LOCK ){
1493 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001494 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001495 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001496
1497end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001498 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001499 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1500 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001501 return rc;
1502}
1503
1504/*
dan08da86a2009-08-21 17:18:03 +00001505** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001506** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001507*/
1508static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001509 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001510 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001511 p->pNext = pInode->pUnused;
1512 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001513 pFile->h = -1;
1514 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001515}
1516
1517/*
drh308c2a52010-05-14 11:30:18 +00001518** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001519** must be either NO_LOCK or SHARED_LOCK.
1520**
1521** If the locking level of the file descriptor is already at or below
1522** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001523**
1524** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1525** the byte range is divided into 2 parts and the first part is unlocked then
1526** set to a read lock, then the other part is simply unlocked. This works
1527** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1528** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001529*/
drha7e61d82011-03-12 17:02:57 +00001530static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001531 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001532 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001533 struct flock lock;
1534 int rc = SQLITE_OK;
1535 int h;
drh0c2694b2009-09-03 16:23:44 +00001536 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001537
drh054889e2005-11-30 03:20:31 +00001538 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001539 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001540 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001541 getpid()));
drha6abd042004-06-09 17:37:22 +00001542
drh308c2a52010-05-14 11:30:18 +00001543 assert( eFileLock<=SHARED_LOCK );
1544 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001545 return SQLITE_OK;
1546 }
drh6c7d5c52008-11-21 20:32:33 +00001547 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001548 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001549 pInode = pFile->pInode;
1550 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001551 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001552 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001553 SimulateIOErrorBenign(1);
1554 SimulateIOError( h=(-1) )
1555 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001556
1557#ifndef NDEBUG
1558 /* When reducing a lock such that other processes can start
1559 ** reading the database file again, make sure that the
1560 ** transaction counter was updated if any part of the database
1561 ** file changed. If the transaction counter is not updated,
1562 ** other connections to the same file might not realize that
1563 ** the file has changed and hence might not know to flush their
1564 ** cache. The use of a stale cache can lead to database corruption.
1565 */
dan7c246102010-04-12 19:00:29 +00001566#if 0
drh8f941bc2009-01-14 23:03:40 +00001567 assert( pFile->inNormalWrite==0
1568 || pFile->dbUpdate==0
1569 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001570#endif
drh8f941bc2009-01-14 23:03:40 +00001571 pFile->inNormalWrite = 0;
1572#endif
1573
drh7ed97b92010-01-20 13:07:21 +00001574 /* downgrading to a shared lock on NFS involves clearing the write lock
1575 ** before establishing the readlock - to avoid a race condition we downgrade
1576 ** the lock in 2 blocks, so that part of the range will be covered by a
1577 ** write lock until the rest is covered by a read lock:
1578 ** 1: [WWWWW]
1579 ** 2: [....W]
1580 ** 3: [RRRRW]
1581 ** 4: [RRRR.]
1582 */
drh308c2a52010-05-14 11:30:18 +00001583 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001584
1585#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001586 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001587 assert( handleNFSUnlock==0 );
1588#endif
1589#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001590 if( handleNFSUnlock ){
1591 off_t divSize = SHARED_SIZE - 1;
1592
1593 lock.l_type = F_UNLCK;
1594 lock.l_whence = SEEK_SET;
1595 lock.l_start = SHARED_FIRST;
1596 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001597 if( unixFileLock(pFile,, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001598 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001599 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1600 if( IS_LOCK_ERROR(rc) ){
1601 pFile->lastErrno = tErrno;
1602 }
1603 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001604 }
drh7ed97b92010-01-20 13:07:21 +00001605 lock.l_type = F_RDLCK;
1606 lock.l_whence = SEEK_SET;
1607 lock.l_start = SHARED_FIRST;
1608 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001609 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001610 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001611 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1612 if( IS_LOCK_ERROR(rc) ){
1613 pFile->lastErrno = tErrno;
1614 }
1615 goto end_unlock;
1616 }
1617 lock.l_type = F_UNLCK;
1618 lock.l_whence = SEEK_SET;
1619 lock.l_start = SHARED_FIRST+divSize;
1620 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001621 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001622 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001623 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1624 if( IS_LOCK_ERROR(rc) ){
1625 pFile->lastErrno = tErrno;
1626 }
1627 goto end_unlock;
1628 }
drh30f776f2011-02-25 03:25:07 +00001629 }else
1630#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1631 {
drh7ed97b92010-01-20 13:07:21 +00001632 lock.l_type = F_RDLCK;
1633 lock.l_whence = SEEK_SET;
1634 lock.l_start = SHARED_FIRST;
1635 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001636 if( unixFileLock(pFile, &lock) ){
drhc05a9a82010-03-04 16:12:34 +00001637 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001638 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
dan661d71a2011-03-30 19:08:03 +00001639 if( rc!=SQLITE_BUSY ){
drh7ed97b92010-01-20 13:07:21 +00001640 pFile->lastErrno = tErrno;
1641 }
1642 goto end_unlock;
1643 }
drh9c105bb2004-10-02 20:38:28 +00001644 }
1645 }
drhbbd42a62004-05-22 17:41:58 +00001646 lock.l_type = F_UNLCK;
1647 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001648 lock.l_start = PENDING_BYTE;
1649 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001650 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001651 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001652 }else{
drh0c2694b2009-09-03 16:23:44 +00001653 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001654 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
dan661d71a2011-03-30 19:08:03 +00001655 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001656 pFile->lastErrno = tErrno;
1657 }
drhcd731cf2009-03-28 23:23:02 +00001658 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001659 }
drhbbd42a62004-05-22 17:41:58 +00001660 }
drh308c2a52010-05-14 11:30:18 +00001661 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001662 /* Decrement the shared lock counter. Release the lock using an
1663 ** OS call only when all threads in this same process have released
1664 ** the lock.
1665 */
drh8af6c222010-05-14 12:43:01 +00001666 pInode->nShared--;
1667 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001668 lock.l_type = F_UNLCK;
1669 lock.l_whence = SEEK_SET;
1670 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001671 SimulateIOErrorBenign(1);
1672 SimulateIOError( h=(-1) )
1673 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001674 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001675 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001676 }else{
drh0c2694b2009-09-03 16:23:44 +00001677 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001678 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
dan661d71a2011-03-30 19:08:03 +00001679 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001680 pFile->lastErrno = tErrno;
1681 }
drh8af6c222010-05-14 12:43:01 +00001682 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001683 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001684 }
drha6abd042004-06-09 17:37:22 +00001685 }
1686
drhbbd42a62004-05-22 17:41:58 +00001687 /* Decrement the count of locks against this same file. When the
1688 ** count reaches zero, close any other file descriptors whose close
1689 ** was deferred because of outstanding locks.
1690 */
drh8af6c222010-05-14 12:43:01 +00001691 pInode->nLock--;
1692 assert( pInode->nLock>=0 );
1693 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001694 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001695 }
1696 }
aswift5b1a2562008-08-22 00:22:35 +00001697
1698end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001699 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001700 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001701 return rc;
drhbbd42a62004-05-22 17:41:58 +00001702}
1703
1704/*
drh308c2a52010-05-14 11:30:18 +00001705** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001706** must be either NO_LOCK or SHARED_LOCK.
1707**
1708** If the locking level of the file descriptor is already at or below
1709** the requested locking level, this routine is a no-op.
1710*/
drh308c2a52010-05-14 11:30:18 +00001711static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001712 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001713}
1714
1715/*
danielk1977e339d652008-06-28 11:23:00 +00001716** This function performs the parts of the "close file" operation
1717** common to all locking schemes. It closes the directory and file
1718** handles, if they are valid, and sets all fields of the unixFile
1719** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001720**
1721** It is *not* necessary to hold the mutex when this routine is called,
1722** even on VxWorks. A mutex will be acquired on VxWorks by the
1723** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001724*/
1725static int closeUnixFile(sqlite3_file *id){
1726 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001727 if( pFile->dirfd>=0 ){
1728 robust_close(pFile, pFile->dirfd, __LINE__);
1729 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001730 }
dan661d71a2011-03-30 19:08:03 +00001731 if( pFile->h>=0 ){
1732 robust_close(pFile, pFile->h, __LINE__);
1733 pFile->h = -1;
1734 }
1735#if OS_VXWORKS
1736 if( pFile->pId ){
1737 if( pFile->isDelete ){
1738 unlink(pFile->pId->zCanonicalName);
1739 }
1740 vxworksReleaseFileId(pFile->pId);
1741 pFile->pId = 0;
1742 }
1743#endif
1744 OSTRACE(("CLOSE %-3d\n", pFile->h));
1745 OpenCounter(-1);
1746 sqlite3_free(pFile->pUnused);
1747 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001748 return SQLITE_OK;
1749}
1750
1751/*
danielk1977e3026632004-06-22 11:29:02 +00001752** Close a file.
1753*/
danielk197762079062007-08-15 17:08:46 +00001754static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001755 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001756 unixFile *pFile = (unixFile *)id;
1757 unixUnlock(id, NO_LOCK);
1758 unixEnterMutex();
1759
1760 /* unixFile.pInode is always valid here. Otherwise, a different close
1761 ** routine (e.g. nolockClose()) would be called instead.
1762 */
1763 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1764 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1765 /* If there are outstanding locks, do not actually close the file just
1766 ** yet because that would clear those locks. Instead, add the file
1767 ** descriptor to pInode->pUnused list. It will be automatically closed
1768 ** when the last lock is cleared.
1769 */
1770 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001771 }
dan661d71a2011-03-30 19:08:03 +00001772 releaseInodeInfo(pFile);
1773 rc = closeUnixFile(id);
1774 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001775 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001776}
1777
drh734c9862008-11-28 15:37:20 +00001778/************** End of the posix advisory lock implementation *****************
1779******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001780
drh734c9862008-11-28 15:37:20 +00001781/******************************************************************************
1782****************************** No-op Locking **********************************
1783**
1784** Of the various locking implementations available, this is by far the
1785** simplest: locking is ignored. No attempt is made to lock the database
1786** file for reading or writing.
1787**
1788** This locking mode is appropriate for use on read-only databases
1789** (ex: databases that are burned into CD-ROM, for example.) It can
1790** also be used if the application employs some external mechanism to
1791** prevent simultaneous access of the same database by two or more
1792** database connections. But there is a serious risk of database
1793** corruption if this locking mode is used in situations where multiple
1794** database connections are accessing the same database file at the same
1795** time and one or more of those connections are writing.
1796*/
drhbfe66312006-10-03 17:40:40 +00001797
drh734c9862008-11-28 15:37:20 +00001798static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1799 UNUSED_PARAMETER(NotUsed);
1800 *pResOut = 0;
1801 return SQLITE_OK;
1802}
drh734c9862008-11-28 15:37:20 +00001803static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1804 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1805 return SQLITE_OK;
1806}
drh734c9862008-11-28 15:37:20 +00001807static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1808 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1809 return SQLITE_OK;
1810}
1811
1812/*
drh9b35ea62008-11-29 02:20:26 +00001813** Close the file.
drh734c9862008-11-28 15:37:20 +00001814*/
1815static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001816 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001817}
1818
1819/******************* End of the no-op lock implementation *********************
1820******************************************************************************/
1821
1822/******************************************************************************
1823************************* Begin dot-file Locking ******************************
1824**
drh0c2694b2009-09-03 16:23:44 +00001825** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001826** files in order to control access to the database. This works on just
1827** about every filesystem imaginable. But there are serious downsides:
1828**
1829** (1) There is zero concurrency. A single reader blocks all other
1830** connections from reading or writing the database.
1831**
1832** (2) An application crash or power loss can leave stale lock files
1833** sitting around that need to be cleared manually.
1834**
1835** Nevertheless, a dotlock is an appropriate locking mode for use if no
1836** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001837**
1838** Dotfile locking works by creating a file in the same directory as the
1839** database and with the same name but with a ".lock" extension added.
1840** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1841** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001842*/
1843
1844/*
1845** The file suffix added to the data base filename in order to create the
1846** lock file.
1847*/
1848#define DOTLOCK_SUFFIX ".lock"
1849
drh7708e972008-11-29 00:56:52 +00001850/*
1851** This routine checks if there is a RESERVED lock held on the specified
1852** file by this or any other process. If such a lock is held, set *pResOut
1853** to a non-zero value otherwise *pResOut is set to zero. The return value
1854** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1855**
1856** In dotfile locking, either a lock exists or it does not. So in this
1857** variation of CheckReservedLock(), *pResOut is set to true if any lock
1858** is held on the file and false if the file is unlocked.
1859*/
drh734c9862008-11-28 15:37:20 +00001860static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1861 int rc = SQLITE_OK;
1862 int reserved = 0;
1863 unixFile *pFile = (unixFile*)id;
1864
1865 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1866
1867 assert( pFile );
1868
1869 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001870 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001871 /* Either this connection or some other connection in the same process
1872 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001873 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001874 }else{
1875 /* The lock is held if and only if the lockfile exists */
1876 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001877 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001878 }
drh308c2a52010-05-14 11:30:18 +00001879 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001880 *pResOut = reserved;
1881 return rc;
1882}
1883
drh7708e972008-11-29 00:56:52 +00001884/*
drh308c2a52010-05-14 11:30:18 +00001885** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001886** of the following:
1887**
1888** (1) SHARED_LOCK
1889** (2) RESERVED_LOCK
1890** (3) PENDING_LOCK
1891** (4) EXCLUSIVE_LOCK
1892**
1893** Sometimes when requesting one lock state, additional lock states
1894** are inserted in between. The locking might fail on one of the later
1895** transitions leaving the lock state different from what it started but
1896** still short of its goal. The following chart shows the allowed
1897** transitions and the inserted intermediate states:
1898**
1899** UNLOCKED -> SHARED
1900** SHARED -> RESERVED
1901** SHARED -> (PENDING) -> EXCLUSIVE
1902** RESERVED -> (PENDING) -> EXCLUSIVE
1903** PENDING -> EXCLUSIVE
1904**
1905** This routine will only increase a lock. Use the sqlite3OsUnlock()
1906** routine to lower a locking level.
1907**
1908** With dotfile locking, we really only support state (4): EXCLUSIVE.
1909** But we track the other locking levels internally.
1910*/
drh308c2a52010-05-14 11:30:18 +00001911static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001912 unixFile *pFile = (unixFile*)id;
1913 int fd;
1914 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001915 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001916
drh7708e972008-11-29 00:56:52 +00001917
1918 /* If we have any lock, then the lock file already exists. All we have
1919 ** to do is adjust our internal record of the lock level.
1920 */
drh308c2a52010-05-14 11:30:18 +00001921 if( pFile->eFileLock > NO_LOCK ){
1922 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001923#if !OS_VXWORKS
1924 /* Always update the timestamp on the old file */
1925 utimes(zLockFile, NULL);
1926#endif
drh7708e972008-11-29 00:56:52 +00001927 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001928 }
1929
1930 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001931 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001932 if( fd<0 ){
1933 /* failed to open/create the file, someone else may have stolen the lock */
1934 int tErrno = errno;
1935 if( EEXIST == tErrno ){
1936 rc = SQLITE_BUSY;
1937 } else {
1938 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1939 if( IS_LOCK_ERROR(rc) ){
1940 pFile->lastErrno = tErrno;
1941 }
1942 }
drh7708e972008-11-29 00:56:52 +00001943 return rc;
drh734c9862008-11-28 15:37:20 +00001944 }
drh0e9365c2011-03-02 02:08:13 +00001945 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001946
1947 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001948 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001949 return rc;
1950}
1951
drh7708e972008-11-29 00:56:52 +00001952/*
drh308c2a52010-05-14 11:30:18 +00001953** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001954** must be either NO_LOCK or SHARED_LOCK.
1955**
1956** If the locking level of the file descriptor is already at or below
1957** the requested locking level, this routine is a no-op.
1958**
1959** When the locking level reaches NO_LOCK, delete the lock file.
1960*/
drh308c2a52010-05-14 11:30:18 +00001961static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001962 unixFile *pFile = (unixFile*)id;
1963 char *zLockFile = (char *)pFile->lockingContext;
1964
1965 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001966 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1967 pFile->eFileLock, getpid()));
1968 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001969
1970 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001971 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001972 return SQLITE_OK;
1973 }
drh7708e972008-11-29 00:56:52 +00001974
1975 /* To downgrade to shared, simply update our internal notion of the
1976 ** lock state. No need to mess with the file on disk.
1977 */
drh308c2a52010-05-14 11:30:18 +00001978 if( eFileLock==SHARED_LOCK ){
1979 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001980 return SQLITE_OK;
1981 }
1982
drh7708e972008-11-29 00:56:52 +00001983 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001984 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001985 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001986 int rc = 0;
1987 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001988 if( ENOENT != tErrno ){
1989 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1990 }
1991 if( IS_LOCK_ERROR(rc) ){
1992 pFile->lastErrno = tErrno;
1993 }
1994 return rc;
1995 }
drh308c2a52010-05-14 11:30:18 +00001996 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001997 return SQLITE_OK;
1998}
1999
2000/*
drh9b35ea62008-11-29 02:20:26 +00002001** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002002*/
2003static int dotlockClose(sqlite3_file *id) {
2004 int rc;
2005 if( id ){
2006 unixFile *pFile = (unixFile*)id;
2007 dotlockUnlock(id, NO_LOCK);
2008 sqlite3_free(pFile->lockingContext);
2009 }
drh734c9862008-11-28 15:37:20 +00002010 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002011 return rc;
2012}
2013/****************** End of the dot-file lock implementation *******************
2014******************************************************************************/
2015
2016/******************************************************************************
2017************************** Begin flock Locking ********************************
2018**
2019** Use the flock() system call to do file locking.
2020**
drh6b9d6dd2008-12-03 19:34:47 +00002021** flock() locking is like dot-file locking in that the various
2022** fine-grain locking levels supported by SQLite are collapsed into
2023** a single exclusive lock. In other words, SHARED, RESERVED, and
2024** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2025** still works when you do this, but concurrency is reduced since
2026** only a single process can be reading the database at a time.
2027**
drh734c9862008-11-28 15:37:20 +00002028** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2029** compiling for VXWORKS.
2030*/
2031#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002032
drh6b9d6dd2008-12-03 19:34:47 +00002033/*
drhff812312011-02-23 13:33:46 +00002034** Retry flock() calls that fail with EINTR
2035*/
2036#ifdef EINTR
2037static int robust_flock(int fd, int op){
2038 int rc;
2039 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2040 return rc;
2041}
2042#else
drh5c819272011-02-23 14:00:12 +00002043# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002044#endif
2045
2046
2047/*
drh6b9d6dd2008-12-03 19:34:47 +00002048** This routine checks if there is a RESERVED lock held on the specified
2049** file by this or any other process. If such a lock is held, set *pResOut
2050** to a non-zero value otherwise *pResOut is set to zero. The return value
2051** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2052*/
drh734c9862008-11-28 15:37:20 +00002053static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2054 int rc = SQLITE_OK;
2055 int reserved = 0;
2056 unixFile *pFile = (unixFile*)id;
2057
2058 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2059
2060 assert( pFile );
2061
2062 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002063 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002064 reserved = 1;
2065 }
2066
2067 /* Otherwise see if some other process holds it. */
2068 if( !reserved ){
2069 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002070 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002071 if( !lrc ){
2072 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002073 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002074 if ( lrc ) {
2075 int tErrno = errno;
2076 /* unlock failed with an error */
2077 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2078 if( IS_LOCK_ERROR(lrc) ){
2079 pFile->lastErrno = tErrno;
2080 rc = lrc;
2081 }
2082 }
2083 } else {
2084 int tErrno = errno;
2085 reserved = 1;
2086 /* someone else might have it reserved */
2087 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2088 if( IS_LOCK_ERROR(lrc) ){
2089 pFile->lastErrno = tErrno;
2090 rc = lrc;
2091 }
2092 }
2093 }
drh308c2a52010-05-14 11:30:18 +00002094 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002095
2096#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2097 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2098 rc = SQLITE_OK;
2099 reserved=1;
2100 }
2101#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2102 *pResOut = reserved;
2103 return rc;
2104}
2105
drh6b9d6dd2008-12-03 19:34:47 +00002106/*
drh308c2a52010-05-14 11:30:18 +00002107** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002108** of the following:
2109**
2110** (1) SHARED_LOCK
2111** (2) RESERVED_LOCK
2112** (3) PENDING_LOCK
2113** (4) EXCLUSIVE_LOCK
2114**
2115** Sometimes when requesting one lock state, additional lock states
2116** are inserted in between. The locking might fail on one of the later
2117** transitions leaving the lock state different from what it started but
2118** still short of its goal. The following chart shows the allowed
2119** transitions and the inserted intermediate states:
2120**
2121** UNLOCKED -> SHARED
2122** SHARED -> RESERVED
2123** SHARED -> (PENDING) -> EXCLUSIVE
2124** RESERVED -> (PENDING) -> EXCLUSIVE
2125** PENDING -> EXCLUSIVE
2126**
2127** flock() only really support EXCLUSIVE locks. We track intermediate
2128** lock states in the sqlite3_file structure, but all locks SHARED or
2129** above are really EXCLUSIVE locks and exclude all other processes from
2130** access the file.
2131**
2132** This routine will only increase a lock. Use the sqlite3OsUnlock()
2133** routine to lower a locking level.
2134*/
drh308c2a52010-05-14 11:30:18 +00002135static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002136 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002137 unixFile *pFile = (unixFile*)id;
2138
2139 assert( pFile );
2140
2141 /* if we already have a lock, it is exclusive.
2142 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002143 if (pFile->eFileLock > NO_LOCK) {
2144 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002145 return SQLITE_OK;
2146 }
2147
2148 /* grab an exclusive lock */
2149
drhff812312011-02-23 13:33:46 +00002150 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002151 int tErrno = errno;
2152 /* didn't get, must be busy */
2153 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2154 if( IS_LOCK_ERROR(rc) ){
2155 pFile->lastErrno = tErrno;
2156 }
2157 } else {
2158 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002159 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002160 }
drh308c2a52010-05-14 11:30:18 +00002161 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2162 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002163#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2164 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2165 rc = SQLITE_BUSY;
2166 }
2167#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2168 return rc;
2169}
2170
drh6b9d6dd2008-12-03 19:34:47 +00002171
2172/*
drh308c2a52010-05-14 11:30:18 +00002173** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002174** must be either NO_LOCK or SHARED_LOCK.
2175**
2176** If the locking level of the file descriptor is already at or below
2177** the requested locking level, this routine is a no-op.
2178*/
drh308c2a52010-05-14 11:30:18 +00002179static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002180 unixFile *pFile = (unixFile*)id;
2181
2182 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002183 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2184 pFile->eFileLock, getpid()));
2185 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002186
2187 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002188 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002189 return SQLITE_OK;
2190 }
2191
2192 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002193 if (eFileLock==SHARED_LOCK) {
2194 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002195 return SQLITE_OK;
2196 }
2197
2198 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002199 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002200 if (rc) {
2201 int r, tErrno = errno;
2202 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2203 if( IS_LOCK_ERROR(r) ){
2204 pFile->lastErrno = tErrno;
2205 }
2206#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2207 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2208 r = SQLITE_BUSY;
2209 }
2210#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2211
2212 return r;
2213 } else {
drh308c2a52010-05-14 11:30:18 +00002214 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002215 return SQLITE_OK;
2216 }
2217}
2218
2219/*
2220** Close a file.
2221*/
2222static int flockClose(sqlite3_file *id) {
2223 if( id ){
2224 flockUnlock(id, NO_LOCK);
2225 }
2226 return closeUnixFile(id);
2227}
2228
2229#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2230
2231/******************* End of the flock lock implementation *********************
2232******************************************************************************/
2233
2234/******************************************************************************
2235************************ Begin Named Semaphore Locking ************************
2236**
2237** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002238**
2239** Semaphore locking is like dot-lock and flock in that it really only
2240** supports EXCLUSIVE locking. Only a single process can read or write
2241** the database file at a time. This reduces potential concurrency, but
2242** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002243*/
2244#if OS_VXWORKS
2245
drh6b9d6dd2008-12-03 19:34:47 +00002246/*
2247** This routine checks if there is a RESERVED lock held on the specified
2248** file by this or any other process. If such a lock is held, set *pResOut
2249** to a non-zero value otherwise *pResOut is set to zero. The return value
2250** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2251*/
drh734c9862008-11-28 15:37:20 +00002252static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2253 int rc = SQLITE_OK;
2254 int reserved = 0;
2255 unixFile *pFile = (unixFile*)id;
2256
2257 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2258
2259 assert( pFile );
2260
2261 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002262 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002263 reserved = 1;
2264 }
2265
2266 /* Otherwise see if some other process holds it. */
2267 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002268 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002269 struct stat statBuf;
2270
2271 if( sem_trywait(pSem)==-1 ){
2272 int tErrno = errno;
2273 if( EAGAIN != tErrno ){
2274 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2275 pFile->lastErrno = tErrno;
2276 } else {
2277 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002278 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002279 }
2280 }else{
2281 /* we could have it if we want it */
2282 sem_post(pSem);
2283 }
2284 }
drh308c2a52010-05-14 11:30:18 +00002285 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002286
2287 *pResOut = reserved;
2288 return rc;
2289}
2290
drh6b9d6dd2008-12-03 19:34:47 +00002291/*
drh308c2a52010-05-14 11:30:18 +00002292** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002293** of the following:
2294**
2295** (1) SHARED_LOCK
2296** (2) RESERVED_LOCK
2297** (3) PENDING_LOCK
2298** (4) EXCLUSIVE_LOCK
2299**
2300** Sometimes when requesting one lock state, additional lock states
2301** are inserted in between. The locking might fail on one of the later
2302** transitions leaving the lock state different from what it started but
2303** still short of its goal. The following chart shows the allowed
2304** transitions and the inserted intermediate states:
2305**
2306** UNLOCKED -> SHARED
2307** SHARED -> RESERVED
2308** SHARED -> (PENDING) -> EXCLUSIVE
2309** RESERVED -> (PENDING) -> EXCLUSIVE
2310** PENDING -> EXCLUSIVE
2311**
2312** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2313** lock states in the sqlite3_file structure, but all locks SHARED or
2314** above are really EXCLUSIVE locks and exclude all other processes from
2315** access the file.
2316**
2317** This routine will only increase a lock. Use the sqlite3OsUnlock()
2318** routine to lower a locking level.
2319*/
drh308c2a52010-05-14 11:30:18 +00002320static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002321 unixFile *pFile = (unixFile*)id;
2322 int fd;
drh8af6c222010-05-14 12:43:01 +00002323 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002324 int rc = SQLITE_OK;
2325
2326 /* if we already have a lock, it is exclusive.
2327 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002328 if (pFile->eFileLock > NO_LOCK) {
2329 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002330 rc = SQLITE_OK;
2331 goto sem_end_lock;
2332 }
2333
2334 /* lock semaphore now but bail out when already locked. */
2335 if( sem_trywait(pSem)==-1 ){
2336 rc = SQLITE_BUSY;
2337 goto sem_end_lock;
2338 }
2339
2340 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002341 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002342
2343 sem_end_lock:
2344 return rc;
2345}
2346
drh6b9d6dd2008-12-03 19:34:47 +00002347/*
drh308c2a52010-05-14 11:30:18 +00002348** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002349** must be either NO_LOCK or SHARED_LOCK.
2350**
2351** If the locking level of the file descriptor is already at or below
2352** the requested locking level, this routine is a no-op.
2353*/
drh308c2a52010-05-14 11:30:18 +00002354static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002355 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002356 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002357
2358 assert( pFile );
2359 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002360 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2361 pFile->eFileLock, getpid()));
2362 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002363
2364 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002365 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002366 return SQLITE_OK;
2367 }
2368
2369 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002370 if (eFileLock==SHARED_LOCK) {
2371 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002372 return SQLITE_OK;
2373 }
2374
2375 /* no, really unlock. */
2376 if ( sem_post(pSem)==-1 ) {
2377 int rc, tErrno = errno;
2378 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2379 if( IS_LOCK_ERROR(rc) ){
2380 pFile->lastErrno = tErrno;
2381 }
2382 return rc;
2383 }
drh308c2a52010-05-14 11:30:18 +00002384 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002385 return SQLITE_OK;
2386}
2387
2388/*
2389 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002390 */
drh734c9862008-11-28 15:37:20 +00002391static int semClose(sqlite3_file *id) {
2392 if( id ){
2393 unixFile *pFile = (unixFile*)id;
2394 semUnlock(id, NO_LOCK);
2395 assert( pFile );
2396 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002397 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002398 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002399 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002400 }
2401 return SQLITE_OK;
2402}
2403
2404#endif /* OS_VXWORKS */
2405/*
2406** Named semaphore locking is only available on VxWorks.
2407**
2408*************** End of the named semaphore lock implementation ****************
2409******************************************************************************/
2410
2411
2412/******************************************************************************
2413*************************** Begin AFP Locking *********************************
2414**
2415** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2416** on Apple Macintosh computers - both OS9 and OSX.
2417**
2418** Third-party implementations of AFP are available. But this code here
2419** only works on OSX.
2420*/
2421
drhd2cb50b2009-01-09 21:41:17 +00002422#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002423/*
2424** The afpLockingContext structure contains all afp lock specific state
2425*/
drhbfe66312006-10-03 17:40:40 +00002426typedef struct afpLockingContext afpLockingContext;
2427struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002428 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002429 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002430};
2431
2432struct ByteRangeLockPB2
2433{
2434 unsigned long long offset; /* offset to first byte to lock */
2435 unsigned long long length; /* nbr of bytes to lock */
2436 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2437 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2438 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2439 int fd; /* file desc to assoc this lock with */
2440};
2441
drhfd131da2007-08-07 17:13:03 +00002442#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002443
drh6b9d6dd2008-12-03 19:34:47 +00002444/*
2445** This is a utility for setting or clearing a bit-range lock on an
2446** AFP filesystem.
2447**
2448** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2449*/
2450static int afpSetLock(
2451 const char *path, /* Name of the file to be locked or unlocked */
2452 unixFile *pFile, /* Open file descriptor on path */
2453 unsigned long long offset, /* First byte to be locked */
2454 unsigned long long length, /* Number of bytes to lock */
2455 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002456){
drh6b9d6dd2008-12-03 19:34:47 +00002457 struct ByteRangeLockPB2 pb;
2458 int err;
drhbfe66312006-10-03 17:40:40 +00002459
2460 pb.unLockFlag = setLockFlag ? 0 : 1;
2461 pb.startEndFlag = 0;
2462 pb.offset = offset;
2463 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002464 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002465
drh308c2a52010-05-14 11:30:18 +00002466 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002467 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002468 offset, length));
drhbfe66312006-10-03 17:40:40 +00002469 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2470 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002471 int rc;
2472 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002473 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2474 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002475#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2476 rc = SQLITE_BUSY;
2477#else
drh734c9862008-11-28 15:37:20 +00002478 rc = sqliteErrorFromPosixError(tErrno,
2479 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002480#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002481 if( IS_LOCK_ERROR(rc) ){
2482 pFile->lastErrno = tErrno;
2483 }
2484 return rc;
drhbfe66312006-10-03 17:40:40 +00002485 } else {
aswift5b1a2562008-08-22 00:22:35 +00002486 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002487 }
2488}
2489
drh6b9d6dd2008-12-03 19:34:47 +00002490/*
2491** This routine checks if there is a RESERVED lock held on the specified
2492** file by this or any other process. If such a lock is held, set *pResOut
2493** to a non-zero value otherwise *pResOut is set to zero. The return value
2494** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2495*/
danielk1977e339d652008-06-28 11:23:00 +00002496static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002497 int rc = SQLITE_OK;
2498 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002499 unixFile *pFile = (unixFile*)id;
2500
aswift5b1a2562008-08-22 00:22:35 +00002501 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2502
2503 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002504 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002505 if( context->reserved ){
2506 *pResOut = 1;
2507 return SQLITE_OK;
2508 }
drh8af6c222010-05-14 12:43:01 +00002509 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002510
2511 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002512 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002513 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002514 }
2515
2516 /* Otherwise see if some other process holds it.
2517 */
aswift5b1a2562008-08-22 00:22:35 +00002518 if( !reserved ){
2519 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002520 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002521 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002522 /* if we succeeded in taking the reserved lock, unlock it to restore
2523 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002524 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002525 } else {
2526 /* if we failed to get the lock then someone else must have it */
2527 reserved = 1;
2528 }
2529 if( IS_LOCK_ERROR(lrc) ){
2530 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002531 }
2532 }
drhbfe66312006-10-03 17:40:40 +00002533
drh7ed97b92010-01-20 13:07:21 +00002534 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002535 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002536
2537 *pResOut = reserved;
2538 return rc;
drhbfe66312006-10-03 17:40:40 +00002539}
2540
drh6b9d6dd2008-12-03 19:34:47 +00002541/*
drh308c2a52010-05-14 11:30:18 +00002542** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002543** of the following:
2544**
2545** (1) SHARED_LOCK
2546** (2) RESERVED_LOCK
2547** (3) PENDING_LOCK
2548** (4) EXCLUSIVE_LOCK
2549**
2550** Sometimes when requesting one lock state, additional lock states
2551** are inserted in between. The locking might fail on one of the later
2552** transitions leaving the lock state different from what it started but
2553** still short of its goal. The following chart shows the allowed
2554** transitions and the inserted intermediate states:
2555**
2556** UNLOCKED -> SHARED
2557** SHARED -> RESERVED
2558** SHARED -> (PENDING) -> EXCLUSIVE
2559** RESERVED -> (PENDING) -> EXCLUSIVE
2560** PENDING -> EXCLUSIVE
2561**
2562** This routine will only increase a lock. Use the sqlite3OsUnlock()
2563** routine to lower a locking level.
2564*/
drh308c2a52010-05-14 11:30:18 +00002565static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002566 int rc = SQLITE_OK;
2567 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002568 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002569 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002570
2571 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002572 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2573 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002574 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002575
drhbfe66312006-10-03 17:40:40 +00002576 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002577 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002578 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002579 */
drh308c2a52010-05-14 11:30:18 +00002580 if( pFile->eFileLock>=eFileLock ){
2581 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2582 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002583 return SQLITE_OK;
2584 }
2585
2586 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002587 ** (1) We never move from unlocked to anything higher than shared lock.
2588 ** (2) SQLite never explicitly requests a pendig lock.
2589 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002590 */
drh308c2a52010-05-14 11:30:18 +00002591 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2592 assert( eFileLock!=PENDING_LOCK );
2593 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002594
drh8af6c222010-05-14 12:43:01 +00002595 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002596 */
drh6c7d5c52008-11-21 20:32:33 +00002597 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002598 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002599
2600 /* If some thread using this PID has a lock via a different unixFile*
2601 ** handle that precludes the requested lock, return BUSY.
2602 */
drh8af6c222010-05-14 12:43:01 +00002603 if( (pFile->eFileLock!=pInode->eFileLock &&
2604 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002605 ){
2606 rc = SQLITE_BUSY;
2607 goto afp_end_lock;
2608 }
2609
2610 /* If a SHARED lock is requested, and some thread using this PID already
2611 ** has a SHARED or RESERVED lock, then increment reference counts and
2612 ** return SQLITE_OK.
2613 */
drh308c2a52010-05-14 11:30:18 +00002614 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002615 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002616 assert( eFileLock==SHARED_LOCK );
2617 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002618 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002619 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002620 pInode->nShared++;
2621 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002622 goto afp_end_lock;
2623 }
drhbfe66312006-10-03 17:40:40 +00002624
2625 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002626 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2627 ** be released.
2628 */
drh308c2a52010-05-14 11:30:18 +00002629 if( eFileLock==SHARED_LOCK
2630 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002631 ){
2632 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002633 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002634 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002635 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002636 goto afp_end_lock;
2637 }
2638 }
2639
2640 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002641 ** operating system calls for the specified lock.
2642 */
drh308c2a52010-05-14 11:30:18 +00002643 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002644 int lrc1, lrc2, lrc1Errno;
2645 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002646
drh8af6c222010-05-14 12:43:01 +00002647 assert( pInode->nShared==0 );
2648 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002649
2650 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002651 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002652 /* note that the quality of the randomness doesn't matter that much */
2653 lk = random();
drh8af6c222010-05-14 12:43:01 +00002654 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002655 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002656 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002657 if( IS_LOCK_ERROR(lrc1) ){
2658 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002659 }
aswift5b1a2562008-08-22 00:22:35 +00002660 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002661 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002662
aswift5b1a2562008-08-22 00:22:35 +00002663 if( IS_LOCK_ERROR(lrc1) ) {
2664 pFile->lastErrno = lrc1Errno;
2665 rc = lrc1;
2666 goto afp_end_lock;
2667 } else if( IS_LOCK_ERROR(lrc2) ){
2668 rc = lrc2;
2669 goto afp_end_lock;
2670 } else if( lrc1 != SQLITE_OK ) {
2671 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002672 } else {
drh308c2a52010-05-14 11:30:18 +00002673 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002674 pInode->nLock++;
2675 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002676 }
drh8af6c222010-05-14 12:43:01 +00002677 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002678 /* We are trying for an exclusive lock but another thread in this
2679 ** same process is still holding a shared lock. */
2680 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002681 }else{
2682 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2683 ** assumed that there is a SHARED or greater lock on the file
2684 ** already.
2685 */
2686 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002687 assert( 0!=pFile->eFileLock );
2688 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002689 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002690 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002691 if( !failed ){
2692 context->reserved = 1;
2693 }
drhbfe66312006-10-03 17:40:40 +00002694 }
drh308c2a52010-05-14 11:30:18 +00002695 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002696 /* Acquire an EXCLUSIVE lock */
2697
2698 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002699 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002700 */
drh6b9d6dd2008-12-03 19:34:47 +00002701 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002702 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002703 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002704 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002705 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002706 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002707 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002708 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002709 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2710 ** a critical I/O error
2711 */
2712 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2713 SQLITE_IOERR_LOCK;
2714 goto afp_end_lock;
2715 }
2716 }else{
aswift5b1a2562008-08-22 00:22:35 +00002717 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002718 }
2719 }
aswift5b1a2562008-08-22 00:22:35 +00002720 if( failed ){
2721 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002722 }
2723 }
2724
2725 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002726 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002727 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002728 }else if( eFileLock==EXCLUSIVE_LOCK ){
2729 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002730 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002731 }
2732
2733afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002735 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2736 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002737 return rc;
2738}
2739
2740/*
drh308c2a52010-05-14 11:30:18 +00002741** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002742** must be either NO_LOCK or SHARED_LOCK.
2743**
2744** If the locking level of the file descriptor is already at or below
2745** the requested locking level, this routine is a no-op.
2746*/
drh308c2a52010-05-14 11:30:18 +00002747static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002748 int rc = SQLITE_OK;
2749 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002750 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002751 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2752 int skipShared = 0;
2753#ifdef SQLITE_TEST
2754 int h = pFile->h;
2755#endif
drhbfe66312006-10-03 17:40:40 +00002756
2757 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002758 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002759 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002760 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002761
drh308c2a52010-05-14 11:30:18 +00002762 assert( eFileLock<=SHARED_LOCK );
2763 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002764 return SQLITE_OK;
2765 }
drh6c7d5c52008-11-21 20:32:33 +00002766 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002767 pInode = pFile->pInode;
2768 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002769 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002770 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002771 SimulateIOErrorBenign(1);
2772 SimulateIOError( h=(-1) )
2773 SimulateIOErrorBenign(0);
2774
2775#ifndef NDEBUG
2776 /* When reducing a lock such that other processes can start
2777 ** reading the database file again, make sure that the
2778 ** transaction counter was updated if any part of the database
2779 ** file changed. If the transaction counter is not updated,
2780 ** other connections to the same file might not realize that
2781 ** the file has changed and hence might not know to flush their
2782 ** cache. The use of a stale cache can lead to database corruption.
2783 */
2784 assert( pFile->inNormalWrite==0
2785 || pFile->dbUpdate==0
2786 || pFile->transCntrChng==1 );
2787 pFile->inNormalWrite = 0;
2788#endif
aswiftaebf4132008-11-21 00:10:35 +00002789
drh308c2a52010-05-14 11:30:18 +00002790 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002791 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002792 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002793 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002794 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002795 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2796 } else {
2797 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002798 }
2799 }
drh308c2a52010-05-14 11:30:18 +00002800 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002801 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002802 }
drh308c2a52010-05-14 11:30:18 +00002803 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002804 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2805 if( !rc ){
2806 context->reserved = 0;
2807 }
aswiftaebf4132008-11-21 00:10:35 +00002808 }
drh8af6c222010-05-14 12:43:01 +00002809 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2810 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002811 }
aswiftaebf4132008-11-21 00:10:35 +00002812 }
drh308c2a52010-05-14 11:30:18 +00002813 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002814
drh7ed97b92010-01-20 13:07:21 +00002815 /* Decrement the shared lock counter. Release the lock using an
2816 ** OS call only when all threads in this same process have released
2817 ** the lock.
2818 */
drh8af6c222010-05-14 12:43:01 +00002819 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2820 pInode->nShared--;
2821 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002822 SimulateIOErrorBenign(1);
2823 SimulateIOError( h=(-1) )
2824 SimulateIOErrorBenign(0);
2825 if( !skipShared ){
2826 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2827 }
2828 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002829 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002830 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002831 }
2832 }
2833 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002834 pInode->nLock--;
2835 assert( pInode->nLock>=0 );
2836 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002837 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002838 }
2839 }
drhbfe66312006-10-03 17:40:40 +00002840 }
drh7ed97b92010-01-20 13:07:21 +00002841
drh6c7d5c52008-11-21 20:32:33 +00002842 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002843 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002844 return rc;
2845}
2846
2847/*
drh339eb0b2008-03-07 15:34:11 +00002848** Close a file & cleanup AFP specific locking context
2849*/
danielk1977e339d652008-06-28 11:23:00 +00002850static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002851 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002852 if( id ){
2853 unixFile *pFile = (unixFile*)id;
2854 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002855 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002856 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002857 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002858 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002859 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002860 ** the last lock is cleared.
2861 */
dan08da86a2009-08-21 17:18:03 +00002862 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002863 }
danb0ac3e32010-06-16 10:55:42 +00002864 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002865 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002866 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002867 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002868 }
drh7ed97b92010-01-20 13:07:21 +00002869 return rc;
drhbfe66312006-10-03 17:40:40 +00002870}
2871
drhd2cb50b2009-01-09 21:41:17 +00002872#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002873/*
2874** The code above is the AFP lock implementation. The code is specific
2875** to MacOSX and does not work on other unix platforms. No alternative
2876** is available. If you don't compile for a mac, then the "unix-afp"
2877** VFS is not available.
2878**
2879********************* End of the AFP lock implementation **********************
2880******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002881
drh7ed97b92010-01-20 13:07:21 +00002882/******************************************************************************
2883*************************** Begin NFS Locking ********************************/
2884
2885#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2886/*
drh308c2a52010-05-14 11:30:18 +00002887 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002888 ** must be either NO_LOCK or SHARED_LOCK.
2889 **
2890 ** If the locking level of the file descriptor is already at or below
2891 ** the requested locking level, this routine is a no-op.
2892 */
drh308c2a52010-05-14 11:30:18 +00002893static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002894 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002895}
2896
2897#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2898/*
2899** The code above is the NFS lock implementation. The code is specific
2900** to MacOSX and does not work on other unix platforms. No alternative
2901** is available.
2902**
2903********************* End of the NFS lock implementation **********************
2904******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002905
2906/******************************************************************************
2907**************** Non-locking sqlite3_file methods *****************************
2908**
2909** The next division contains implementations for all methods of the
2910** sqlite3_file object other than the locking methods. The locking
2911** methods were defined in divisions above (one locking method per
2912** division). Those methods that are common to all locking modes
2913** are gather together into this division.
2914*/
drhbfe66312006-10-03 17:40:40 +00002915
2916/*
drh734c9862008-11-28 15:37:20 +00002917** Seek to the offset passed as the second argument, then read cnt
2918** bytes into pBuf. Return the number of bytes actually read.
2919**
2920** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2921** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2922** one system to another. Since SQLite does not define USE_PREAD
2923** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2924** See tickets #2741 and #2681.
2925**
2926** To avoid stomping the errno value on a failed read the lastErrno value
2927** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002928*/
drh734c9862008-11-28 15:37:20 +00002929static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2930 int got;
drh7ed97b92010-01-20 13:07:21 +00002931#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002932 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002933#endif
drh734c9862008-11-28 15:37:20 +00002934 TIMER_START;
2935#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002936 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002937 SimulateIOError( got = -1 );
2938#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002939 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002940 SimulateIOError( got = -1 );
2941#else
2942 newOffset = lseek(id->h, offset, SEEK_SET);
2943 SimulateIOError( newOffset-- );
2944 if( newOffset!=offset ){
2945 if( newOffset == -1 ){
2946 ((unixFile*)id)->lastErrno = errno;
2947 }else{
2948 ((unixFile*)id)->lastErrno = 0;
2949 }
2950 return -1;
2951 }
drhe562be52011-03-02 18:01:10 +00002952 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002953#endif
2954 TIMER_END;
2955 if( got<0 ){
2956 ((unixFile*)id)->lastErrno = errno;
2957 }
drh308c2a52010-05-14 11:30:18 +00002958 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002959 return got;
drhbfe66312006-10-03 17:40:40 +00002960}
2961
2962/*
drh734c9862008-11-28 15:37:20 +00002963** Read data from a file into a buffer. Return SQLITE_OK if all
2964** bytes were read successfully and SQLITE_IOERR if anything goes
2965** wrong.
drh339eb0b2008-03-07 15:34:11 +00002966*/
drh734c9862008-11-28 15:37:20 +00002967static int unixRead(
2968 sqlite3_file *id,
2969 void *pBuf,
2970 int amt,
2971 sqlite3_int64 offset
2972){
dan08da86a2009-08-21 17:18:03 +00002973 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002974 int got;
2975 assert( id );
drh08c6d442009-02-09 17:34:07 +00002976
dan08da86a2009-08-21 17:18:03 +00002977 /* If this is a database file (not a journal, master-journal or temp
2978 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002979#if 0
dane946c392009-08-22 11:39:46 +00002980 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002981 || offset>=PENDING_BYTE+512
2982 || offset+amt<=PENDING_BYTE
2983 );
dan7c246102010-04-12 19:00:29 +00002984#endif
drh08c6d442009-02-09 17:34:07 +00002985
dan08da86a2009-08-21 17:18:03 +00002986 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002987 if( got==amt ){
2988 return SQLITE_OK;
2989 }else if( got<0 ){
2990 /* lastErrno set by seekAndRead */
2991 return SQLITE_IOERR_READ;
2992 }else{
dan08da86a2009-08-21 17:18:03 +00002993 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002994 /* Unread parts of the buffer must be zero-filled */
2995 memset(&((char*)pBuf)[got], 0, amt-got);
2996 return SQLITE_IOERR_SHORT_READ;
2997 }
2998}
2999
3000/*
3001** Seek to the offset in id->offset then read cnt bytes into pBuf.
3002** Return the number of bytes actually read. Update the offset.
3003**
3004** To avoid stomping the errno value on a failed write the lastErrno value
3005** is set before returning.
3006*/
3007static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3008 int got;
drh7ed97b92010-01-20 13:07:21 +00003009#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003010 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003011#endif
drh734c9862008-11-28 15:37:20 +00003012 TIMER_START;
3013#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003014 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003015#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003016 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003017#else
3018 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003019 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003020 if( newOffset!=offset ){
3021 if( newOffset == -1 ){
3022 ((unixFile*)id)->lastErrno = errno;
3023 }else{
3024 ((unixFile*)id)->lastErrno = 0;
3025 }
3026 return -1;
3027 }
drhe562be52011-03-02 18:01:10 +00003028 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003029#endif
3030 TIMER_END;
3031 if( got<0 ){
3032 ((unixFile*)id)->lastErrno = errno;
3033 }
3034
drh308c2a52010-05-14 11:30:18 +00003035 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003036 return got;
3037}
3038
3039
3040/*
3041** Write data from a buffer into a file. Return SQLITE_OK on success
3042** or some other error code on failure.
3043*/
3044static int unixWrite(
3045 sqlite3_file *id,
3046 const void *pBuf,
3047 int amt,
3048 sqlite3_int64 offset
3049){
dan08da86a2009-08-21 17:18:03 +00003050 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003051 int wrote = 0;
3052 assert( id );
3053 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003054
dan08da86a2009-08-21 17:18:03 +00003055 /* If this is a database file (not a journal, master-journal or temp
3056 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003057#if 0
dane946c392009-08-22 11:39:46 +00003058 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003059 || offset>=PENDING_BYTE+512
3060 || offset+amt<=PENDING_BYTE
3061 );
dan7c246102010-04-12 19:00:29 +00003062#endif
drh08c6d442009-02-09 17:34:07 +00003063
drh8f941bc2009-01-14 23:03:40 +00003064#ifndef NDEBUG
3065 /* If we are doing a normal write to a database file (as opposed to
3066 ** doing a hot-journal rollback or a write to some file other than a
3067 ** normal database file) then record the fact that the database
3068 ** has changed. If the transaction counter is modified, record that
3069 ** fact too.
3070 */
dan08da86a2009-08-21 17:18:03 +00003071 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003072 pFile->dbUpdate = 1; /* The database has been modified */
3073 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003074 int rc;
drh8f941bc2009-01-14 23:03:40 +00003075 char oldCntr[4];
3076 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003077 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003078 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003079 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003080 pFile->transCntrChng = 1; /* The transaction counter has changed */
3081 }
3082 }
3083 }
3084#endif
3085
dan08da86a2009-08-21 17:18:03 +00003086 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003087 amt -= wrote;
3088 offset += wrote;
3089 pBuf = &((char*)pBuf)[wrote];
3090 }
3091 SimulateIOError(( wrote=(-1), amt=1 ));
3092 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003093
drh734c9862008-11-28 15:37:20 +00003094 if( amt>0 ){
3095 if( wrote<0 ){
3096 /* lastErrno set by seekAndWrite */
3097 return SQLITE_IOERR_WRITE;
3098 }else{
dan08da86a2009-08-21 17:18:03 +00003099 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003100 return SQLITE_FULL;
3101 }
3102 }
dan6e09d692010-07-27 18:34:15 +00003103
drh734c9862008-11-28 15:37:20 +00003104 return SQLITE_OK;
3105}
3106
3107#ifdef SQLITE_TEST
3108/*
3109** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003110** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003111*/
3112int sqlite3_sync_count = 0;
3113int sqlite3_fullsync_count = 0;
3114#endif
3115
3116/*
drh89240432009-03-25 01:06:01 +00003117** We do not trust systems to provide a working fdatasync(). Some do.
3118** Others do no. To be safe, we will stick with the (slower) fsync().
3119** If you know that your system does support fdatasync() correctly,
3120** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003121*/
drh89240432009-03-25 01:06:01 +00003122#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003123# define fdatasync fsync
3124#endif
3125
3126/*
3127** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3128** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3129** only available on Mac OS X. But that could change.
3130*/
3131#ifdef F_FULLFSYNC
3132# define HAVE_FULLFSYNC 1
3133#else
3134# define HAVE_FULLFSYNC 0
3135#endif
3136
3137
3138/*
3139** The fsync() system call does not work as advertised on many
3140** unix systems. The following procedure is an attempt to make
3141** it work better.
3142**
3143** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3144** for testing when we want to run through the test suite quickly.
3145** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3146** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3147** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003148**
3149** SQLite sets the dataOnly flag if the size of the file is unchanged.
3150** The idea behind dataOnly is that it should only write the file content
3151** to disk, not the inode. We only set dataOnly if the file size is
3152** unchanged since the file size is part of the inode. However,
3153** Ted Ts'o tells us that fdatasync() will also write the inode if the
3154** file size has changed. The only real difference between fdatasync()
3155** and fsync(), Ted tells us, is that fdatasync() will not flush the
3156** inode if the mtime or owner or other inode attributes have changed.
3157** We only care about the file size, not the other file attributes, so
3158** as far as SQLite is concerned, an fdatasync() is always adequate.
3159** So, we always use fdatasync() if it is available, regardless of
3160** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003161*/
3162static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003163 int rc;
drh734c9862008-11-28 15:37:20 +00003164
3165 /* The following "ifdef/elif/else/" block has the same structure as
3166 ** the one below. It is replicated here solely to avoid cluttering
3167 ** up the real code with the UNUSED_PARAMETER() macros.
3168 */
3169#ifdef SQLITE_NO_SYNC
3170 UNUSED_PARAMETER(fd);
3171 UNUSED_PARAMETER(fullSync);
3172 UNUSED_PARAMETER(dataOnly);
3173#elif HAVE_FULLFSYNC
3174 UNUSED_PARAMETER(dataOnly);
3175#else
3176 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003177 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003178#endif
3179
3180 /* Record the number of times that we do a normal fsync() and
3181 ** FULLSYNC. This is used during testing to verify that this procedure
3182 ** gets called with the correct arguments.
3183 */
3184#ifdef SQLITE_TEST
3185 if( fullSync ) sqlite3_fullsync_count++;
3186 sqlite3_sync_count++;
3187#endif
3188
3189 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3190 ** no-op
3191 */
3192#ifdef SQLITE_NO_SYNC
3193 rc = SQLITE_OK;
3194#elif HAVE_FULLFSYNC
3195 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003196 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003197 }else{
3198 rc = 1;
3199 }
3200 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003201 ** It shouldn't be possible for fullfsync to fail on the local
3202 ** file system (on OSX), so failure indicates that FULLFSYNC
3203 ** isn't supported for this file system. So, attempt an fsync
3204 ** and (for now) ignore the overhead of a superfluous fcntl call.
3205 ** It'd be better to detect fullfsync support once and avoid
3206 ** the fcntl call every time sync is called.
3207 */
drh734c9862008-11-28 15:37:20 +00003208 if( rc ) rc = fsync(fd);
3209
drh7ed97b92010-01-20 13:07:21 +00003210#elif defined(__APPLE__)
3211 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3212 ** so currently we default to the macro that redefines fdatasync to fsync
3213 */
3214 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003215#else
drh0b647ff2009-03-21 14:41:04 +00003216 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003217#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003218 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003219 rc = fsync(fd);
3220 }
drh0b647ff2009-03-21 14:41:04 +00003221#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003222#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3223
3224 if( OS_VXWORKS && rc!= -1 ){
3225 rc = 0;
3226 }
chw97185482008-11-17 08:05:31 +00003227 return rc;
drhbfe66312006-10-03 17:40:40 +00003228}
3229
drh734c9862008-11-28 15:37:20 +00003230/*
3231** Make sure all writes to a particular file are committed to disk.
3232**
3233** If dataOnly==0 then both the file itself and its metadata (file
3234** size, access time, etc) are synced. If dataOnly!=0 then only the
3235** file data is synced.
3236**
3237** Under Unix, also make sure that the directory entry for the file
3238** has been created by fsync-ing the directory that contains the file.
3239** If we do not do this and we encounter a power failure, the directory
3240** entry for the journal might not exist after we reboot. The next
3241** SQLite to access the file will not know that the journal exists (because
3242** the directory entry for the journal was never created) and the transaction
3243** will not roll back - possibly leading to database corruption.
3244*/
3245static int unixSync(sqlite3_file *id, int flags){
3246 int rc;
3247 unixFile *pFile = (unixFile*)id;
3248
3249 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3250 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3251
3252 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3253 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3254 || (flags&0x0F)==SQLITE_SYNC_FULL
3255 );
3256
3257 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3258 ** line is to test that doing so does not cause any problems.
3259 */
3260 SimulateDiskfullError( return SQLITE_FULL );
3261
3262 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003263 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003264 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3265 SimulateIOError( rc=1 );
3266 if( rc ){
3267 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003268 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003269 }
3270 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003271 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3272 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003273#ifndef SQLITE_DISABLE_DIRSYNC
3274 /* The directory sync is only attempted if full_fsync is
3275 ** turned off or unavailable. If a full_fsync occurred above,
3276 ** then the directory sync is superfluous.
3277 */
3278 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3279 /*
3280 ** We have received multiple reports of fsync() returning
3281 ** errors when applied to directories on certain file systems.
3282 ** A failed directory sync is not a big deal. So it seems
3283 ** better to ignore the error. Ticket #1657
3284 */
3285 /* pFile->lastErrno = errno; */
3286 /* return SQLITE_IOERR; */
3287 }
3288#endif
drh0e9365c2011-03-02 02:08:13 +00003289 /* Only need to sync once, so close the directory when we are done */
3290 robust_close(pFile, pFile->dirfd, __LINE__);
3291 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003292 }
3293 return rc;
3294}
3295
3296/*
3297** Truncate an open file to a specified size
3298*/
3299static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003300 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003301 int rc;
dan6e09d692010-07-27 18:34:15 +00003302 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003303 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003304
3305 /* If the user has configured a chunk-size for this file, truncate the
3306 ** file so that it consists of an integer number of chunks (i.e. the
3307 ** actual file size after the operation may be larger than the requested
3308 ** size).
3309 */
3310 if( pFile->szChunk ){
3311 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3312 }
3313
drhff812312011-02-23 13:33:46 +00003314 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003315 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003316 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003317 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003318 }else{
drh3313b142009-11-06 04:13:18 +00003319#ifndef NDEBUG
3320 /* If we are doing a normal write to a database file (as opposed to
3321 ** doing a hot-journal rollback or a write to some file other than a
3322 ** normal database file) and we truncate the file to zero length,
3323 ** that effectively updates the change counter. This might happen
3324 ** when restoring a database using the backup API from a zero-length
3325 ** source.
3326 */
dan6e09d692010-07-27 18:34:15 +00003327 if( pFile->inNormalWrite && nByte==0 ){
3328 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003329 }
3330#endif
3331
drh734c9862008-11-28 15:37:20 +00003332 return SQLITE_OK;
3333 }
3334}
3335
3336/*
3337** Determine the current size of a file in bytes
3338*/
3339static int unixFileSize(sqlite3_file *id, i64 *pSize){
3340 int rc;
3341 struct stat buf;
3342 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003343 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003344 SimulateIOError( rc=1 );
3345 if( rc!=0 ){
3346 ((unixFile*)id)->lastErrno = errno;
3347 return SQLITE_IOERR_FSTAT;
3348 }
3349 *pSize = buf.st_size;
3350
drh8af6c222010-05-14 12:43:01 +00003351 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003352 ** writes a single byte into that file in order to work around a bug
3353 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3354 ** layers, we need to report this file size as zero even though it is
3355 ** really 1. Ticket #3260.
3356 */
3357 if( *pSize==1 ) *pSize = 0;
3358
3359
3360 return SQLITE_OK;
3361}
3362
drhd2cb50b2009-01-09 21:41:17 +00003363#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003364/*
3365** Handler for proxy-locking file-control verbs. Defined below in the
3366** proxying locking division.
3367*/
3368static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003369#endif
drh715ff302008-12-03 22:32:44 +00003370
dan502019c2010-07-28 14:26:17 +00003371/*
3372** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3373** file-control operation.
3374**
3375** If the user has configured a chunk-size for this file, it could be
3376** that the file needs to be extended at this point. Otherwise, the
3377** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3378*/
3379static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3380 if( pFile->szChunk ){
3381 i64 nSize; /* Required file size */
3382 struct stat buf; /* Used to hold return values of fstat() */
3383
drh99ab3b12011-03-02 15:09:07 +00003384 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003385
3386 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3387 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003388
dan502019c2010-07-28 14:26:17 +00003389#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003390 /* The code below is handling the return value of osFallocate()
3391 ** correctly. posix_fallocate() is defined to "returns zero on success,
3392 ** or an error number on failure". See the manpage for details. */
3393 int err;
drhff812312011-02-23 13:33:46 +00003394 do{
dan661d71a2011-03-30 19:08:03 +00003395 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3396 }while( err==EINTR );
3397 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003398#else
3399 /* If the OS does not have posix_fallocate(), fake it. First use
3400 ** ftruncate() to set the file size, then write a single byte to
3401 ** the last byte in each block within the extended region. This
3402 ** is the same technique used by glibc to implement posix_fallocate()
3403 ** on systems that do not have a real fallocate() system call.
3404 */
3405 int nBlk = buf.st_blksize; /* File-system block size */
3406 i64 iWrite; /* Next offset to write to */
3407 int nWrite; /* Return value from seekAndWrite() */
3408
drhff812312011-02-23 13:33:46 +00003409 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003410 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003411 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003412 }
3413 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3414 do {
3415 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3416 iWrite += nBlk;
3417 } while( nWrite==1 && iWrite<nSize );
3418 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3419#endif
3420 }
3421 }
3422
3423 return SQLITE_OK;
3424}
danielk1977ad94b582007-08-20 06:44:22 +00003425
danielk1977e3026632004-06-22 11:29:02 +00003426/*
drh9e33c2c2007-08-31 18:34:59 +00003427** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003428*/
drhcc6bb3e2007-08-31 16:11:35 +00003429static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003430 switch( op ){
3431 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003432 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003433 return SQLITE_OK;
3434 }
drh7708e972008-11-29 00:56:52 +00003435 case SQLITE_LAST_ERRNO: {
3436 *(int*)pArg = ((unixFile*)id)->lastErrno;
3437 return SQLITE_OK;
3438 }
dan6e09d692010-07-27 18:34:15 +00003439 case SQLITE_FCNTL_CHUNK_SIZE: {
3440 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003441 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003442 }
drh9ff27ec2010-05-19 19:26:05 +00003443 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003444 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003445 }
drh8f941bc2009-01-14 23:03:40 +00003446#ifndef NDEBUG
3447 /* The pager calls this method to signal that it has done
3448 ** a rollback and that the database is therefore unchanged and
3449 ** it hence it is OK for the transaction change counter to be
3450 ** unchanged.
3451 */
3452 case SQLITE_FCNTL_DB_UNCHANGED: {
3453 ((unixFile*)id)->dbUpdate = 0;
3454 return SQLITE_OK;
3455 }
3456#endif
drhd2cb50b2009-01-09 21:41:17 +00003457#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003458 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003459 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003460 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003461 }
drhd2cb50b2009-01-09 21:41:17 +00003462#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003463 case SQLITE_FCNTL_SYNC_OMITTED: {
3464 return SQLITE_OK; /* A no-op */
3465 }
drh9e33c2c2007-08-31 18:34:59 +00003466 }
drh0b52b7d2011-01-26 19:46:22 +00003467 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003468}
3469
3470/*
danielk1977a3d4c882007-03-23 10:08:38 +00003471** Return the sector size in bytes of the underlying block device for
3472** the specified file. This is almost always 512 bytes, but may be
3473** larger for some devices.
3474**
3475** SQLite code assumes this function cannot fail. It also assumes that
3476** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003477** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003478** same for both.
3479*/
danielk1977397d65f2008-11-19 11:35:39 +00003480static int unixSectorSize(sqlite3_file *NotUsed){
3481 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003482 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003483}
3484
danielk197790949c22007-08-17 16:50:38 +00003485/*
danielk1977397d65f2008-11-19 11:35:39 +00003486** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003487*/
danielk1977397d65f2008-11-19 11:35:39 +00003488static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3489 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003490 return 0;
3491}
3492
drhd9e5c4f2010-05-12 18:01:39 +00003493#ifndef SQLITE_OMIT_WAL
3494
3495
3496/*
drhd91c68f2010-05-14 14:52:25 +00003497** Object used to represent an shared memory buffer.
3498**
3499** When multiple threads all reference the same wal-index, each thread
3500** has its own unixShm object, but they all point to a single instance
3501** of this unixShmNode object. In other words, each wal-index is opened
3502** only once per process.
3503**
3504** Each unixShmNode object is connected to a single unixInodeInfo object.
3505** We could coalesce this object into unixInodeInfo, but that would mean
3506** every open file that does not use shared memory (in other words, most
3507** open files) would have to carry around this extra information. So
3508** the unixInodeInfo object contains a pointer to this unixShmNode object
3509** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003510**
3511** unixMutexHeld() must be true when creating or destroying
3512** this object or while reading or writing the following fields:
3513**
3514** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003515**
3516** The following fields are read-only after the object is created:
3517**
3518** fid
3519** zFilename
3520**
drhd91c68f2010-05-14 14:52:25 +00003521** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003522** unixMutexHeld() is true when reading or writing any other field
3523** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003524*/
drhd91c68f2010-05-14 14:52:25 +00003525struct unixShmNode {
3526 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003527 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003528 char *zFilename; /* Name of the mmapped file */
3529 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003530 int szRegion; /* Size of shared-memory regions */
3531 int nRegion; /* Size of array apRegion */
3532 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003533 int nRef; /* Number of unixShm objects pointing to this */
3534 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003535#ifdef SQLITE_DEBUG
3536 u8 exclMask; /* Mask of exclusive locks held */
3537 u8 sharedMask; /* Mask of shared locks held */
3538 u8 nextShmId; /* Next available unixShm.id value */
3539#endif
3540};
3541
3542/*
drhd9e5c4f2010-05-12 18:01:39 +00003543** Structure used internally by this VFS to record the state of an
3544** open shared memory connection.
3545**
drhd91c68f2010-05-14 14:52:25 +00003546** The following fields are initialized when this object is created and
3547** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003548**
drhd91c68f2010-05-14 14:52:25 +00003549** unixShm.pFile
3550** unixShm.id
3551**
3552** All other fields are read/write. The unixShm.pFile->mutex must be held
3553** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003554*/
3555struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003556 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3557 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003558 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003559 u16 sharedMask; /* Mask of shared locks held */
3560 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003561#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003562 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003563#endif
3564};
3565
3566/*
drhd9e5c4f2010-05-12 18:01:39 +00003567** Constants used for locking
3568*/
drhbd9676c2010-06-23 17:58:38 +00003569#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003570#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003571
drhd9e5c4f2010-05-12 18:01:39 +00003572/*
drh73b64e42010-05-30 19:55:15 +00003573** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003574**
3575** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3576** otherwise.
3577*/
3578static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003579 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3580 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003581 int ofst, /* First byte of the locking range */
3582 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003583){
3584 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003585 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003586
drhd91c68f2010-05-14 14:52:25 +00003587 /* Access to the unixShmNode object is serialized by the caller */
3588 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003589
drh73b64e42010-05-30 19:55:15 +00003590 /* Shared locks never span more than one byte */
3591 assert( n==1 || lockType!=F_RDLCK );
3592
3593 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003594 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003595
drh3cb93392011-03-12 18:10:44 +00003596 if( pShmNode->h>=0 ){
3597 /* Initialize the locking parameters */
3598 memset(&f, 0, sizeof(f));
3599 f.l_type = lockType;
3600 f.l_whence = SEEK_SET;
3601 f.l_start = ofst;
3602 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003603
drh3cb93392011-03-12 18:10:44 +00003604 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3605 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3606 }
drhd9e5c4f2010-05-12 18:01:39 +00003607
3608 /* Update the global lock state and do debug tracing */
3609#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003610 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003611 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003612 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003613 if( rc==SQLITE_OK ){
3614 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003615 OSTRACE(("unlock %d ok", ofst));
3616 pShmNode->exclMask &= ~mask;
3617 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003618 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003619 OSTRACE(("read-lock %d ok", ofst));
3620 pShmNode->exclMask &= ~mask;
3621 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003622 }else{
3623 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003624 OSTRACE(("write-lock %d ok", ofst));
3625 pShmNode->exclMask |= mask;
3626 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003627 }
3628 }else{
3629 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003630 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003631 }else if( lockType==F_RDLCK ){
3632 OSTRACE(("read-lock failed"));
3633 }else{
3634 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003635 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003636 }
3637 }
drh20e1f082010-05-31 16:10:12 +00003638 OSTRACE((" - afterwards %03x,%03x\n",
3639 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003640 }
drhd9e5c4f2010-05-12 18:01:39 +00003641#endif
3642
3643 return rc;
3644}
3645
drhd9e5c4f2010-05-12 18:01:39 +00003646
3647/*
drhd91c68f2010-05-14 14:52:25 +00003648** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003649**
3650** This is not a VFS shared-memory method; it is a utility function called
3651** by VFS shared-memory methods.
3652*/
drhd91c68f2010-05-14 14:52:25 +00003653static void unixShmPurge(unixFile *pFd){
3654 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003655 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003656 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003657 int i;
drhd91c68f2010-05-14 14:52:25 +00003658 assert( p->pInode==pFd->pInode );
3659 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003660 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003661 if( p->h>=0 ){
3662 munmap(p->apRegion[i], p->szRegion);
3663 }else{
3664 sqlite3_free(p->apRegion[i]);
3665 }
dan13a3cb82010-06-11 19:04:21 +00003666 }
dan18801912010-06-14 14:07:50 +00003667 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003668 if( p->h>=0 ){
3669 robust_close(pFd, p->h, __LINE__);
3670 p->h = -1;
3671 }
drhd91c68f2010-05-14 14:52:25 +00003672 p->pInode->pShmNode = 0;
3673 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003674 }
3675}
3676
3677/*
danda9fe0c2010-07-13 18:44:03 +00003678** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003679** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003680**
drh7234c6d2010-06-19 15:10:09 +00003681** The file used to implement shared-memory is in the same directory
3682** as the open database file and has the same name as the open database
3683** file with the "-shm" suffix added. For example, if the database file
3684** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003685** for shared memory will be called "/home/user1/config.db-shm".
3686**
3687** Another approach to is to use files in /dev/shm or /dev/tmp or an
3688** some other tmpfs mount. But if a file in a different directory
3689** from the database file is used, then differing access permissions
3690** or a chroot() might cause two different processes on the same
3691** database to end up using different files for shared memory -
3692** meaning that their memory would not really be shared - resulting
3693** in database corruption. Nevertheless, this tmpfs file usage
3694** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3695** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3696** option results in an incompatible build of SQLite; builds of SQLite
3697** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3698** same database file at the same time, database corruption will likely
3699** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3700** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003701**
3702** When opening a new shared-memory file, if no other instances of that
3703** file are currently open, in this process or in other processes, then
3704** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003705**
3706** If the original database file (pDbFd) is using the "unix-excl" VFS
3707** that means that an exclusive lock is held on the database file and
3708** that no other processes are able to read or write the database. In
3709** that case, we do not really need shared memory. No shared memory
3710** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003711*/
danda9fe0c2010-07-13 18:44:03 +00003712static int unixOpenSharedMemory(unixFile *pDbFd){
3713 struct unixShm *p = 0; /* The connection to be opened */
3714 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3715 int rc; /* Result code */
3716 unixInodeInfo *pInode; /* The inode of fd */
3717 char *zShmFilename; /* Name of the file used for SHM */
3718 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003719
danda9fe0c2010-07-13 18:44:03 +00003720 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003721 p = sqlite3_malloc( sizeof(*p) );
3722 if( p==0 ) return SQLITE_NOMEM;
3723 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003724 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003725
danda9fe0c2010-07-13 18:44:03 +00003726 /* Check to see if a unixShmNode object already exists. Reuse an existing
3727 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003728 */
3729 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003730 pInode = pDbFd->pInode;
3731 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003732 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003733 struct stat sStat; /* fstat() info for database file */
3734
3735 /* Call fstat() to figure out the permissions on the database file. If
3736 ** a new *-shm file is created, an attempt will be made to create it
3737 ** with the same permissions. The actual permissions the file is created
3738 ** with are subject to the current umask setting.
3739 */
drh3cb93392011-03-12 18:10:44 +00003740 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003741 rc = SQLITE_IOERR_FSTAT;
3742 goto shm_open_err;
3743 }
3744
drha4ced192010-07-15 18:32:40 +00003745#ifdef SQLITE_SHM_DIRECTORY
3746 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3747#else
drh7234c6d2010-06-19 15:10:09 +00003748 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003749#endif
drh7234c6d2010-06-19 15:10:09 +00003750 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003751 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003752 rc = SQLITE_NOMEM;
3753 goto shm_open_err;
3754 }
drhd91c68f2010-05-14 14:52:25 +00003755 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003756 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003757#ifdef SQLITE_SHM_DIRECTORY
3758 sqlite3_snprintf(nShmFilename, zShmFilename,
3759 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3760 (u32)sStat.st_ino, (u32)sStat.st_dev);
3761#else
drh7234c6d2010-06-19 15:10:09 +00003762 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003763#endif
drhd91c68f2010-05-14 14:52:25 +00003764 pShmNode->h = -1;
3765 pDbFd->pInode->pShmNode = pShmNode;
3766 pShmNode->pInode = pDbFd->pInode;
3767 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3768 if( pShmNode->mutex==0 ){
3769 rc = SQLITE_NOMEM;
3770 goto shm_open_err;
3771 }
drhd9e5c4f2010-05-12 18:01:39 +00003772
drh3cb93392011-03-12 18:10:44 +00003773 if( pInode->bProcessLock==0 ){
3774 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3775 (sStat.st_mode & 0777));
3776 if( pShmNode->h<0 ){
3777 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3778 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003779 }
drh3cb93392011-03-12 18:10:44 +00003780
3781 /* Check to see if another process is holding the dead-man switch.
3782 ** If not, truncate the file to zero length.
3783 */
3784 rc = SQLITE_OK;
3785 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3786 if( robust_ftruncate(pShmNode->h, 0) ){
3787 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3788 }
3789 }
3790 if( rc==SQLITE_OK ){
3791 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3792 }
3793 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003794 }
drhd9e5c4f2010-05-12 18:01:39 +00003795 }
3796
drhd91c68f2010-05-14 14:52:25 +00003797 /* Make the new connection a child of the unixShmNode */
3798 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003799#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003800 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003801#endif
drhd91c68f2010-05-14 14:52:25 +00003802 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003803 pDbFd->pShm = p;
3804 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003805
3806 /* The reference count on pShmNode has already been incremented under
3807 ** the cover of the unixEnterMutex() mutex and the pointer from the
3808 ** new (struct unixShm) object to the pShmNode has been set. All that is
3809 ** left to do is to link the new object into the linked list starting
3810 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3811 ** mutex.
3812 */
3813 sqlite3_mutex_enter(pShmNode->mutex);
3814 p->pNext = pShmNode->pFirst;
3815 pShmNode->pFirst = p;
3816 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003817 return SQLITE_OK;
3818
3819 /* Jump here on any error */
3820shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003821 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003822 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003823 unixLeaveMutex();
3824 return rc;
3825}
3826
3827/*
danda9fe0c2010-07-13 18:44:03 +00003828** This function is called to obtain a pointer to region iRegion of the
3829** shared-memory associated with the database file fd. Shared-memory regions
3830** are numbered starting from zero. Each shared-memory region is szRegion
3831** bytes in size.
3832**
3833** If an error occurs, an error code is returned and *pp is set to NULL.
3834**
3835** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3836** region has not been allocated (by any client, including one running in a
3837** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3838** bExtend is non-zero and the requested shared-memory region has not yet
3839** been allocated, it is allocated by this function.
3840**
3841** If the shared-memory region has already been allocated or is allocated by
3842** this call as described above, then it is mapped into this processes
3843** address space (if it is not already), *pp is set to point to the mapped
3844** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003845*/
danda9fe0c2010-07-13 18:44:03 +00003846static int unixShmMap(
3847 sqlite3_file *fd, /* Handle open on database file */
3848 int iRegion, /* Region to retrieve */
3849 int szRegion, /* Size of regions */
3850 int bExtend, /* True to extend file if necessary */
3851 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003852){
danda9fe0c2010-07-13 18:44:03 +00003853 unixFile *pDbFd = (unixFile*)fd;
3854 unixShm *p;
3855 unixShmNode *pShmNode;
3856 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003857
danda9fe0c2010-07-13 18:44:03 +00003858 /* If the shared-memory file has not yet been opened, open it now. */
3859 if( pDbFd->pShm==0 ){
3860 rc = unixOpenSharedMemory(pDbFd);
3861 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003862 }
drhd9e5c4f2010-05-12 18:01:39 +00003863
danda9fe0c2010-07-13 18:44:03 +00003864 p = pDbFd->pShm;
3865 pShmNode = p->pShmNode;
3866 sqlite3_mutex_enter(pShmNode->mutex);
3867 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003868 assert( pShmNode->pInode==pDbFd->pInode );
3869 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3870 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003871
3872 if( pShmNode->nRegion<=iRegion ){
3873 char **apNew; /* New apRegion[] array */
3874 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3875 struct stat sStat; /* Used by fstat() */
3876
3877 pShmNode->szRegion = szRegion;
3878
drh3cb93392011-03-12 18:10:44 +00003879 if( pShmNode->h>=0 ){
3880 /* The requested region is not mapped into this processes address space.
3881 ** Check to see if it has been allocated (i.e. if the wal-index file is
3882 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003883 */
drh3cb93392011-03-12 18:10:44 +00003884 if( osFstat(pShmNode->h, &sStat) ){
3885 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003886 goto shmpage_out;
3887 }
drh3cb93392011-03-12 18:10:44 +00003888
3889 if( sStat.st_size<nByte ){
3890 /* The requested memory region does not exist. If bExtend is set to
3891 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3892 **
3893 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3894 ** the requested memory region.
3895 */
3896 if( !bExtend ) goto shmpage_out;
3897 if( robust_ftruncate(pShmNode->h, nByte) ){
3898 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3899 pShmNode->zFilename);
3900 goto shmpage_out;
3901 }
3902 }
danda9fe0c2010-07-13 18:44:03 +00003903 }
3904
3905 /* Map the requested memory region into this processes address space. */
3906 apNew = (char **)sqlite3_realloc(
3907 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3908 );
3909 if( !apNew ){
3910 rc = SQLITE_IOERR_NOMEM;
3911 goto shmpage_out;
3912 }
3913 pShmNode->apRegion = apNew;
3914 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003915 void *pMem;
3916 if( pShmNode->h>=0 ){
3917 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3918 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3919 );
3920 if( pMem==MAP_FAILED ){
3921 rc = SQLITE_IOERR;
3922 goto shmpage_out;
3923 }
3924 }else{
3925 pMem = sqlite3_malloc(szRegion);
3926 if( pMem==0 ){
3927 rc = SQLITE_NOMEM;
3928 goto shmpage_out;
3929 }
3930 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003931 }
3932 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3933 pShmNode->nRegion++;
3934 }
3935 }
3936
3937shmpage_out:
3938 if( pShmNode->nRegion>iRegion ){
3939 *pp = pShmNode->apRegion[iRegion];
3940 }else{
3941 *pp = 0;
3942 }
3943 sqlite3_mutex_leave(pShmNode->mutex);
3944 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003945}
3946
3947/*
drhd9e5c4f2010-05-12 18:01:39 +00003948** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003949**
3950** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3951** different here than in posix. In xShmLock(), one can go from unlocked
3952** to shared and back or from unlocked to exclusive and back. But one may
3953** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003954*/
3955static int unixShmLock(
3956 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003957 int ofst, /* First lock to acquire or release */
3958 int n, /* Number of locks to acquire or release */
3959 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003960){
drh73b64e42010-05-30 19:55:15 +00003961 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3962 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3963 unixShm *pX; /* For looping over all siblings */
3964 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3965 int rc = SQLITE_OK; /* Result code */
3966 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003967
drhd91c68f2010-05-14 14:52:25 +00003968 assert( pShmNode==pDbFd->pInode->pShmNode );
3969 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003970 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003971 assert( n>=1 );
3972 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3973 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3974 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3975 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3976 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003977 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3978 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003979
drhc99597c2010-05-31 01:41:15 +00003980 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003981 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003982 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003983 if( flags & SQLITE_SHM_UNLOCK ){
3984 u16 allMask = 0; /* Mask of locks held by siblings */
3985
3986 /* See if any siblings hold this same lock */
3987 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3988 if( pX==p ) continue;
3989 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3990 allMask |= pX->sharedMask;
3991 }
3992
3993 /* Unlock the system-level locks */
3994 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003995 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003996 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003997 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003998 }
drh73b64e42010-05-30 19:55:15 +00003999
4000 /* Undo the local locks */
4001 if( rc==SQLITE_OK ){
4002 p->exclMask &= ~mask;
4003 p->sharedMask &= ~mask;
4004 }
4005 }else if( flags & SQLITE_SHM_SHARED ){
4006 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4007
4008 /* Find out which shared locks are already held by sibling connections.
4009 ** If any sibling already holds an exclusive lock, go ahead and return
4010 ** SQLITE_BUSY.
4011 */
4012 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004013 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004014 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004015 break;
4016 }
4017 allShared |= pX->sharedMask;
4018 }
4019
4020 /* Get shared locks at the system level, if necessary */
4021 if( rc==SQLITE_OK ){
4022 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004023 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004024 }else{
drh73b64e42010-05-30 19:55:15 +00004025 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004026 }
drhd9e5c4f2010-05-12 18:01:39 +00004027 }
drh73b64e42010-05-30 19:55:15 +00004028
4029 /* Get the local shared locks */
4030 if( rc==SQLITE_OK ){
4031 p->sharedMask |= mask;
4032 }
4033 }else{
4034 /* Make sure no sibling connections hold locks that will block this
4035 ** lock. If any do, return SQLITE_BUSY right away.
4036 */
4037 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004038 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4039 rc = SQLITE_BUSY;
4040 break;
4041 }
4042 }
4043
4044 /* Get the exclusive locks at the system level. Then if successful
4045 ** also mark the local connection as being locked.
4046 */
4047 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004048 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004049 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004050 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004051 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004052 }
drhd9e5c4f2010-05-12 18:01:39 +00004053 }
4054 }
drhd91c68f2010-05-14 14:52:25 +00004055 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004056 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4057 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004058 return rc;
4059}
4060
drh286a2882010-05-20 23:51:06 +00004061/*
4062** Implement a memory barrier or memory fence on shared memory.
4063**
4064** All loads and stores begun before the barrier must complete before
4065** any load or store begun after the barrier.
4066*/
4067static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004068 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004069){
drhff828942010-06-26 21:34:06 +00004070 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004071 unixEnterMutex();
4072 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004073}
4074
dan18801912010-06-14 14:07:50 +00004075/*
danda9fe0c2010-07-13 18:44:03 +00004076** Close a connection to shared-memory. Delete the underlying
4077** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004078**
4079** If there is no shared memory associated with the connection then this
4080** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004081*/
danda9fe0c2010-07-13 18:44:03 +00004082static int unixShmUnmap(
4083 sqlite3_file *fd, /* The underlying database file */
4084 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004085){
danda9fe0c2010-07-13 18:44:03 +00004086 unixShm *p; /* The connection to be closed */
4087 unixShmNode *pShmNode; /* The underlying shared-memory file */
4088 unixShm **pp; /* For looping over sibling connections */
4089 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004090
danda9fe0c2010-07-13 18:44:03 +00004091 pDbFd = (unixFile*)fd;
4092 p = pDbFd->pShm;
4093 if( p==0 ) return SQLITE_OK;
4094 pShmNode = p->pShmNode;
4095
4096 assert( pShmNode==pDbFd->pInode->pShmNode );
4097 assert( pShmNode->pInode==pDbFd->pInode );
4098
4099 /* Remove connection p from the set of connections associated
4100 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004101 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004102 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4103 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004104
danda9fe0c2010-07-13 18:44:03 +00004105 /* Free the connection p */
4106 sqlite3_free(p);
4107 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004108 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004109
4110 /* If pShmNode->nRef has reached 0, then close the underlying
4111 ** shared-memory file, too */
4112 unixEnterMutex();
4113 assert( pShmNode->nRef>0 );
4114 pShmNode->nRef--;
4115 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004116 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004117 unixShmPurge(pDbFd);
4118 }
4119 unixLeaveMutex();
4120
4121 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004122}
drh286a2882010-05-20 23:51:06 +00004123
danda9fe0c2010-07-13 18:44:03 +00004124
drhd9e5c4f2010-05-12 18:01:39 +00004125#else
drh6b017cc2010-06-14 18:01:46 +00004126# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004127# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004128# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004129# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004130#endif /* #ifndef SQLITE_OMIT_WAL */
4131
drh734c9862008-11-28 15:37:20 +00004132/*
4133** Here ends the implementation of all sqlite3_file methods.
4134**
4135********************** End sqlite3_file Methods *******************************
4136******************************************************************************/
4137
4138/*
drh6b9d6dd2008-12-03 19:34:47 +00004139** This division contains definitions of sqlite3_io_methods objects that
4140** implement various file locking strategies. It also contains definitions
4141** of "finder" functions. A finder-function is used to locate the appropriate
4142** sqlite3_io_methods object for a particular database file. The pAppData
4143** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4144** the correct finder-function for that VFS.
4145**
4146** Most finder functions return a pointer to a fixed sqlite3_io_methods
4147** object. The only interesting finder-function is autolockIoFinder, which
4148** looks at the filesystem type and tries to guess the best locking
4149** strategy from that.
4150**
drh1875f7a2008-12-08 18:19:17 +00004151** For finder-funtion F, two objects are created:
4152**
4153** (1) The real finder-function named "FImpt()".
4154**
dane946c392009-08-22 11:39:46 +00004155** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004156**
4157**
4158** A pointer to the F pointer is used as the pAppData value for VFS
4159** objects. We have to do this instead of letting pAppData point
4160** directly at the finder-function since C90 rules prevent a void*
4161** from be cast into a function pointer.
4162**
drh6b9d6dd2008-12-03 19:34:47 +00004163**
drh7708e972008-11-29 00:56:52 +00004164** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004165**
drh7708e972008-11-29 00:56:52 +00004166** * A constant sqlite3_io_methods object call METHOD that has locking
4167** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4168**
4169** * An I/O method finder function called FINDER that returns a pointer
4170** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004171*/
drhd9e5c4f2010-05-12 18:01:39 +00004172#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004173static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004174 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004175 CLOSE, /* xClose */ \
4176 unixRead, /* xRead */ \
4177 unixWrite, /* xWrite */ \
4178 unixTruncate, /* xTruncate */ \
4179 unixSync, /* xSync */ \
4180 unixFileSize, /* xFileSize */ \
4181 LOCK, /* xLock */ \
4182 UNLOCK, /* xUnlock */ \
4183 CKLOCK, /* xCheckReservedLock */ \
4184 unixFileControl, /* xFileControl */ \
4185 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004186 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004187 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004188 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004189 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004190 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004191}; \
drh0c2694b2009-09-03 16:23:44 +00004192static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4193 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004194 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004195} \
drh0c2694b2009-09-03 16:23:44 +00004196static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004197 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004198
4199/*
4200** Here are all of the sqlite3_io_methods objects for each of the
4201** locking strategies. Functions that return pointers to these methods
4202** are also created.
4203*/
4204IOMETHODS(
4205 posixIoFinder, /* Finder function name */
4206 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004207 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004208 unixClose, /* xClose method */
4209 unixLock, /* xLock method */
4210 unixUnlock, /* xUnlock method */
4211 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004212)
drh7708e972008-11-29 00:56:52 +00004213IOMETHODS(
4214 nolockIoFinder, /* Finder function name */
4215 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004216 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004217 nolockClose, /* xClose method */
4218 nolockLock, /* xLock method */
4219 nolockUnlock, /* xUnlock method */
4220 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004221)
drh7708e972008-11-29 00:56:52 +00004222IOMETHODS(
4223 dotlockIoFinder, /* Finder function name */
4224 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004225 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004226 dotlockClose, /* xClose method */
4227 dotlockLock, /* xLock method */
4228 dotlockUnlock, /* xUnlock method */
4229 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004230)
drh7708e972008-11-29 00:56:52 +00004231
chw78a13182009-04-07 05:35:03 +00004232#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004233IOMETHODS(
4234 flockIoFinder, /* Finder function name */
4235 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004236 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004237 flockClose, /* xClose method */
4238 flockLock, /* xLock method */
4239 flockUnlock, /* xUnlock method */
4240 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004241)
drh7708e972008-11-29 00:56:52 +00004242#endif
4243
drh6c7d5c52008-11-21 20:32:33 +00004244#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004245IOMETHODS(
4246 semIoFinder, /* Finder function name */
4247 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004248 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004249 semClose, /* xClose method */
4250 semLock, /* xLock method */
4251 semUnlock, /* xUnlock method */
4252 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004253)
aswiftaebf4132008-11-21 00:10:35 +00004254#endif
drh7708e972008-11-29 00:56:52 +00004255
drhd2cb50b2009-01-09 21:41:17 +00004256#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004257IOMETHODS(
4258 afpIoFinder, /* Finder function name */
4259 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004260 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004261 afpClose, /* xClose method */
4262 afpLock, /* xLock method */
4263 afpUnlock, /* xUnlock method */
4264 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004265)
drh715ff302008-12-03 22:32:44 +00004266#endif
4267
4268/*
4269** The proxy locking method is a "super-method" in the sense that it
4270** opens secondary file descriptors for the conch and lock files and
4271** it uses proxy, dot-file, AFP, and flock() locking methods on those
4272** secondary files. For this reason, the division that implements
4273** proxy locking is located much further down in the file. But we need
4274** to go ahead and define the sqlite3_io_methods and finder function
4275** for proxy locking here. So we forward declare the I/O methods.
4276*/
drhd2cb50b2009-01-09 21:41:17 +00004277#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004278static int proxyClose(sqlite3_file*);
4279static int proxyLock(sqlite3_file*, int);
4280static int proxyUnlock(sqlite3_file*, int);
4281static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004282IOMETHODS(
4283 proxyIoFinder, /* Finder function name */
4284 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004285 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004286 proxyClose, /* xClose method */
4287 proxyLock, /* xLock method */
4288 proxyUnlock, /* xUnlock method */
4289 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004290)
aswiftaebf4132008-11-21 00:10:35 +00004291#endif
drh7708e972008-11-29 00:56:52 +00004292
drh7ed97b92010-01-20 13:07:21 +00004293/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4294#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4295IOMETHODS(
4296 nfsIoFinder, /* Finder function name */
4297 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004298 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004299 unixClose, /* xClose method */
4300 unixLock, /* xLock method */
4301 nfsUnlock, /* xUnlock method */
4302 unixCheckReservedLock /* xCheckReservedLock method */
4303)
4304#endif
drh7708e972008-11-29 00:56:52 +00004305
drhd2cb50b2009-01-09 21:41:17 +00004306#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004307/*
drh6b9d6dd2008-12-03 19:34:47 +00004308** This "finder" function attempts to determine the best locking strategy
4309** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004310** object that implements that strategy.
4311**
4312** This is for MacOSX only.
4313*/
drh1875f7a2008-12-08 18:19:17 +00004314static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004315 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004316 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004317){
4318 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004319 const char *zFilesystem; /* Filesystem type name */
4320 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004321 } aMap[] = {
4322 { "hfs", &posixIoMethods },
4323 { "ufs", &posixIoMethods },
4324 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004325 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004326 { "webdav", &nolockIoMethods },
4327 { 0, 0 }
4328 };
4329 int i;
4330 struct statfs fsInfo;
4331 struct flock lockInfo;
4332
4333 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004334 /* If filePath==NULL that means we are dealing with a transient file
4335 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004336 return &nolockIoMethods;
4337 }
4338 if( statfs(filePath, &fsInfo) != -1 ){
4339 if( fsInfo.f_flags & MNT_RDONLY ){
4340 return &nolockIoMethods;
4341 }
4342 for(i=0; aMap[i].zFilesystem; i++){
4343 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4344 return aMap[i].pMethods;
4345 }
4346 }
4347 }
4348
4349 /* Default case. Handles, amongst others, "nfs".
4350 ** Test byte-range lock using fcntl(). If the call succeeds,
4351 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004352 */
drh7708e972008-11-29 00:56:52 +00004353 lockInfo.l_len = 1;
4354 lockInfo.l_start = 0;
4355 lockInfo.l_whence = SEEK_SET;
4356 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004357 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004358 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4359 return &nfsIoMethods;
4360 } else {
4361 return &posixIoMethods;
4362 }
drh7708e972008-11-29 00:56:52 +00004363 }else{
4364 return &dotlockIoMethods;
4365 }
4366}
drh0c2694b2009-09-03 16:23:44 +00004367static const sqlite3_io_methods
4368 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004369
drhd2cb50b2009-01-09 21:41:17 +00004370#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004371
chw78a13182009-04-07 05:35:03 +00004372#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4373/*
4374** This "finder" function attempts to determine the best locking strategy
4375** for the database file "filePath". It then returns the sqlite3_io_methods
4376** object that implements that strategy.
4377**
4378** This is for VXWorks only.
4379*/
4380static const sqlite3_io_methods *autolockIoFinderImpl(
4381 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004382 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004383){
4384 struct flock lockInfo;
4385
4386 if( !filePath ){
4387 /* If filePath==NULL that means we are dealing with a transient file
4388 ** that does not need to be locked. */
4389 return &nolockIoMethods;
4390 }
4391
4392 /* Test if fcntl() is supported and use POSIX style locks.
4393 ** Otherwise fall back to the named semaphore method.
4394 */
4395 lockInfo.l_len = 1;
4396 lockInfo.l_start = 0;
4397 lockInfo.l_whence = SEEK_SET;
4398 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004399 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004400 return &posixIoMethods;
4401 }else{
4402 return &semIoMethods;
4403 }
4404}
drh0c2694b2009-09-03 16:23:44 +00004405static const sqlite3_io_methods
4406 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004407
4408#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4409
drh7708e972008-11-29 00:56:52 +00004410/*
4411** An abstract type for a pointer to a IO method finder function:
4412*/
drh0c2694b2009-09-03 16:23:44 +00004413typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004414
aswiftaebf4132008-11-21 00:10:35 +00004415
drh734c9862008-11-28 15:37:20 +00004416/****************************************************************************
4417**************************** sqlite3_vfs methods ****************************
4418**
4419** This division contains the implementation of methods on the
4420** sqlite3_vfs object.
4421*/
4422
danielk1977a3d4c882007-03-23 10:08:38 +00004423/*
danielk1977e339d652008-06-28 11:23:00 +00004424** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004425*/
4426static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004427 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004428 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004429 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004430 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004431 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004432 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004433 int isDelete, /* Delete on close if true */
4434 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004435){
drh7708e972008-11-29 00:56:52 +00004436 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004437 unixFile *pNew = (unixFile *)pId;
4438 int rc = SQLITE_OK;
4439
drh8af6c222010-05-14 12:43:01 +00004440 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004441
dane946c392009-08-22 11:39:46 +00004442 /* Parameter isDelete is only used on vxworks. Express this explicitly
4443 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004444 */
drh7708e972008-11-29 00:56:52 +00004445 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004446
dan00157392010-10-05 11:33:15 +00004447 /* Usually the path zFilename should not be a relative pathname. The
4448 ** exception is when opening the proxy "conch" file in builds that
4449 ** include the special Apple locking styles.
4450 */
dan00157392010-10-05 11:33:15 +00004451#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004452 assert( zFilename==0 || zFilename[0]=='/'
4453 || pVfs->pAppData==(void*)&autolockIoFinder );
4454#else
4455 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004456#endif
dan00157392010-10-05 11:33:15 +00004457
drh308c2a52010-05-14 11:30:18 +00004458 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004459 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004460 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004461 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004462 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4463 pNew->ctrlFlags = UNIXFILE_EXCL;
4464 }else{
4465 pNew->ctrlFlags = 0;
4466 }
drh77197112011-03-15 19:08:48 +00004467 if( isReadOnly ){
4468 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4469 }
drh339eb0b2008-03-07 15:34:11 +00004470
drh6c7d5c52008-11-21 20:32:33 +00004471#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004472 pNew->pId = vxworksFindFileId(zFilename);
4473 if( pNew->pId==0 ){
4474 noLock = 1;
4475 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004476 }
4477#endif
4478
drhda0e7682008-07-30 15:27:54 +00004479 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004480 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004481 }else{
drh0c2694b2009-09-03 16:23:44 +00004482 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004483#if SQLITE_ENABLE_LOCKING_STYLE
4484 /* Cache zFilename in the locking context (AFP and dotlock override) for
4485 ** proxyLock activation is possible (remote proxy is based on db name)
4486 ** zFilename remains valid until file is closed, to support */
4487 pNew->lockingContext = (void*)zFilename;
4488#endif
drhda0e7682008-07-30 15:27:54 +00004489 }
danielk1977e339d652008-06-28 11:23:00 +00004490
drh7ed97b92010-01-20 13:07:21 +00004491 if( pLockingStyle == &posixIoMethods
4492#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4493 || pLockingStyle == &nfsIoMethods
4494#endif
4495 ){
drh7708e972008-11-29 00:56:52 +00004496 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004497 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004498 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004499 /* If an error occured in findInodeInfo(), close the file descriptor
4500 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004501 ** in two scenarios:
4502 **
4503 ** (a) A call to fstat() failed.
4504 ** (b) A malloc failed.
4505 **
4506 ** Scenario (b) may only occur if the process is holding no other
4507 ** file descriptors open on the same file. If there were other file
4508 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004509 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004510 ** handle h - as it is guaranteed that no posix locks will be released
4511 ** by doing so.
4512 **
4513 ** If scenario (a) caused the error then things are not so safe. The
4514 ** implicit assumption here is that if fstat() fails, things are in
4515 ** such bad shape that dropping a lock or two doesn't matter much.
4516 */
drh0e9365c2011-03-02 02:08:13 +00004517 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004518 h = -1;
4519 }
drh7708e972008-11-29 00:56:52 +00004520 unixLeaveMutex();
4521 }
danielk1977e339d652008-06-28 11:23:00 +00004522
drhd2cb50b2009-01-09 21:41:17 +00004523#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004524 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004525 /* AFP locking uses the file path so it needs to be included in
4526 ** the afpLockingContext.
4527 */
4528 afpLockingContext *pCtx;
4529 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4530 if( pCtx==0 ){
4531 rc = SQLITE_NOMEM;
4532 }else{
4533 /* NB: zFilename exists and remains valid until the file is closed
4534 ** according to requirement F11141. So we do not need to make a
4535 ** copy of the filename. */
4536 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004537 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004538 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004539 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004540 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004541 if( rc!=SQLITE_OK ){
4542 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004543 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004544 h = -1;
4545 }
drh7708e972008-11-29 00:56:52 +00004546 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004547 }
drh7708e972008-11-29 00:56:52 +00004548 }
4549#endif
danielk1977e339d652008-06-28 11:23:00 +00004550
drh7708e972008-11-29 00:56:52 +00004551 else if( pLockingStyle == &dotlockIoMethods ){
4552 /* Dotfile locking uses the file path so it needs to be included in
4553 ** the dotlockLockingContext
4554 */
4555 char *zLockFile;
4556 int nFilename;
drhea678832008-12-10 19:26:22 +00004557 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004558 zLockFile = (char *)sqlite3_malloc(nFilename);
4559 if( zLockFile==0 ){
4560 rc = SQLITE_NOMEM;
4561 }else{
4562 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004563 }
drh7708e972008-11-29 00:56:52 +00004564 pNew->lockingContext = zLockFile;
4565 }
danielk1977e339d652008-06-28 11:23:00 +00004566
drh6c7d5c52008-11-21 20:32:33 +00004567#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004568 else if( pLockingStyle == &semIoMethods ){
4569 /* Named semaphore locking uses the file path so it needs to be
4570 ** included in the semLockingContext
4571 */
4572 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004573 rc = findInodeInfo(pNew, &pNew->pInode);
4574 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4575 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004576 int n;
drh2238dcc2009-08-27 17:56:20 +00004577 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004578 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004579 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004580 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004581 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4582 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004583 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004584 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004585 }
chw97185482008-11-17 08:05:31 +00004586 }
drh7708e972008-11-29 00:56:52 +00004587 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004588 }
drh7708e972008-11-29 00:56:52 +00004589#endif
aswift5b1a2562008-08-22 00:22:35 +00004590
4591 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004592#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004593 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004594 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004595 h = -1;
chw97185482008-11-17 08:05:31 +00004596 unlink(zFilename);
4597 isDelete = 0;
4598 }
4599 pNew->isDelete = isDelete;
4600#endif
danielk1977e339d652008-06-28 11:23:00 +00004601 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004602 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4603 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004604 }else{
drh7708e972008-11-29 00:56:52 +00004605 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004606 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004607 }
danielk1977e339d652008-06-28 11:23:00 +00004608 return rc;
drh054889e2005-11-30 03:20:31 +00004609}
drh9c06c952005-11-26 00:25:00 +00004610
danielk1977ad94b582007-08-20 06:44:22 +00004611/*
4612** Open a file descriptor to the directory containing file zFilename.
4613** If successful, *pFd is set to the opened file descriptor and
4614** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4615** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4616** value.
4617**
4618** If SQLITE_OK is returned, the caller is responsible for closing
4619** the file descriptor *pFd using close().
4620*/
danielk1977fee2d252007-08-18 10:59:19 +00004621static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004622 int ii;
drh777b17a2007-09-20 10:02:54 +00004623 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004624 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004625
drh153c62c2007-08-24 03:51:33 +00004626 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004627 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004628 if( ii>0 ){
4629 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004630 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004631 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004632#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004633 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004634#endif
drh308c2a52010-05-14 11:30:18 +00004635 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004636 }
4637 }
danielk1977fee2d252007-08-18 10:59:19 +00004638 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004639 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004640}
4641
danielk1977b4b47412007-08-17 15:53:36 +00004642/*
drh8b3cf822010-06-01 21:02:51 +00004643** Return the name of a directory in which to put temporary files.
4644** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004645*/
drh7234c6d2010-06-19 15:10:09 +00004646static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004647 static const char *azDirs[] = {
4648 0,
aswiftaebf4132008-11-21 00:10:35 +00004649 0,
danielk197717b90b52008-06-06 11:11:25 +00004650 "/var/tmp",
4651 "/usr/tmp",
4652 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004653 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004654 };
drh8b3cf822010-06-01 21:02:51 +00004655 unsigned int i;
4656 struct stat buf;
4657 const char *zDir = 0;
4658
4659 azDirs[0] = sqlite3_temp_directory;
4660 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004661 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004662 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004663 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004664 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004665 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004666 break;
4667 }
4668 return zDir;
4669}
4670
4671/*
4672** Create a temporary file name in zBuf. zBuf must be allocated
4673** by the calling process and must be big enough to hold at least
4674** pVfs->mxPathname bytes.
4675*/
4676static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004677 static const unsigned char zChars[] =
4678 "abcdefghijklmnopqrstuvwxyz"
4679 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4680 "0123456789";
drh41022642008-11-21 00:24:42 +00004681 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004682 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004683
4684 /* It's odd to simulate an io-error here, but really this is just
4685 ** using the io-error infrastructure to test that SQLite handles this
4686 ** function failing.
4687 */
4688 SimulateIOError( return SQLITE_IOERR );
4689
drh7234c6d2010-06-19 15:10:09 +00004690 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004691 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004692
4693 /* Check that the output buffer is large enough for the temporary file
4694 ** name. If it is not, return SQLITE_ERROR.
4695 */
danielk197700e13612008-11-17 19:18:54 +00004696 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004697 return SQLITE_ERROR;
4698 }
4699
4700 do{
4701 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004702 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004703 sqlite3_randomness(15, &zBuf[j]);
4704 for(i=0; i<15; i++, j++){
4705 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4706 }
4707 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004708 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004709 return SQLITE_OK;
4710}
4711
drhd2cb50b2009-01-09 21:41:17 +00004712#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004713/*
4714** Routine to transform a unixFile into a proxy-locking unixFile.
4715** Implementation in the proxy-lock division, but used by unixOpen()
4716** if SQLITE_PREFER_PROXY_LOCKING is defined.
4717*/
4718static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004719#endif
drhc66d5b62008-12-03 22:48:32 +00004720
dan08da86a2009-08-21 17:18:03 +00004721/*
4722** Search for an unused file descriptor that was opened on the database
4723** file (not a journal or master-journal file) identified by pathname
4724** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4725** argument to this function.
4726**
4727** Such a file descriptor may exist if a database connection was closed
4728** but the associated file descriptor could not be closed because some
4729** other file descriptor open on the same file is holding a file-lock.
4730** Refer to comments in the unixClose() function and the lengthy comment
4731** describing "Posix Advisory Locking" at the start of this file for
4732** further details. Also, ticket #4018.
4733**
4734** If a suitable file descriptor is found, then it is returned. If no
4735** such file descriptor is located, -1 is returned.
4736*/
dane946c392009-08-22 11:39:46 +00004737static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4738 UnixUnusedFd *pUnused = 0;
4739
4740 /* Do not search for an unused file descriptor on vxworks. Not because
4741 ** vxworks would not benefit from the change (it might, we're not sure),
4742 ** but because no way to test it is currently available. It is better
4743 ** not to risk breaking vxworks support for the sake of such an obscure
4744 ** feature. */
4745#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004746 struct stat sStat; /* Results of stat() call */
4747
4748 /* A stat() call may fail for various reasons. If this happens, it is
4749 ** almost certain that an open() call on the same path will also fail.
4750 ** For this reason, if an error occurs in the stat() call here, it is
4751 ** ignored and -1 is returned. The caller will try to open a new file
4752 ** descriptor on the same path, fail, and return an error to SQLite.
4753 **
4754 ** Even if a subsequent open() call does succeed, the consequences of
4755 ** not searching for a resusable file descriptor are not dire. */
4756 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004757 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004758
4759 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004760 pInode = inodeList;
4761 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4762 || pInode->fileId.ino!=sStat.st_ino) ){
4763 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004764 }
drh8af6c222010-05-14 12:43:01 +00004765 if( pInode ){
dane946c392009-08-22 11:39:46 +00004766 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004767 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004768 pUnused = *pp;
4769 if( pUnused ){
4770 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004771 }
4772 }
4773 unixLeaveMutex();
4774 }
dane946c392009-08-22 11:39:46 +00004775#endif /* if !OS_VXWORKS */
4776 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004777}
danielk197717b90b52008-06-06 11:11:25 +00004778
4779/*
danddb0ac42010-07-14 14:48:58 +00004780** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004781** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004782** and a value suitable for passing as the third argument to open(2) is
4783** written to *pMode. If an IO error occurs, an SQLite error code is
4784** returned and the value of *pMode is not modified.
4785**
4786** If the file being opened is a temporary file, it is always created with
4787** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004788** is a database or master journal file, it is created with the permissions
4789** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004790**
drh8ab58662010-07-15 18:38:39 +00004791** Finally, if the file being opened is a WAL or regular journal file, then
4792** this function queries the file-system for the permissions on the
4793** corresponding database file and sets *pMode to this value. Whenever
4794** possible, WAL and journal files are created using the same permissions
4795** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004796*/
4797static int findCreateFileMode(
4798 const char *zPath, /* Path of file (possibly) being created */
4799 int flags, /* Flags passed as 4th argument to xOpen() */
4800 mode_t *pMode /* OUT: Permissions to open file with */
4801){
4802 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004803 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004804 char zDb[MAX_PATHNAME+1]; /* Database file path */
4805 int nDb; /* Number of valid bytes in zDb */
4806 struct stat sStat; /* Output of stat() on database file */
4807
dana0c989d2010-11-05 18:07:37 +00004808 /* zPath is a path to a WAL or journal file. The following block derives
4809 ** the path to the associated database file from zPath. This block handles
4810 ** the following naming conventions:
4811 **
4812 ** "<path to db>-journal"
4813 ** "<path to db>-wal"
4814 ** "<path to db>-journal-NNNN"
4815 ** "<path to db>-wal-NNNN"
4816 **
4817 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4818 ** used by the test_multiplex.c module.
4819 */
4820 nDb = sqlite3Strlen30(zPath) - 1;
4821 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4822 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004823 memcpy(zDb, zPath, nDb);
4824 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004825
danddb0ac42010-07-14 14:48:58 +00004826 if( 0==stat(zDb, &sStat) ){
4827 *pMode = sStat.st_mode & 0777;
4828 }else{
4829 rc = SQLITE_IOERR_FSTAT;
4830 }
4831 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4832 *pMode = 0600;
4833 }else{
4834 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4835 }
4836 return rc;
4837}
4838
4839/*
danielk1977ad94b582007-08-20 06:44:22 +00004840** Open the file zPath.
4841**
danielk1977b4b47412007-08-17 15:53:36 +00004842** Previously, the SQLite OS layer used three functions in place of this
4843** one:
4844**
4845** sqlite3OsOpenReadWrite();
4846** sqlite3OsOpenReadOnly();
4847** sqlite3OsOpenExclusive();
4848**
4849** These calls correspond to the following combinations of flags:
4850**
4851** ReadWrite() -> (READWRITE | CREATE)
4852** ReadOnly() -> (READONLY)
4853** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4854**
4855** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4856** true, the file was configured to be automatically deleted when the
4857** file handle closed. To achieve the same effect using this new
4858** interface, add the DELETEONCLOSE flag to those specified above for
4859** OpenExclusive().
4860*/
4861static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004862 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4863 const char *zPath, /* Pathname of file to be opened */
4864 sqlite3_file *pFile, /* The file descriptor to be filled in */
4865 int flags, /* Input flags to control the opening */
4866 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004867){
dan08da86a2009-08-21 17:18:03 +00004868 unixFile *p = (unixFile *)pFile;
4869 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004870 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004871 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004872 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004873 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004874 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004875
4876 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4877 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4878 int isCreate = (flags & SQLITE_OPEN_CREATE);
4879 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4880 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004881#if SQLITE_ENABLE_LOCKING_STYLE
4882 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4883#endif
danielk1977b4b47412007-08-17 15:53:36 +00004884
danielk1977fee2d252007-08-18 10:59:19 +00004885 /* If creating a master or main-file journal, this function will open
4886 ** a file-descriptor on the directory too. The first time unixSync()
4887 ** is called the directory file descriptor will be fsync()ed and close()d.
4888 */
danddb0ac42010-07-14 14:48:58 +00004889 int isOpenDirectory = (isCreate && (
4890 eType==SQLITE_OPEN_MASTER_JOURNAL
4891 || eType==SQLITE_OPEN_MAIN_JOURNAL
4892 || eType==SQLITE_OPEN_WAL
4893 ));
danielk1977fee2d252007-08-18 10:59:19 +00004894
danielk197717b90b52008-06-06 11:11:25 +00004895 /* If argument zPath is a NULL pointer, this function is required to open
4896 ** a temporary file. Use this buffer to store the file name in.
4897 */
4898 char zTmpname[MAX_PATHNAME+1];
4899 const char *zName = zPath;
4900
danielk1977fee2d252007-08-18 10:59:19 +00004901 /* Check the following statements are true:
4902 **
4903 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4904 ** (b) if CREATE is set, then READWRITE must also be set, and
4905 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004906 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004907 */
danielk1977b4b47412007-08-17 15:53:36 +00004908 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004909 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004910 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004911 assert(isDelete==0 || isCreate);
4912
danddb0ac42010-07-14 14:48:58 +00004913 /* The main DB, main journal, WAL file and master journal are never
4914 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004915 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4916 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4917 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004918 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004919
danielk1977fee2d252007-08-18 10:59:19 +00004920 /* Assert that the upper layer has set one of the "file-type" flags. */
4921 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4922 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4923 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004924 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004925 );
4926
dan08da86a2009-08-21 17:18:03 +00004927 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004928
dan08da86a2009-08-21 17:18:03 +00004929 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004930 UnixUnusedFd *pUnused;
4931 pUnused = findReusableFd(zName, flags);
4932 if( pUnused ){
4933 fd = pUnused->fd;
4934 }else{
dan6aa657f2009-08-24 18:57:58 +00004935 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004936 if( !pUnused ){
4937 return SQLITE_NOMEM;
4938 }
4939 }
4940 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004941 }else if( !zName ){
4942 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004943 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004944 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004945 if( rc!=SQLITE_OK ){
4946 return rc;
4947 }
4948 zName = zTmpname;
4949 }
4950
dan08da86a2009-08-21 17:18:03 +00004951 /* Determine the value of the flags parameter passed to POSIX function
4952 ** open(). These must be calculated even if open() is not called, as
4953 ** they may be stored as part of the file handle and used by the
4954 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004955 if( isReadonly ) openFlags |= O_RDONLY;
4956 if( isReadWrite ) openFlags |= O_RDWR;
4957 if( isCreate ) openFlags |= O_CREAT;
4958 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4959 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004960
danielk1977b4b47412007-08-17 15:53:36 +00004961 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004962 mode_t openMode; /* Permissions to create file with */
4963 rc = findCreateFileMode(zName, flags, &openMode);
4964 if( rc!=SQLITE_OK ){
4965 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004966 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004967 return rc;
4968 }
drhad4f1e52011-03-04 15:43:57 +00004969 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004970 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004971 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4972 /* Failed to open the file for read/write access. Try read-only. */
4973 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004974 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004975 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004976 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00004977 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00004978 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004979 }
4980 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004981 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004982 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004983 }
danielk1977b4b47412007-08-17 15:53:36 +00004984 }
dan08da86a2009-08-21 17:18:03 +00004985 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004986 if( pOutFlags ){
4987 *pOutFlags = flags;
4988 }
4989
dane946c392009-08-22 11:39:46 +00004990 if( p->pUnused ){
4991 p->pUnused->fd = fd;
4992 p->pUnused->flags = flags;
4993 }
4994
danielk1977b4b47412007-08-17 15:53:36 +00004995 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004996#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004997 zPath = zName;
4998#else
danielk197717b90b52008-06-06 11:11:25 +00004999 unlink(zName);
chw97185482008-11-17 08:05:31 +00005000#endif
danielk1977b4b47412007-08-17 15:53:36 +00005001 }
drh41022642008-11-21 00:24:42 +00005002#if SQLITE_ENABLE_LOCKING_STYLE
5003 else{
dan08da86a2009-08-21 17:18:03 +00005004 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005005 }
5006#endif
5007
danielk1977fee2d252007-08-18 10:59:19 +00005008 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005009 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005010 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005011 /* It is safe to close fd at this point, because it is guaranteed not
5012 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005013 ** it would not be safe to close as this would release any locks held
5014 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005015 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005016 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005017 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005018 }
5019 }
danielk1977e339d652008-06-28 11:23:00 +00005020
5021#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005022 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005023#endif
5024
drhda0e7682008-07-30 15:27:54 +00005025 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005026
drh7ed97b92010-01-20 13:07:21 +00005027
5028#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5029 struct statfs fsInfo;
5030 if( fstatfs(fd, &fsInfo) == -1 ){
5031 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005032 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5033 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005034 return SQLITE_IOERR_ACCESS;
5035 }
5036 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5037 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5038 }
5039#endif
5040
5041#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005042#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005043 isAutoProxy = 1;
5044#endif
5045 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005046 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5047 int useProxy = 0;
5048
dan08da86a2009-08-21 17:18:03 +00005049 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5050 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005051 if( envforce!=NULL ){
5052 useProxy = atoi(envforce)>0;
5053 }else{
5054 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005055 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005056 /* In theory, the close(fd) call is sub-optimal. If the file opened
5057 ** with fd is a database file, and there are other connections open
5058 ** on that file that are currently holding advisory locks on it,
5059 ** then the call to close() will cancel those locks. In practice,
5060 ** we're assuming that statfs() doesn't fail very often. At least
5061 ** not while other file descriptors opened by the same process on
5062 ** the same file are working. */
5063 p->lastErrno = errno;
5064 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005065 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005066 }
drh0e9365c2011-03-02 02:08:13 +00005067 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005068 rc = SQLITE_IOERR_ACCESS;
5069 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005070 }
5071 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5072 }
5073 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005074 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5075 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005076 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005077 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005078 if( rc!=SQLITE_OK ){
5079 /* Use unixClose to clean up the resources added in fillInUnixFile
5080 ** and clear all the structure's references. Specifically,
5081 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5082 */
5083 unixClose(pFile);
5084 return rc;
5085 }
aswiftaebf4132008-11-21 00:10:35 +00005086 }
dane946c392009-08-22 11:39:46 +00005087 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005088 }
5089 }
5090#endif
5091
drh77197112011-03-15 19:08:48 +00005092 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5093 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005094open_finished:
5095 if( rc!=SQLITE_OK ){
5096 sqlite3_free(p->pUnused);
5097 }
5098 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005099}
5100
dane946c392009-08-22 11:39:46 +00005101
danielk1977b4b47412007-08-17 15:53:36 +00005102/*
danielk1977fee2d252007-08-18 10:59:19 +00005103** Delete the file at zPath. If the dirSync argument is true, fsync()
5104** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005105*/
drh6b9d6dd2008-12-03 19:34:47 +00005106static int unixDelete(
5107 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5108 const char *zPath, /* Name of file to be deleted */
5109 int dirSync /* If true, fsync() directory after deleting file */
5110){
danielk1977fee2d252007-08-18 10:59:19 +00005111 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005112 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005113 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005114 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005115 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005116 }
danielk1977d39fa702008-10-16 13:27:40 +00005117#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005118 if( dirSync ){
5119 int fd;
5120 rc = openDirectory(zPath, &fd);
5121 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005122#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005123 if( fsync(fd)==-1 )
5124#else
5125 if( fsync(fd) )
5126#endif
5127 {
dane18d4952011-02-21 11:46:24 +00005128 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005129 }
drh0e9365c2011-03-02 02:08:13 +00005130 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005131 }
5132 }
danielk1977d138dd82008-10-15 16:02:48 +00005133#endif
danielk1977fee2d252007-08-18 10:59:19 +00005134 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005135}
5136
danielk197790949c22007-08-17 16:50:38 +00005137/*
5138** Test the existance of or access permissions of file zPath. The
5139** test performed depends on the value of flags:
5140**
5141** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5142** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5143** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5144**
5145** Otherwise return 0.
5146*/
danielk1977861f7452008-06-05 11:39:11 +00005147static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005148 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5149 const char *zPath, /* Path of the file to examine */
5150 int flags, /* What do we want to learn about the zPath file? */
5151 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005152){
rse25c0d1a2007-09-20 08:38:14 +00005153 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005154 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005155 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005156 switch( flags ){
5157 case SQLITE_ACCESS_EXISTS:
5158 amode = F_OK;
5159 break;
5160 case SQLITE_ACCESS_READWRITE:
5161 amode = W_OK|R_OK;
5162 break;
drh50d3f902007-08-27 21:10:36 +00005163 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005164 amode = R_OK;
5165 break;
5166
5167 default:
5168 assert(!"Invalid flags argument");
5169 }
drh99ab3b12011-03-02 15:09:07 +00005170 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005171 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5172 struct stat buf;
5173 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5174 *pResOut = 0;
5175 }
5176 }
danielk1977861f7452008-06-05 11:39:11 +00005177 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005178}
5179
danielk1977b4b47412007-08-17 15:53:36 +00005180
5181/*
5182** Turn a relative pathname into a full pathname. The relative path
5183** is stored as a nul-terminated string in the buffer pointed to by
5184** zPath.
5185**
5186** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5187** (in this case, MAX_PATHNAME bytes). The full-path is written to
5188** this buffer before returning.
5189*/
danielk1977adfb9b02007-09-17 07:02:56 +00005190static int unixFullPathname(
5191 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5192 const char *zPath, /* Possibly relative input path */
5193 int nOut, /* Size of output buffer in bytes */
5194 char *zOut /* Output buffer */
5195){
danielk1977843e65f2007-09-01 16:16:15 +00005196
5197 /* It's odd to simulate an io-error here, but really this is just
5198 ** using the io-error infrastructure to test that SQLite handles this
5199 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005200 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005201 */
5202 SimulateIOError( return SQLITE_ERROR );
5203
drh153c62c2007-08-24 03:51:33 +00005204 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005205 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005206
drh3c7f2dc2007-12-06 13:26:20 +00005207 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005208 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005209 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005210 }else{
5211 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005212 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005213 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005214 }
drhea678832008-12-10 19:26:22 +00005215 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005216 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005217 }
5218 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005219}
5220
drh0ccebe72005-06-07 22:22:50 +00005221
drh761df872006-12-21 01:29:22 +00005222#ifndef SQLITE_OMIT_LOAD_EXTENSION
5223/*
5224** Interfaces for opening a shared library, finding entry points
5225** within the shared library, and closing the shared library.
5226*/
5227#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005228static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5229 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005230 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5231}
danielk197795c8a542007-09-01 06:51:27 +00005232
5233/*
5234** SQLite calls this function immediately after a call to unixDlSym() or
5235** unixDlOpen() fails (returns a null pointer). If a more detailed error
5236** message is available, it is written to zBufOut. If no error message
5237** is available, zBufOut is left unmodified and SQLite uses a default
5238** error message.
5239*/
danielk1977397d65f2008-11-19 11:35:39 +00005240static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005241 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005242 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005243 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005244 zErr = dlerror();
5245 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005246 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005247 }
drh6c7d5c52008-11-21 20:32:33 +00005248 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005249}
drh1875f7a2008-12-08 18:19:17 +00005250static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5251 /*
5252 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5253 ** cast into a pointer to a function. And yet the library dlsym() routine
5254 ** returns a void* which is really a pointer to a function. So how do we
5255 ** use dlsym() with -pedantic-errors?
5256 **
5257 ** Variable x below is defined to be a pointer to a function taking
5258 ** parameters void* and const char* and returning a pointer to a function.
5259 ** We initialize x by assigning it a pointer to the dlsym() function.
5260 ** (That assignment requires a cast.) Then we call the function that
5261 ** x points to.
5262 **
5263 ** This work-around is unlikely to work correctly on any system where
5264 ** you really cannot cast a function pointer into void*. But then, on the
5265 ** other hand, dlsym() will not work on such a system either, so we have
5266 ** not really lost anything.
5267 */
5268 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005269 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005270 x = (void(*(*)(void*,const char*))(void))dlsym;
5271 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005272}
danielk1977397d65f2008-11-19 11:35:39 +00005273static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5274 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005275 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005276}
danielk1977b4b47412007-08-17 15:53:36 +00005277#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5278 #define unixDlOpen 0
5279 #define unixDlError 0
5280 #define unixDlSym 0
5281 #define unixDlClose 0
5282#endif
5283
5284/*
danielk197790949c22007-08-17 16:50:38 +00005285** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005286*/
danielk1977397d65f2008-11-19 11:35:39 +00005287static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5288 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005289 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005290
drhbbd42a62004-05-22 17:41:58 +00005291 /* We have to initialize zBuf to prevent valgrind from reporting
5292 ** errors. The reports issued by valgrind are incorrect - we would
5293 ** prefer that the randomness be increased by making use of the
5294 ** uninitialized space in zBuf - but valgrind errors tend to worry
5295 ** some users. Rather than argue, it seems easier just to initialize
5296 ** the whole array and silence valgrind, even if that means less randomness
5297 ** in the random seed.
5298 **
5299 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005300 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005301 ** tests repeatable.
5302 */
danielk1977b4b47412007-08-17 15:53:36 +00005303 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005304#if !defined(SQLITE_TEST)
5305 {
drh842b8642005-01-21 17:53:17 +00005306 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005307 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005308 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005309 time_t t;
5310 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005311 memcpy(zBuf, &t, sizeof(t));
5312 pid = getpid();
5313 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005314 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005315 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005316 }else{
drhe562be52011-03-02 18:01:10 +00005317 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005318 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005319 }
drhbbd42a62004-05-22 17:41:58 +00005320 }
5321#endif
drh72cbd072008-10-14 17:58:38 +00005322 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005323}
5324
danielk1977b4b47412007-08-17 15:53:36 +00005325
drhbbd42a62004-05-22 17:41:58 +00005326/*
5327** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005328** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005329** The return value is the number of microseconds of sleep actually
5330** requested from the underlying operating system, a number which
5331** might be greater than or equal to the argument, but not less
5332** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005333*/
danielk1977397d65f2008-11-19 11:35:39 +00005334static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005335#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005336 struct timespec sp;
5337
5338 sp.tv_sec = microseconds / 1000000;
5339 sp.tv_nsec = (microseconds % 1000000) * 1000;
5340 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005341 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005342 return microseconds;
5343#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005344 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005345 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005346 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005347#else
danielk1977b4b47412007-08-17 15:53:36 +00005348 int seconds = (microseconds+999999)/1000000;
5349 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005350 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005351 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005352#endif
drh88f474a2006-01-02 20:00:12 +00005353}
5354
5355/*
drh6b9d6dd2008-12-03 19:34:47 +00005356** The following variable, if set to a non-zero value, is interpreted as
5357** the number of seconds since 1970 and is used to set the result of
5358** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005359*/
5360#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005361int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005362#endif
5363
5364/*
drhb7e8ea22010-05-03 14:32:30 +00005365** Find the current time (in Universal Coordinated Time). Write into *piNow
5366** the current time and date as a Julian Day number times 86_400_000. In
5367** other words, write into *piNow the number of milliseconds since the Julian
5368** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5369** proleptic Gregorian calendar.
5370**
5371** On success, return 0. Return 1 if the time and date cannot be found.
5372*/
5373static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5374 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5375#if defined(NO_GETTOD)
5376 time_t t;
5377 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005378 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005379#elif OS_VXWORKS
5380 struct timespec sNow;
5381 clock_gettime(CLOCK_REALTIME, &sNow);
5382 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5383#else
5384 struct timeval sNow;
5385 gettimeofday(&sNow, 0);
5386 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5387#endif
5388
5389#ifdef SQLITE_TEST
5390 if( sqlite3_current_time ){
5391 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5392 }
5393#endif
5394 UNUSED_PARAMETER(NotUsed);
5395 return 0;
5396}
5397
5398/*
drhbbd42a62004-05-22 17:41:58 +00005399** Find the current time (in Universal Coordinated Time). Write the
5400** current time and date as a Julian Day number into *prNow and
5401** return 0. Return 1 if the time and date cannot be found.
5402*/
danielk1977397d65f2008-11-19 11:35:39 +00005403static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005404 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005405 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005406 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005407 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005408 return 0;
5409}
danielk1977b4b47412007-08-17 15:53:36 +00005410
drh6b9d6dd2008-12-03 19:34:47 +00005411/*
5412** We added the xGetLastError() method with the intention of providing
5413** better low-level error messages when operating-system problems come up
5414** during SQLite operation. But so far, none of that has been implemented
5415** in the core. So this routine is never called. For now, it is merely
5416** a place-holder.
5417*/
danielk1977397d65f2008-11-19 11:35:39 +00005418static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5419 UNUSED_PARAMETER(NotUsed);
5420 UNUSED_PARAMETER(NotUsed2);
5421 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005422 return 0;
5423}
5424
drhf2424c52010-04-26 00:04:55 +00005425
5426/*
drh734c9862008-11-28 15:37:20 +00005427************************ End of sqlite3_vfs methods ***************************
5428******************************************************************************/
5429
drh715ff302008-12-03 22:32:44 +00005430/******************************************************************************
5431************************** Begin Proxy Locking ********************************
5432**
5433** Proxy locking is a "uber-locking-method" in this sense: It uses the
5434** other locking methods on secondary lock files. Proxy locking is a
5435** meta-layer over top of the primitive locking implemented above. For
5436** this reason, the division that implements of proxy locking is deferred
5437** until late in the file (here) after all of the other I/O methods have
5438** been defined - so that the primitive locking methods are available
5439** as services to help with the implementation of proxy locking.
5440**
5441****
5442**
5443** The default locking schemes in SQLite use byte-range locks on the
5444** database file to coordinate safe, concurrent access by multiple readers
5445** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5446** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5447** as POSIX read & write locks over fixed set of locations (via fsctl),
5448** on AFP and SMB only exclusive byte-range locks are available via fsctl
5449** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5450** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5451** address in the shared range is taken for a SHARED lock, the entire
5452** shared range is taken for an EXCLUSIVE lock):
5453**
5454** PENDING_BYTE 0x40000000
5455** RESERVED_BYTE 0x40000001
5456** SHARED_RANGE 0x40000002 -> 0x40000200
5457**
5458** This works well on the local file system, but shows a nearly 100x
5459** slowdown in read performance on AFP because the AFP client disables
5460** the read cache when byte-range locks are present. Enabling the read
5461** cache exposes a cache coherency problem that is present on all OS X
5462** supported network file systems. NFS and AFP both observe the
5463** close-to-open semantics for ensuring cache coherency
5464** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5465** address the requirements for concurrent database access by multiple
5466** readers and writers
5467** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5468**
5469** To address the performance and cache coherency issues, proxy file locking
5470** changes the way database access is controlled by limiting access to a
5471** single host at a time and moving file locks off of the database file
5472** and onto a proxy file on the local file system.
5473**
5474**
5475** Using proxy locks
5476** -----------------
5477**
5478** C APIs
5479**
5480** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5481** <proxy_path> | ":auto:");
5482** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5483**
5484**
5485** SQL pragmas
5486**
5487** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5488** PRAGMA [database.]lock_proxy_file
5489**
5490** Specifying ":auto:" means that if there is a conch file with a matching
5491** host ID in it, the proxy path in the conch file will be used, otherwise
5492** a proxy path based on the user's temp dir
5493** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5494** actual proxy file name is generated from the name and path of the
5495** database file. For example:
5496**
5497** For database path "/Users/me/foo.db"
5498** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5499**
5500** Once a lock proxy is configured for a database connection, it can not
5501** be removed, however it may be switched to a different proxy path via
5502** the above APIs (assuming the conch file is not being held by another
5503** connection or process).
5504**
5505**
5506** How proxy locking works
5507** -----------------------
5508**
5509** Proxy file locking relies primarily on two new supporting files:
5510**
5511** * conch file to limit access to the database file to a single host
5512** at a time
5513**
5514** * proxy file to act as a proxy for the advisory locks normally
5515** taken on the database
5516**
5517** The conch file - to use a proxy file, sqlite must first "hold the conch"
5518** by taking an sqlite-style shared lock on the conch file, reading the
5519** contents and comparing the host's unique host ID (see below) and lock
5520** proxy path against the values stored in the conch. The conch file is
5521** stored in the same directory as the database file and the file name
5522** is patterned after the database file name as ".<databasename>-conch".
5523** If the conch file does not exist, or it's contents do not match the
5524** host ID and/or proxy path, then the lock is escalated to an exclusive
5525** lock and the conch file contents is updated with the host ID and proxy
5526** path and the lock is downgraded to a shared lock again. If the conch
5527** is held by another process (with a shared lock), the exclusive lock
5528** will fail and SQLITE_BUSY is returned.
5529**
5530** The proxy file - a single-byte file used for all advisory file locks
5531** normally taken on the database file. This allows for safe sharing
5532** of the database file for multiple readers and writers on the same
5533** host (the conch ensures that they all use the same local lock file).
5534**
drh715ff302008-12-03 22:32:44 +00005535** Requesting the lock proxy does not immediately take the conch, it is
5536** only taken when the first request to lock database file is made.
5537** This matches the semantics of the traditional locking behavior, where
5538** opening a connection to a database file does not take a lock on it.
5539** The shared lock and an open file descriptor are maintained until
5540** the connection to the database is closed.
5541**
5542** The proxy file and the lock file are never deleted so they only need
5543** to be created the first time they are used.
5544**
5545** Configuration options
5546** ---------------------
5547**
5548** SQLITE_PREFER_PROXY_LOCKING
5549**
5550** Database files accessed on non-local file systems are
5551** automatically configured for proxy locking, lock files are
5552** named automatically using the same logic as
5553** PRAGMA lock_proxy_file=":auto:"
5554**
5555** SQLITE_PROXY_DEBUG
5556**
5557** Enables the logging of error messages during host id file
5558** retrieval and creation
5559**
drh715ff302008-12-03 22:32:44 +00005560** LOCKPROXYDIR
5561**
5562** Overrides the default directory used for lock proxy files that
5563** are named automatically via the ":auto:" setting
5564**
5565** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5566**
5567** Permissions to use when creating a directory for storing the
5568** lock proxy files, only used when LOCKPROXYDIR is not set.
5569**
5570**
5571** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5572** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5573** force proxy locking to be used for every database file opened, and 0
5574** will force automatic proxy locking to be disabled for all database
5575** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5576** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5577*/
5578
5579/*
5580** Proxy locking is only available on MacOSX
5581*/
drhd2cb50b2009-01-09 21:41:17 +00005582#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005583
drh715ff302008-12-03 22:32:44 +00005584/*
5585** The proxyLockingContext has the path and file structures for the remote
5586** and local proxy files in it
5587*/
5588typedef struct proxyLockingContext proxyLockingContext;
5589struct proxyLockingContext {
5590 unixFile *conchFile; /* Open conch file */
5591 char *conchFilePath; /* Name of the conch file */
5592 unixFile *lockProxy; /* Open proxy lock file */
5593 char *lockProxyPath; /* Name of the proxy lock file */
5594 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005595 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005596 void *oldLockingContext; /* Original lockingcontext to restore on close */
5597 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5598};
5599
drh7ed97b92010-01-20 13:07:21 +00005600/*
5601** The proxy lock file path for the database at dbPath is written into lPath,
5602** which must point to valid, writable memory large enough for a maxLen length
5603** file path.
drh715ff302008-12-03 22:32:44 +00005604*/
drh715ff302008-12-03 22:32:44 +00005605static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5606 int len;
5607 int dbLen;
5608 int i;
5609
5610#ifdef LOCKPROXYDIR
5611 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5612#else
5613# ifdef _CS_DARWIN_USER_TEMP_DIR
5614 {
drh7ed97b92010-01-20 13:07:21 +00005615 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005616 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5617 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005618 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005619 }
drh7ed97b92010-01-20 13:07:21 +00005620 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005621 }
5622# else
5623 len = strlcpy(lPath, "/tmp/", maxLen);
5624# endif
5625#endif
5626
5627 if( lPath[len-1]!='/' ){
5628 len = strlcat(lPath, "/", maxLen);
5629 }
5630
5631 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005632 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005633 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005634 char c = dbPath[i];
5635 lPath[i+len] = (c=='/')?'_':c;
5636 }
5637 lPath[i+len]='\0';
5638 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005639 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005640 return SQLITE_OK;
5641}
5642
drh7ed97b92010-01-20 13:07:21 +00005643/*
5644 ** Creates the lock file and any missing directories in lockPath
5645 */
5646static int proxyCreateLockPath(const char *lockPath){
5647 int i, len;
5648 char buf[MAXPATHLEN];
5649 int start = 0;
5650
5651 assert(lockPath!=NULL);
5652 /* try to create all the intermediate directories */
5653 len = (int)strlen(lockPath);
5654 buf[0] = lockPath[0];
5655 for( i=1; i<len; i++ ){
5656 if( lockPath[i] == '/' && (i - start > 0) ){
5657 /* only mkdir if leaf dir != "." or "/" or ".." */
5658 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5659 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5660 buf[i]='\0';
5661 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5662 int err=errno;
5663 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005664 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005665 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005666 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005667 return err;
5668 }
5669 }
5670 }
5671 start=i+1;
5672 }
5673 buf[i] = lockPath[i];
5674 }
drh308c2a52010-05-14 11:30:18 +00005675 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005676 return 0;
5677}
5678
drh715ff302008-12-03 22:32:44 +00005679/*
5680** Create a new VFS file descriptor (stored in memory obtained from
5681** sqlite3_malloc) and open the file named "path" in the file descriptor.
5682**
5683** The caller is responsible not only for closing the file descriptor
5684** but also for freeing the memory associated with the file descriptor.
5685*/
drh7ed97b92010-01-20 13:07:21 +00005686static int proxyCreateUnixFile(
5687 const char *path, /* path for the new unixFile */
5688 unixFile **ppFile, /* unixFile created and returned by ref */
5689 int islockfile /* if non zero missing dirs will be created */
5690) {
5691 int fd = -1;
5692 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005693 unixFile *pNew;
5694 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005695 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005696 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005697 int terrno = 0;
5698 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005699
drh7ed97b92010-01-20 13:07:21 +00005700 /* 1. first try to open/create the file
5701 ** 2. if that fails, and this is a lock file (not-conch), try creating
5702 ** the parent directories and then try again.
5703 ** 3. if that fails, try to open the file read-only
5704 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5705 */
5706 pUnused = findReusableFd(path, openFlags);
5707 if( pUnused ){
5708 fd = pUnused->fd;
5709 }else{
5710 pUnused = sqlite3_malloc(sizeof(*pUnused));
5711 if( !pUnused ){
5712 return SQLITE_NOMEM;
5713 }
5714 }
5715 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005716 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005717 terrno = errno;
5718 if( fd<0 && errno==ENOENT && islockfile ){
5719 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005720 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005721 }
5722 }
5723 }
5724 if( fd<0 ){
5725 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005726 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005727 terrno = errno;
5728 }
5729 if( fd<0 ){
5730 if( islockfile ){
5731 return SQLITE_BUSY;
5732 }
5733 switch (terrno) {
5734 case EACCES:
5735 return SQLITE_PERM;
5736 case EIO:
5737 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5738 default:
drh9978c972010-02-23 17:36:32 +00005739 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005740 }
5741 }
5742
5743 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5744 if( pNew==NULL ){
5745 rc = SQLITE_NOMEM;
5746 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005747 }
5748 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005749 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005750 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005751 pUnused->fd = fd;
5752 pUnused->flags = openFlags;
5753 pNew->pUnused = pUnused;
5754
drh77197112011-03-15 19:08:48 +00005755 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005756 if( rc==SQLITE_OK ){
5757 *ppFile = pNew;
5758 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005759 }
drh7ed97b92010-01-20 13:07:21 +00005760end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005761 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005762 sqlite3_free(pNew);
5763 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005764 return rc;
5765}
5766
drh7ed97b92010-01-20 13:07:21 +00005767#ifdef SQLITE_TEST
5768/* simulate multiple hosts by creating unique hostid file paths */
5769int sqlite3_hostid_num = 0;
5770#endif
5771
5772#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5773
drh0ab216a2010-07-02 17:10:40 +00005774/* Not always defined in the headers as it ought to be */
5775extern int gethostuuid(uuid_t id, const struct timespec *wait);
5776
drh7ed97b92010-01-20 13:07:21 +00005777/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5778** bytes of writable memory.
5779*/
5780static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005781 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5782 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005783#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5784 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005785 {
5786 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5787 if( gethostuuid(pHostID, &timeout) ){
5788 int err = errno;
5789 if( pError ){
5790 *pError = err;
5791 }
5792 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005793 }
drh7ed97b92010-01-20 13:07:21 +00005794 }
drhe8b0c9b2010-09-25 14:13:17 +00005795#endif
drh7ed97b92010-01-20 13:07:21 +00005796#ifdef SQLITE_TEST
5797 /* simulate multiple hosts by creating unique hostid file paths */
5798 if( sqlite3_hostid_num != 0){
5799 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5800 }
5801#endif
5802
5803 return SQLITE_OK;
5804}
5805
5806/* The conch file contains the header, host id and lock file path
5807 */
5808#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5809#define PROXY_HEADERLEN 1 /* conch file header length */
5810#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5811#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5812
5813/*
5814** Takes an open conch file, copies the contents to a new path and then moves
5815** it back. The newly created file's file descriptor is assigned to the
5816** conch file structure and finally the original conch file descriptor is
5817** closed. Returns zero if successful.
5818*/
5819static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5820 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5821 unixFile *conchFile = pCtx->conchFile;
5822 char tPath[MAXPATHLEN];
5823 char buf[PROXY_MAXCONCHLEN];
5824 char *cPath = pCtx->conchFilePath;
5825 size_t readLen = 0;
5826 size_t pathLen = 0;
5827 char errmsg[64] = "";
5828 int fd = -1;
5829 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005830 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005831
5832 /* create a new path by replace the trailing '-conch' with '-break' */
5833 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5834 if( pathLen>MAXPATHLEN || pathLen<6 ||
5835 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005836 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005837 goto end_breaklock;
5838 }
5839 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005840 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005841 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005842 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005843 goto end_breaklock;
5844 }
5845 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005846 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5847 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005848 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005849 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005850 goto end_breaklock;
5851 }
drhe562be52011-03-02 18:01:10 +00005852 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005853 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005854 goto end_breaklock;
5855 }
5856 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005857 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005858 goto end_breaklock;
5859 }
5860 rc = 0;
5861 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005862 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005863 conchFile->h = fd;
5864 conchFile->openFlags = O_RDWR | O_CREAT;
5865
5866end_breaklock:
5867 if( rc ){
5868 if( fd>=0 ){
5869 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005870 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005871 }
5872 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5873 }
5874 return rc;
5875}
5876
5877/* Take the requested lock on the conch file and break a stale lock if the
5878** host id matches.
5879*/
5880static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5881 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5882 unixFile *conchFile = pCtx->conchFile;
5883 int rc = SQLITE_OK;
5884 int nTries = 0;
5885 struct timespec conchModTime;
5886
5887 do {
5888 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5889 nTries ++;
5890 if( rc==SQLITE_BUSY ){
5891 /* If the lock failed (busy):
5892 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5893 * 2nd try: fail if the mod time changed or host id is different, wait
5894 * 10 sec and try again
5895 * 3rd try: break the lock unless the mod time has changed.
5896 */
5897 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005898 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005899 pFile->lastErrno = errno;
5900 return SQLITE_IOERR_LOCK;
5901 }
5902
5903 if( nTries==1 ){
5904 conchModTime = buf.st_mtimespec;
5905 usleep(500000); /* wait 0.5 sec and try the lock again*/
5906 continue;
5907 }
5908
5909 assert( nTries>1 );
5910 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5911 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5912 return SQLITE_BUSY;
5913 }
5914
5915 if( nTries==2 ){
5916 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005917 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005918 if( len<0 ){
5919 pFile->lastErrno = errno;
5920 return SQLITE_IOERR_LOCK;
5921 }
5922 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5923 /* don't break the lock if the host id doesn't match */
5924 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5925 return SQLITE_BUSY;
5926 }
5927 }else{
5928 /* don't break the lock on short read or a version mismatch */
5929 return SQLITE_BUSY;
5930 }
5931 usleep(10000000); /* wait 10 sec and try the lock again */
5932 continue;
5933 }
5934
5935 assert( nTries==3 );
5936 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5937 rc = SQLITE_OK;
5938 if( lockType==EXCLUSIVE_LOCK ){
5939 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5940 }
5941 if( !rc ){
5942 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5943 }
5944 }
5945 }
5946 } while( rc==SQLITE_BUSY && nTries<3 );
5947
5948 return rc;
5949}
5950
5951/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005952** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5953** lockPath means that the lockPath in the conch file will be used if the
5954** host IDs match, or a new lock path will be generated automatically
5955** and written to the conch file.
5956*/
5957static int proxyTakeConch(unixFile *pFile){
5958 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5959
drh7ed97b92010-01-20 13:07:21 +00005960 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005961 return SQLITE_OK;
5962 }else{
5963 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005964 uuid_t myHostID;
5965 int pError = 0;
5966 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005967 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005968 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005969 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005970 int createConch = 0;
5971 int hostIdMatch = 0;
5972 int readLen = 0;
5973 int tryOldLockPath = 0;
5974 int forceNewLockPath = 0;
5975
drh308c2a52010-05-14 11:30:18 +00005976 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5977 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005978
drh7ed97b92010-01-20 13:07:21 +00005979 rc = proxyGetHostID(myHostID, &pError);
5980 if( (rc&0xff)==SQLITE_IOERR ){
5981 pFile->lastErrno = pError;
5982 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005983 }
drh7ed97b92010-01-20 13:07:21 +00005984 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005985 if( rc!=SQLITE_OK ){
5986 goto end_takeconch;
5987 }
drh7ed97b92010-01-20 13:07:21 +00005988 /* read the existing conch file */
5989 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5990 if( readLen<0 ){
5991 /* I/O error: lastErrno set by seekAndRead */
5992 pFile->lastErrno = conchFile->lastErrno;
5993 rc = SQLITE_IOERR_READ;
5994 goto end_takeconch;
5995 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5996 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5997 /* a short read or version format mismatch means we need to create a new
5998 ** conch file.
5999 */
6000 createConch = 1;
6001 }
6002 /* if the host id matches and the lock path already exists in the conch
6003 ** we'll try to use the path there, if we can't open that path, we'll
6004 ** retry with a new auto-generated path
6005 */
6006 do { /* in case we need to try again for an :auto: named lock file */
6007
6008 if( !createConch && !forceNewLockPath ){
6009 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6010 PROXY_HOSTIDLEN);
6011 /* if the conch has data compare the contents */
6012 if( !pCtx->lockProxyPath ){
6013 /* for auto-named local lock file, just check the host ID and we'll
6014 ** use the local lock file path that's already in there
6015 */
6016 if( hostIdMatch ){
6017 size_t pathLen = (readLen - PROXY_PATHINDEX);
6018
6019 if( pathLen>=MAXPATHLEN ){
6020 pathLen=MAXPATHLEN-1;
6021 }
6022 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6023 lockPath[pathLen] = 0;
6024 tempLockPath = lockPath;
6025 tryOldLockPath = 1;
6026 /* create a copy of the lock path if the conch is taken */
6027 goto end_takeconch;
6028 }
6029 }else if( hostIdMatch
6030 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6031 readLen-PROXY_PATHINDEX)
6032 ){
6033 /* conch host and lock path match */
6034 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006035 }
drh7ed97b92010-01-20 13:07:21 +00006036 }
6037
6038 /* if the conch isn't writable and doesn't match, we can't take it */
6039 if( (conchFile->openFlags&O_RDWR) == 0 ){
6040 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006041 goto end_takeconch;
6042 }
drh7ed97b92010-01-20 13:07:21 +00006043
6044 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006045 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006046 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6047 tempLockPath = lockPath;
6048 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006049 }
drh7ed97b92010-01-20 13:07:21 +00006050
6051 /* update conch with host and path (this will fail if other process
6052 ** has a shared lock already), if the host id matches, use the big
6053 ** stick.
drh715ff302008-12-03 22:32:44 +00006054 */
drh7ed97b92010-01-20 13:07:21 +00006055 futimes(conchFile->h, NULL);
6056 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006057 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006058 /* We are trying for an exclusive lock but another thread in this
6059 ** same process is still holding a shared lock. */
6060 rc = SQLITE_BUSY;
6061 } else {
6062 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006063 }
drh715ff302008-12-03 22:32:44 +00006064 }else{
drh7ed97b92010-01-20 13:07:21 +00006065 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006066 }
drh7ed97b92010-01-20 13:07:21 +00006067 if( rc==SQLITE_OK ){
6068 char writeBuffer[PROXY_MAXCONCHLEN];
6069 int writeSize = 0;
6070
6071 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6072 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6073 if( pCtx->lockProxyPath!=NULL ){
6074 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6075 }else{
6076 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6077 }
6078 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006079 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006080 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6081 fsync(conchFile->h);
6082 /* If we created a new conch file (not just updated the contents of a
6083 ** valid conch file), try to match the permissions of the database
6084 */
6085 if( rc==SQLITE_OK && createConch ){
6086 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006087 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006088 if( err==0 ){
6089 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6090 S_IROTH|S_IWOTH);
6091 /* try to match the database file R/W permissions, ignore failure */
6092#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006093 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006094#else
drhff812312011-02-23 13:33:46 +00006095 do{
drhe562be52011-03-02 18:01:10 +00006096 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006097 }while( rc==(-1) && errno==EINTR );
6098 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006099 int code = errno;
6100 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6101 cmode, code, strerror(code));
6102 } else {
6103 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6104 }
6105 }else{
6106 int code = errno;
6107 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6108 err, code, strerror(code));
6109#endif
6110 }
drh715ff302008-12-03 22:32:44 +00006111 }
6112 }
drh7ed97b92010-01-20 13:07:21 +00006113 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6114
6115 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006116 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006117 if( rc==SQLITE_OK && pFile->openFlags ){
6118 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006119 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006120 }
6121 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006122 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006123 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006124 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006125 if( fd>=0 ){
6126 pFile->h = fd;
6127 }else{
drh9978c972010-02-23 17:36:32 +00006128 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006129 during locking */
6130 }
6131 }
6132 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6133 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6134 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6135 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6136 /* we couldn't create the proxy lock file with the old lock file path
6137 ** so try again via auto-naming
6138 */
6139 forceNewLockPath = 1;
6140 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006141 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006142 }
6143 }
6144 if( rc==SQLITE_OK ){
6145 /* Need to make a copy of path if we extracted the value
6146 ** from the conch file or the path was allocated on the stack
6147 */
6148 if( tempLockPath ){
6149 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6150 if( !pCtx->lockProxyPath ){
6151 rc = SQLITE_NOMEM;
6152 }
6153 }
6154 }
6155 if( rc==SQLITE_OK ){
6156 pCtx->conchHeld = 1;
6157
6158 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6159 afpLockingContext *afpCtx;
6160 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6161 afpCtx->dbPath = pCtx->lockProxyPath;
6162 }
6163 } else {
6164 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6165 }
drh308c2a52010-05-14 11:30:18 +00006166 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6167 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006168 return rc;
drh308c2a52010-05-14 11:30:18 +00006169 } while (1); /* in case we need to retry the :auto: lock file -
6170 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006171 }
6172}
6173
6174/*
6175** If pFile holds a lock on a conch file, then release that lock.
6176*/
6177static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006178 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006179 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6180 unixFile *conchFile; /* Name of the conch file */
6181
6182 pCtx = (proxyLockingContext *)pFile->lockingContext;
6183 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006184 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006185 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006186 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006187 if( pCtx->conchHeld>0 ){
6188 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6189 }
drh715ff302008-12-03 22:32:44 +00006190 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006191 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6192 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006193 return rc;
6194}
6195
6196/*
6197** Given the name of a database file, compute the name of its conch file.
6198** Store the conch filename in memory obtained from sqlite3_malloc().
6199** Make *pConchPath point to the new name. Return SQLITE_OK on success
6200** or SQLITE_NOMEM if unable to obtain memory.
6201**
6202** The caller is responsible for ensuring that the allocated memory
6203** space is eventually freed.
6204**
6205** *pConchPath is set to NULL if a memory allocation error occurs.
6206*/
6207static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6208 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006209 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006210 char *conchPath; /* buffer in which to construct conch name */
6211
6212 /* Allocate space for the conch filename and initialize the name to
6213 ** the name of the original database file. */
6214 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6215 if( conchPath==0 ){
6216 return SQLITE_NOMEM;
6217 }
6218 memcpy(conchPath, dbPath, len+1);
6219
6220 /* now insert a "." before the last / character */
6221 for( i=(len-1); i>=0; i-- ){
6222 if( conchPath[i]=='/' ){
6223 i++;
6224 break;
6225 }
6226 }
6227 conchPath[i]='.';
6228 while ( i<len ){
6229 conchPath[i+1]=dbPath[i];
6230 i++;
6231 }
6232
6233 /* append the "-conch" suffix to the file */
6234 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006235 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006236
6237 return SQLITE_OK;
6238}
6239
6240
6241/* Takes a fully configured proxy locking-style unix file and switches
6242** the local lock file path
6243*/
6244static int switchLockProxyPath(unixFile *pFile, const char *path) {
6245 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6246 char *oldPath = pCtx->lockProxyPath;
6247 int rc = SQLITE_OK;
6248
drh308c2a52010-05-14 11:30:18 +00006249 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006250 return SQLITE_BUSY;
6251 }
6252
6253 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6254 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6255 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6256 return SQLITE_OK;
6257 }else{
6258 unixFile *lockProxy = pCtx->lockProxy;
6259 pCtx->lockProxy=NULL;
6260 pCtx->conchHeld = 0;
6261 if( lockProxy!=NULL ){
6262 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6263 if( rc ) return rc;
6264 sqlite3_free(lockProxy);
6265 }
6266 sqlite3_free(oldPath);
6267 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6268 }
6269
6270 return rc;
6271}
6272
6273/*
6274** pFile is a file that has been opened by a prior xOpen call. dbPath
6275** is a string buffer at least MAXPATHLEN+1 characters in size.
6276**
6277** This routine find the filename associated with pFile and writes it
6278** int dbPath.
6279*/
6280static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006281#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006282 if( pFile->pMethod == &afpIoMethods ){
6283 /* afp style keeps a reference to the db path in the filePath field
6284 ** of the struct */
drhea678832008-12-10 19:26:22 +00006285 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006286 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6287 } else
drh715ff302008-12-03 22:32:44 +00006288#endif
6289 if( pFile->pMethod == &dotlockIoMethods ){
6290 /* dot lock style uses the locking context to store the dot lock
6291 ** file path */
6292 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6293 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6294 }else{
6295 /* all other styles use the locking context to store the db file path */
6296 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006297 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006298 }
6299 return SQLITE_OK;
6300}
6301
6302/*
6303** Takes an already filled in unix file and alters it so all file locking
6304** will be performed on the local proxy lock file. The following fields
6305** are preserved in the locking context so that they can be restored and
6306** the unix structure properly cleaned up at close time:
6307** ->lockingContext
6308** ->pMethod
6309*/
6310static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6311 proxyLockingContext *pCtx;
6312 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6313 char *lockPath=NULL;
6314 int rc = SQLITE_OK;
6315
drh308c2a52010-05-14 11:30:18 +00006316 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006317 return SQLITE_BUSY;
6318 }
6319 proxyGetDbPathForUnixFile(pFile, dbPath);
6320 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6321 lockPath=NULL;
6322 }else{
6323 lockPath=(char *)path;
6324 }
6325
drh308c2a52010-05-14 11:30:18 +00006326 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6327 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006328
6329 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6330 if( pCtx==0 ){
6331 return SQLITE_NOMEM;
6332 }
6333 memset(pCtx, 0, sizeof(*pCtx));
6334
6335 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6336 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006337 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6338 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6339 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6340 ** (c) the file system is read-only, then enable no-locking access.
6341 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6342 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6343 */
6344 struct statfs fsInfo;
6345 struct stat conchInfo;
6346 int goLockless = 0;
6347
drh99ab3b12011-03-02 15:09:07 +00006348 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006349 int err = errno;
6350 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6351 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6352 }
6353 }
6354 if( goLockless ){
6355 pCtx->conchHeld = -1; /* read only FS/ lockless */
6356 rc = SQLITE_OK;
6357 }
6358 }
drh715ff302008-12-03 22:32:44 +00006359 }
6360 if( rc==SQLITE_OK && lockPath ){
6361 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6362 }
6363
6364 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006365 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6366 if( pCtx->dbPath==NULL ){
6367 rc = SQLITE_NOMEM;
6368 }
6369 }
6370 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006371 /* all memory is allocated, proxys are created and assigned,
6372 ** switch the locking context and pMethod then return.
6373 */
drh715ff302008-12-03 22:32:44 +00006374 pCtx->oldLockingContext = pFile->lockingContext;
6375 pFile->lockingContext = pCtx;
6376 pCtx->pOldMethod = pFile->pMethod;
6377 pFile->pMethod = &proxyIoMethods;
6378 }else{
6379 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006380 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006381 sqlite3_free(pCtx->conchFile);
6382 }
drhd56b1212010-08-11 06:14:15 +00006383 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006384 sqlite3_free(pCtx->conchFilePath);
6385 sqlite3_free(pCtx);
6386 }
drh308c2a52010-05-14 11:30:18 +00006387 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6388 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006389 return rc;
6390}
6391
6392
6393/*
6394** This routine handles sqlite3_file_control() calls that are specific
6395** to proxy locking.
6396*/
6397static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6398 switch( op ){
6399 case SQLITE_GET_LOCKPROXYFILE: {
6400 unixFile *pFile = (unixFile*)id;
6401 if( pFile->pMethod == &proxyIoMethods ){
6402 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6403 proxyTakeConch(pFile);
6404 if( pCtx->lockProxyPath ){
6405 *(const char **)pArg = pCtx->lockProxyPath;
6406 }else{
6407 *(const char **)pArg = ":auto: (not held)";
6408 }
6409 } else {
6410 *(const char **)pArg = NULL;
6411 }
6412 return SQLITE_OK;
6413 }
6414 case SQLITE_SET_LOCKPROXYFILE: {
6415 unixFile *pFile = (unixFile*)id;
6416 int rc = SQLITE_OK;
6417 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6418 if( pArg==NULL || (const char *)pArg==0 ){
6419 if( isProxyStyle ){
6420 /* turn off proxy locking - not supported */
6421 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6422 }else{
6423 /* turn off proxy locking - already off - NOOP */
6424 rc = SQLITE_OK;
6425 }
6426 }else{
6427 const char *proxyPath = (const char *)pArg;
6428 if( isProxyStyle ){
6429 proxyLockingContext *pCtx =
6430 (proxyLockingContext*)pFile->lockingContext;
6431 if( !strcmp(pArg, ":auto:")
6432 || (pCtx->lockProxyPath &&
6433 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6434 ){
6435 rc = SQLITE_OK;
6436 }else{
6437 rc = switchLockProxyPath(pFile, proxyPath);
6438 }
6439 }else{
6440 /* turn on proxy file locking */
6441 rc = proxyTransformUnixFile(pFile, proxyPath);
6442 }
6443 }
6444 return rc;
6445 }
6446 default: {
6447 assert( 0 ); /* The call assures that only valid opcodes are sent */
6448 }
6449 }
6450 /*NOTREACHED*/
6451 return SQLITE_ERROR;
6452}
6453
6454/*
6455** Within this division (the proxying locking implementation) the procedures
6456** above this point are all utilities. The lock-related methods of the
6457** proxy-locking sqlite3_io_method object follow.
6458*/
6459
6460
6461/*
6462** This routine checks if there is a RESERVED lock held on the specified
6463** file by this or any other process. If such a lock is held, set *pResOut
6464** to a non-zero value otherwise *pResOut is set to zero. The return value
6465** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6466*/
6467static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6468 unixFile *pFile = (unixFile*)id;
6469 int rc = proxyTakeConch(pFile);
6470 if( rc==SQLITE_OK ){
6471 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006472 if( pCtx->conchHeld>0 ){
6473 unixFile *proxy = pCtx->lockProxy;
6474 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6475 }else{ /* conchHeld < 0 is lockless */
6476 pResOut=0;
6477 }
drh715ff302008-12-03 22:32:44 +00006478 }
6479 return rc;
6480}
6481
6482/*
drh308c2a52010-05-14 11:30:18 +00006483** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006484** of the following:
6485**
6486** (1) SHARED_LOCK
6487** (2) RESERVED_LOCK
6488** (3) PENDING_LOCK
6489** (4) EXCLUSIVE_LOCK
6490**
6491** Sometimes when requesting one lock state, additional lock states
6492** are inserted in between. The locking might fail on one of the later
6493** transitions leaving the lock state different from what it started but
6494** still short of its goal. The following chart shows the allowed
6495** transitions and the inserted intermediate states:
6496**
6497** UNLOCKED -> SHARED
6498** SHARED -> RESERVED
6499** SHARED -> (PENDING) -> EXCLUSIVE
6500** RESERVED -> (PENDING) -> EXCLUSIVE
6501** PENDING -> EXCLUSIVE
6502**
6503** This routine will only increase a lock. Use the sqlite3OsUnlock()
6504** routine to lower a locking level.
6505*/
drh308c2a52010-05-14 11:30:18 +00006506static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006507 unixFile *pFile = (unixFile*)id;
6508 int rc = proxyTakeConch(pFile);
6509 if( rc==SQLITE_OK ){
6510 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006511 if( pCtx->conchHeld>0 ){
6512 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006513 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6514 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006515 }else{
6516 /* conchHeld < 0 is lockless */
6517 }
drh715ff302008-12-03 22:32:44 +00006518 }
6519 return rc;
6520}
6521
6522
6523/*
drh308c2a52010-05-14 11:30:18 +00006524** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006525** must be either NO_LOCK or SHARED_LOCK.
6526**
6527** If the locking level of the file descriptor is already at or below
6528** the requested locking level, this routine is a no-op.
6529*/
drh308c2a52010-05-14 11:30:18 +00006530static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006531 unixFile *pFile = (unixFile*)id;
6532 int rc = proxyTakeConch(pFile);
6533 if( rc==SQLITE_OK ){
6534 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006535 if( pCtx->conchHeld>0 ){
6536 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006537 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6538 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006539 }else{
6540 /* conchHeld < 0 is lockless */
6541 }
drh715ff302008-12-03 22:32:44 +00006542 }
6543 return rc;
6544}
6545
6546/*
6547** Close a file that uses proxy locks.
6548*/
6549static int proxyClose(sqlite3_file *id) {
6550 if( id ){
6551 unixFile *pFile = (unixFile*)id;
6552 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6553 unixFile *lockProxy = pCtx->lockProxy;
6554 unixFile *conchFile = pCtx->conchFile;
6555 int rc = SQLITE_OK;
6556
6557 if( lockProxy ){
6558 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6559 if( rc ) return rc;
6560 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6561 if( rc ) return rc;
6562 sqlite3_free(lockProxy);
6563 pCtx->lockProxy = 0;
6564 }
6565 if( conchFile ){
6566 if( pCtx->conchHeld ){
6567 rc = proxyReleaseConch(pFile);
6568 if( rc ) return rc;
6569 }
6570 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6571 if( rc ) return rc;
6572 sqlite3_free(conchFile);
6573 }
drhd56b1212010-08-11 06:14:15 +00006574 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006575 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006576 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006577 /* restore the original locking context and pMethod then close it */
6578 pFile->lockingContext = pCtx->oldLockingContext;
6579 pFile->pMethod = pCtx->pOldMethod;
6580 sqlite3_free(pCtx);
6581 return pFile->pMethod->xClose(id);
6582 }
6583 return SQLITE_OK;
6584}
6585
6586
6587
drhd2cb50b2009-01-09 21:41:17 +00006588#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006589/*
6590** The proxy locking style is intended for use with AFP filesystems.
6591** And since AFP is only supported on MacOSX, the proxy locking is also
6592** restricted to MacOSX.
6593**
6594**
6595******************* End of the proxy lock implementation **********************
6596******************************************************************************/
6597
drh734c9862008-11-28 15:37:20 +00006598/*
danielk1977e339d652008-06-28 11:23:00 +00006599** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006600**
6601** This routine registers all VFS implementations for unix-like operating
6602** systems. This routine, and the sqlite3_os_end() routine that follows,
6603** should be the only routines in this file that are visible from other
6604** files.
drh6b9d6dd2008-12-03 19:34:47 +00006605**
6606** This routine is called once during SQLite initialization and by a
6607** single thread. The memory allocation and mutex subsystems have not
6608** necessarily been initialized when this routine is called, and so they
6609** should not be used.
drh153c62c2007-08-24 03:51:33 +00006610*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006611int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006612 /*
6613 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006614 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6615 ** to the "finder" function. (pAppData is a pointer to a pointer because
6616 ** silly C90 rules prohibit a void* from being cast to a function pointer
6617 ** and so we have to go through the intermediate pointer to avoid problems
6618 ** when compiling with -pedantic-errors on GCC.)
6619 **
6620 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006621 ** finder-function. The finder-function returns a pointer to the
6622 ** sqlite_io_methods object that implements the desired locking
6623 ** behaviors. See the division above that contains the IOMETHODS
6624 ** macro for addition information on finder-functions.
6625 **
6626 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6627 ** object. But the "autolockIoFinder" available on MacOSX does a little
6628 ** more than that; it looks at the filesystem type that hosts the
6629 ** database file and tries to choose an locking method appropriate for
6630 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006631 */
drh7708e972008-11-29 00:56:52 +00006632 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006633 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006634 sizeof(unixFile), /* szOsFile */ \
6635 MAX_PATHNAME, /* mxPathname */ \
6636 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006637 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006638 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006639 unixOpen, /* xOpen */ \
6640 unixDelete, /* xDelete */ \
6641 unixAccess, /* xAccess */ \
6642 unixFullPathname, /* xFullPathname */ \
6643 unixDlOpen, /* xDlOpen */ \
6644 unixDlError, /* xDlError */ \
6645 unixDlSym, /* xDlSym */ \
6646 unixDlClose, /* xDlClose */ \
6647 unixRandomness, /* xRandomness */ \
6648 unixSleep, /* xSleep */ \
6649 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006650 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006651 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006652 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006653 unixGetSystemCall, /* xGetSystemCall */ \
6654 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006655 }
6656
drh6b9d6dd2008-12-03 19:34:47 +00006657 /*
6658 ** All default VFSes for unix are contained in the following array.
6659 **
6660 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6661 ** by the SQLite core when the VFS is registered. So the following
6662 ** array cannot be const.
6663 */
danielk1977e339d652008-06-28 11:23:00 +00006664 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006665#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006666 UNIXVFS("unix", autolockIoFinder ),
6667#else
6668 UNIXVFS("unix", posixIoFinder ),
6669#endif
6670 UNIXVFS("unix-none", nolockIoFinder ),
6671 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006672 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006673#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006674 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006675#endif
6676#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006677 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006678#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006679 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006680#endif
chw78a13182009-04-07 05:35:03 +00006681#endif
drhd2cb50b2009-01-09 21:41:17 +00006682#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006683 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006684 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006685 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006686#endif
drh153c62c2007-08-24 03:51:33 +00006687 };
drh6b9d6dd2008-12-03 19:34:47 +00006688 unsigned int i; /* Loop counter */
6689
6690 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006691 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006692 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006693 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006694 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006695}
danielk1977e339d652008-06-28 11:23:00 +00006696
6697/*
drh6b9d6dd2008-12-03 19:34:47 +00006698** Shutdown the operating system interface.
6699**
6700** Some operating systems might need to do some cleanup in this routine,
6701** to release dynamically allocated objects. But not on unix.
6702** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006703*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006704int sqlite3_os_end(void){
6705 return SQLITE_OK;
6706}
drhdce8bdb2007-08-16 13:01:44 +00006707
danielk197729bafea2008-06-26 10:41:19 +00006708#endif /* SQLITE_OS_UNIX */