blob: a65f894eb8c654395eb83ce26a707dd487a68601 [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
drh6033e152012-11-13 11:08:49 +000049/* Use posix_fallocate() if it is available
50*/
51#if !defined(HAVE_POSIX_FALLOCATE) \
52 && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
53# define HAVE_POSIX_FALLOCATE 1
54#endif
55
danielk1977e339d652008-06-28 11:23:00 +000056/*
drh6b9d6dd2008-12-03 19:34:47 +000057** There are various methods for file locking used for concurrency
58** control:
danielk1977e339d652008-06-28 11:23:00 +000059**
drh734c9862008-11-28 15:37:20 +000060** 1. POSIX locking (the default),
61** 2. No locking,
62** 3. Dot-file locking,
63** 4. flock() locking,
64** 5. AFP locking (OSX only),
65** 6. Named POSIX semaphores (VXWorks only),
66** 7. proxy locking. (OSX only)
67**
68** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
69** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
70** selection of the appropriate locking style based on the filesystem
71** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000072*/
drh40bbb0a2008-09-23 10:23:26 +000073#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000074# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000075# define SQLITE_ENABLE_LOCKING_STYLE 1
76# else
77# define SQLITE_ENABLE_LOCKING_STYLE 0
78# endif
79#endif
drhbfe66312006-10-03 17:40:40 +000080
drh9cbe6352005-11-29 03:13:21 +000081/*
drh6c7d5c52008-11-21 20:32:33 +000082** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000083** vxworks, or 0 otherwise.
84*/
drh6c7d5c52008-11-21 20:32:33 +000085#ifndef OS_VXWORKS
86# if defined(__RTP__) || defined(_WRS_KERNEL)
87# define OS_VXWORKS 1
88# else
89# define OS_VXWORKS 0
90# endif
danielk1977397d65f2008-11-19 11:35:39 +000091#endif
92
93/*
drh9cbe6352005-11-29 03:13:21 +000094** These #defines should enable >2GB file support on Posix if the
95** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000096** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000097**
98** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
99** on the compiler command line. This is necessary if you are compiling
100** on a recent machine (ex: RedHat 7.2) but you want your code to work
101** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
102** without this option, LFS is enable. But LFS does not exist in the kernel
103** in RedHat 6.0, so the code won't work. Hence, for maximum binary
104** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000105**
106** The previous paragraph was written in 2005. (This paragraph is written
107** on 2008-11-28.) These days, all Linux kernels support large files, so
108** you should probably leave LFS enabled. But some embedded platforms might
109** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000110*/
111#ifndef SQLITE_DISABLE_LFS
112# define _LARGE_FILE 1
113# ifndef _FILE_OFFSET_BITS
114# define _FILE_OFFSET_BITS 64
115# endif
116# define _LARGEFILE_SOURCE 1
117#endif
drhbbd42a62004-05-22 17:41:58 +0000118
drh9cbe6352005-11-29 03:13:21 +0000119/*
120** standard include files.
121*/
122#include <sys/types.h>
123#include <sys/stat.h>
124#include <fcntl.h>
125#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000126#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000127#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000128#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000129#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000130#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000131#endif
drh1da88f02011-12-17 16:09:16 +0000132
danielk1977e339d652008-06-28 11:23:00 +0000133
drh40bbb0a2008-09-23 10:23:26 +0000134#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000135# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000136# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000137# include <semaphore.h>
138# include <limits.h>
139# else
drh9b35ea62008-11-29 02:20:26 +0000140# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000141# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000142# endif
drhbfe66312006-10-03 17:40:40 +0000143#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000144
drhf8b4d8c2010-03-05 13:53:22 +0000145#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000146# include <sys/mount.h>
147#endif
148
drhdbe4b882011-06-20 18:00:17 +0000149#ifdef HAVE_UTIME
150# include <utime.h>
151#endif
152
drh9cbe6352005-11-29 03:13:21 +0000153/*
drh7ed97b92010-01-20 13:07:21 +0000154** Allowed values of unixFile.fsFlags
155*/
156#define SQLITE_FSFLAGS_IS_MSDOS 0x1
157
158/*
drhf1a221e2006-01-15 17:27:17 +0000159** If we are to be thread-safe, include the pthreads header and define
160** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000161*/
drhd677b3d2007-08-20 22:48:41 +0000162#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000163# include <pthread.h>
164# define SQLITE_UNIX_THREADS 1
165#endif
166
167/*
168** Default permissions when creating a new file
169*/
170#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
171# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
172#endif
173
danielk1977b4b47412007-08-17 15:53:36 +0000174/*
drh5adc60b2012-04-14 13:25:11 +0000175** Default permissions when creating auto proxy dir
176*/
aswiftaebf4132008-11-21 00:10:35 +0000177#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
178# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
179#endif
180
181/*
danielk1977b4b47412007-08-17 15:53:36 +0000182** Maximum supported path-length.
183*/
184#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000185
drh734c9862008-11-28 15:37:20 +0000186/*
drh734c9862008-11-28 15:37:20 +0000187** Only set the lastErrno if the error code is a real error and not
188** a normal expected return code of SQLITE_BUSY or SQLITE_OK
189*/
190#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
191
drhd91c68f2010-05-14 14:52:25 +0000192/* Forward references */
193typedef struct unixShm unixShm; /* Connection shared memory */
194typedef struct unixShmNode unixShmNode; /* Shared memory instance */
195typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
196typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000197
198/*
dane946c392009-08-22 11:39:46 +0000199** Sometimes, after a file handle is closed by SQLite, the file descriptor
200** cannot be closed immediately. In these cases, instances of the following
201** structure are used to store the file descriptor while waiting for an
202** opportunity to either close or reuse it.
203*/
dane946c392009-08-22 11:39:46 +0000204struct UnixUnusedFd {
205 int fd; /* File descriptor to close */
206 int flags; /* Flags this file descriptor was opened with */
207 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
208};
209
210/*
drh9b35ea62008-11-29 02:20:26 +0000211** The unixFile structure is subclass of sqlite3_file specific to the unix
212** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000213*/
drh054889e2005-11-30 03:20:31 +0000214typedef struct unixFile unixFile;
215struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000216 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000217 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000218 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000219 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000220 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000221 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000222 int lastErrno; /* The unix errno from last I/O error */
223 void *lockingContext; /* Locking style specific state */
224 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000225 const char *zPath; /* Name of the file */
226 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000227 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh0d0614b2013-03-25 23:09:28 +0000228 int nFetchOut; /* Number of outstanding xFetch refs */
229 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
230 sqlite3_int64 mmapOrigsize; /* Actual size of mapping at pMapRegion */
231 sqlite3_int64 mmapLimit; /* Configured FCNTL_MMAP_LIMIT value */
232 void *pMapRegion; /* Memory mapped region */
drh537dddf2012-10-26 13:46:24 +0000233#ifdef __QNXNTO__
234 int sectorSize; /* Device sector size */
235 int deviceCharacteristics; /* Precomputed device characteristics */
236#endif
drh08c6d442009-02-09 17:34:07 +0000237#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000238 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000239#endif
drh7ed97b92010-01-20 13:07:21 +0000240#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000241 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000242#endif
243#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000244 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000245#endif
drhd3d8c042012-05-29 17:02:40 +0000246#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000247 /* The next group of variables are used to track whether or not the
248 ** transaction counter in bytes 24-27 of database files are updated
249 ** whenever any part of the database changes. An assertion fault will
250 ** occur if a file is updated without also updating the transaction
251 ** counter. This test is made to avoid new problems similar to the
252 ** one described by ticket #3584.
253 */
254 unsigned char transCntrChng; /* True if the transaction counter changed */
255 unsigned char dbUpdate; /* True if any part of database file changed */
256 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000257
drh8f941bc2009-01-14 23:03:40 +0000258#endif
danf23da962013-03-23 21:00:41 +0000259
danielk1977967a4a12007-08-20 14:23:44 +0000260#ifdef SQLITE_TEST
261 /* In test mode, increase the size of this structure a bit so that
262 ** it is larger than the struct CrashFile defined in test6.c.
263 */
264 char aPadding[32];
265#endif
drh9cbe6352005-11-29 03:13:21 +0000266};
267
drh0ccebe72005-06-07 22:22:50 +0000268/*
drha7e61d82011-03-12 17:02:57 +0000269** Allowed values for the unixFile.ctrlFlags bitmask:
270*/
drhf0b190d2011-07-26 16:03:07 +0000271#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
272#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
273#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000274#ifndef SQLITE_DISABLE_DIRSYNC
275# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
276#else
277# define UNIXFILE_DIRSYNC 0x00
278#endif
drhcb15f352011-12-23 01:04:17 +0000279#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000280#define UNIXFILE_DELETE 0x20 /* Delete on close */
281#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
282#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000283
284/*
drh198bf392006-01-06 21:52:49 +0000285** Include code that is common to all os_*.c files
286*/
287#include "os_common.h"
288
289/*
drh0ccebe72005-06-07 22:22:50 +0000290** Define various macros that are missing from some systems.
291*/
drhbbd42a62004-05-22 17:41:58 +0000292#ifndef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifdef SQLITE_DISABLE_LFS
296# undef O_LARGEFILE
297# define O_LARGEFILE 0
298#endif
299#ifndef O_NOFOLLOW
300# define O_NOFOLLOW 0
301#endif
302#ifndef O_BINARY
303# define O_BINARY 0
304#endif
305
306/*
drh2b4b5962005-06-15 17:47:55 +0000307** The threadid macro resolves to the thread-id or to 0. Used for
308** testing and debugging only.
309*/
drhd677b3d2007-08-20 22:48:41 +0000310#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000311#define threadid pthread_self()
312#else
313#define threadid 0
314#endif
315
drh99ab3b12011-03-02 15:09:07 +0000316/*
dane6ecd662013-04-01 17:56:59 +0000317** HAVE_MREMAP defaults to true on Linux and false everywhere else.
318*/
319#if !defined(HAVE_MREMAP)
320# if defined(__linux__) && defined(_GNU_SOURCE)
321# define HAVE_MREMAP 1
322# else
323# define HAVE_MREMAP 0
324# endif
325#endif
326
327/*
drh9a3baf12011-04-25 18:01:27 +0000328** Different Unix systems declare open() in different ways. Same use
329** open(const char*,int,mode_t). Others use open(const char*,int,...).
330** The difference is important when using a pointer to the function.
331**
332** The safest way to deal with the problem is to always use this wrapper
333** which always has the same well-defined interface.
334*/
335static int posixOpen(const char *zFile, int flags, int mode){
336 return open(zFile, flags, mode);
337}
338
drhed466822012-05-31 13:10:49 +0000339/*
340** On some systems, calls to fchown() will trigger a message in a security
341** log if they come from non-root processes. So avoid calling fchown() if
342** we are not running as root.
343*/
344static int posixFchown(int fd, uid_t uid, gid_t gid){
345 return geteuid() ? 0 : fchown(fd,uid,gid);
346}
347
drh90315a22011-08-10 01:52:12 +0000348/* Forward reference */
349static int openDirectory(const char*, int*);
350
drh9a3baf12011-04-25 18:01:27 +0000351/*
drh99ab3b12011-03-02 15:09:07 +0000352** Many system calls are accessed through pointer-to-functions so that
353** they may be overridden at runtime to facilitate fault injection during
354** testing and sandboxing. The following array holds the names and pointers
355** to all overrideable system calls.
356*/
357static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000358 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000359 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
360 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000361} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000362 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
363#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000364
drh58ad5802011-03-23 22:02:23 +0000365 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000366#define osClose ((int(*)(int))aSyscall[1].pCurrent)
367
drh58ad5802011-03-23 22:02:23 +0000368 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000369#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
370
drh58ad5802011-03-23 22:02:23 +0000371 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000372#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
373
drh58ad5802011-03-23 22:02:23 +0000374 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000375#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
376
377/*
378** The DJGPP compiler environment looks mostly like Unix, but it
379** lacks the fcntl() system call. So redefine fcntl() to be something
380** that always succeeds. This means that locking does not occur under
381** DJGPP. But it is DOS - what did you expect?
382*/
383#ifdef __DJGPP__
384 { "fstat", 0, 0 },
385#define osFstat(a,b,c) 0
386#else
drh58ad5802011-03-23 22:02:23 +0000387 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
389#endif
390
drh58ad5802011-03-23 22:02:23 +0000391 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000392#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
393
drh58ad5802011-03-23 22:02:23 +0000394 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000395#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000396
drh58ad5802011-03-23 22:02:23 +0000397 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000398#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
399
drhd4a80312011-04-15 14:33:20 +0000400#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000401 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000402#else
drh58ad5802011-03-23 22:02:23 +0000403 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000404#endif
405#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
406
407#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000408 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000409#else
drh58ad5802011-03-23 22:02:23 +0000410 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000411#endif
412#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
413
drh58ad5802011-03-23 22:02:23 +0000414 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000415#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
416
drhd4a80312011-04-15 14:33:20 +0000417#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000418 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000419#else
drh58ad5802011-03-23 22:02:23 +0000420 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000421#endif
422#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
423 aSyscall[12].pCurrent)
424
425#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000426 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000427#else
drh58ad5802011-03-23 22:02:23 +0000428 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000429#endif
430#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
431 aSyscall[13].pCurrent)
432
drh58ad5802011-03-23 22:02:23 +0000433 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000434#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000435
436#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000437 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000438#else
drh58ad5802011-03-23 22:02:23 +0000439 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000440#endif
dan0fd7d862011-03-29 10:04:23 +0000441#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000442
drh036ac7f2011-08-08 23:18:05 +0000443 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
444#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
445
drh90315a22011-08-10 01:52:12 +0000446 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
447#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
448
drh9ef6bc42011-11-04 02:24:02 +0000449 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
450#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
451
452 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
453#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
454
drhed466822012-05-31 13:10:49 +0000455 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000456#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000457
dan893c0ff2013-03-25 19:05:07 +0000458 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
459#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
460
drhd1ab8062013-03-25 20:50:25 +0000461 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
462#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
463
dane6ecd662013-04-01 17:56:59 +0000464#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000465 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
466#else
467 { "mremap", (sqlite3_syscall_ptr)0, 0 },
468#endif
469#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
470
drhe562be52011-03-02 18:01:10 +0000471}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000472
473/*
474** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000475** "unix" VFSes. Return SQLITE_OK opon successfully updating the
476** system call pointer, or SQLITE_NOTFOUND if there is no configurable
477** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000478*/
479static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000480 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
481 const char *zName, /* Name of system call to override */
482 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000483){
drh58ad5802011-03-23 22:02:23 +0000484 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000485 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000486
487 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000488 if( zName==0 ){
489 /* If no zName is given, restore all system calls to their default
490 ** settings and return NULL
491 */
dan51438a72011-04-02 17:00:47 +0000492 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000493 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
494 if( aSyscall[i].pDefault ){
495 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000496 }
497 }
498 }else{
499 /* If zName is specified, operate on only the one system call
500 ** specified.
501 */
502 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
503 if( strcmp(zName, aSyscall[i].zName)==0 ){
504 if( aSyscall[i].pDefault==0 ){
505 aSyscall[i].pDefault = aSyscall[i].pCurrent;
506 }
drh1df30962011-03-02 19:06:42 +0000507 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000508 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
509 aSyscall[i].pCurrent = pNewFunc;
510 break;
511 }
512 }
513 }
514 return rc;
515}
516
drh1df30962011-03-02 19:06:42 +0000517/*
518** Return the value of a system call. Return NULL if zName is not a
519** recognized system call name. NULL is also returned if the system call
520** is currently undefined.
521*/
drh58ad5802011-03-23 22:02:23 +0000522static sqlite3_syscall_ptr unixGetSystemCall(
523 sqlite3_vfs *pNotUsed,
524 const char *zName
525){
526 unsigned int i;
527
528 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000529 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
530 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
531 }
532 return 0;
533}
534
535/*
536** Return the name of the first system call after zName. If zName==NULL
537** then return the name of the first system call. Return NULL if zName
538** is the last system call or if zName is not the name of a valid
539** system call.
540*/
541static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000542 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000543
544 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000545 if( zName ){
546 for(i=0; i<ArraySize(aSyscall)-1; i++){
547 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000548 }
549 }
dan0fd7d862011-03-29 10:04:23 +0000550 for(i++; i<ArraySize(aSyscall); i++){
551 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000552 }
553 return 0;
554}
555
drhad4f1e52011-03-04 15:43:57 +0000556/*
drh8c815d12012-02-13 20:16:37 +0000557** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000558** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000559**
560** If the file creation mode "m" is 0 then set it to the default for
561** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
562** 0644) as modified by the system umask. If m is not 0, then
563** make the file creation mode be exactly m ignoring the umask.
564**
565** The m parameter will be non-zero only when creating -wal, -journal,
566** and -shm files. We want those files to have *exactly* the same
567** permissions as their original database, unadulterated by the umask.
568** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
569** transaction crashes and leaves behind hot journals, then any
570** process that is able to write to the database will also be able to
571** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000572*/
drh8c815d12012-02-13 20:16:37 +0000573static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000574 int fd;
drhe1186ab2013-01-04 20:45:13 +0000575 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000576 do{
577#if defined(O_CLOEXEC)
578 fd = osOpen(z,f|O_CLOEXEC,m2);
579#else
580 fd = osOpen(z,f,m2);
581#endif
582 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000583 if( fd>=0 ){
584 if( m!=0 ){
585 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000586 if( osFstat(fd, &statbuf)==0
587 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000588 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000589 ){
drhe1186ab2013-01-04 20:45:13 +0000590 osFchmod(fd, m);
591 }
592 }
drh5adc60b2012-04-14 13:25:11 +0000593#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000594 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000595#endif
drhe1186ab2013-01-04 20:45:13 +0000596 }
drh5adc60b2012-04-14 13:25:11 +0000597 return fd;
drhad4f1e52011-03-04 15:43:57 +0000598}
danielk197713adf8a2004-06-03 16:08:41 +0000599
drh107886a2008-11-21 22:21:50 +0000600/*
dan9359c7b2009-08-21 08:29:10 +0000601** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000602** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000603** vxworksFileId objects used by this file, all of which may be
604** shared by multiple threads.
605**
606** Function unixMutexHeld() is used to assert() that the global mutex
607** is held when required. This function is only used as part of assert()
608** statements. e.g.
609**
610** unixEnterMutex()
611** assert( unixMutexHeld() );
612** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000613*/
614static void unixEnterMutex(void){
615 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
616}
617static void unixLeaveMutex(void){
618 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
619}
dan9359c7b2009-08-21 08:29:10 +0000620#ifdef SQLITE_DEBUG
621static int unixMutexHeld(void) {
622 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
623}
624#endif
drh107886a2008-11-21 22:21:50 +0000625
drh734c9862008-11-28 15:37:20 +0000626
drh30ddce62011-10-15 00:16:30 +0000627#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000628/*
629** Helper function for printing out trace information from debugging
630** binaries. This returns the string represetation of the supplied
631** integer lock-type.
632*/
drh308c2a52010-05-14 11:30:18 +0000633static const char *azFileLock(int eFileLock){
634 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000635 case NO_LOCK: return "NONE";
636 case SHARED_LOCK: return "SHARED";
637 case RESERVED_LOCK: return "RESERVED";
638 case PENDING_LOCK: return "PENDING";
639 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000640 }
641 return "ERROR";
642}
643#endif
644
645#ifdef SQLITE_LOCK_TRACE
646/*
647** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000648**
drh734c9862008-11-28 15:37:20 +0000649** This routine is used for troubleshooting locks on multithreaded
650** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
651** command-line option on the compiler. This code is normally
652** turned off.
653*/
654static int lockTrace(int fd, int op, struct flock *p){
655 char *zOpName, *zType;
656 int s;
657 int savedErrno;
658 if( op==F_GETLK ){
659 zOpName = "GETLK";
660 }else if( op==F_SETLK ){
661 zOpName = "SETLK";
662 }else{
drh99ab3b12011-03-02 15:09:07 +0000663 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000664 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
665 return s;
666 }
667 if( p->l_type==F_RDLCK ){
668 zType = "RDLCK";
669 }else if( p->l_type==F_WRLCK ){
670 zType = "WRLCK";
671 }else if( p->l_type==F_UNLCK ){
672 zType = "UNLCK";
673 }else{
674 assert( 0 );
675 }
676 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000677 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000678 savedErrno = errno;
679 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
680 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
681 (int)p->l_pid, s);
682 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
683 struct flock l2;
684 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000685 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000686 if( l2.l_type==F_RDLCK ){
687 zType = "RDLCK";
688 }else if( l2.l_type==F_WRLCK ){
689 zType = "WRLCK";
690 }else if( l2.l_type==F_UNLCK ){
691 zType = "UNLCK";
692 }else{
693 assert( 0 );
694 }
695 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
696 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
697 }
698 errno = savedErrno;
699 return s;
700}
drh99ab3b12011-03-02 15:09:07 +0000701#undef osFcntl
702#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000703#endif /* SQLITE_LOCK_TRACE */
704
drhff812312011-02-23 13:33:46 +0000705/*
706** Retry ftruncate() calls that fail due to EINTR
707*/
drhff812312011-02-23 13:33:46 +0000708static int robust_ftruncate(int h, sqlite3_int64 sz){
709 int rc;
drh99ab3b12011-03-02 15:09:07 +0000710 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000711 return rc;
712}
drh734c9862008-11-28 15:37:20 +0000713
714/*
715** This routine translates a standard POSIX errno code into something
716** useful to the clients of the sqlite3 functions. Specifically, it is
717** intended to translate a variety of "try again" errors into SQLITE_BUSY
718** and a variety of "please close the file descriptor NOW" errors into
719** SQLITE_IOERR
720**
721** Errors during initialization of locks, or file system support for locks,
722** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
723*/
724static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
725 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000726#if 0
727 /* At one point this code was not commented out. In theory, this branch
728 ** should never be hit, as this function should only be called after
729 ** a locking-related function (i.e. fcntl()) has returned non-zero with
730 ** the value of errno as the first argument. Since a system call has failed,
731 ** errno should be non-zero.
732 **
733 ** Despite this, if errno really is zero, we still don't want to return
734 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
735 ** propagated back to the caller. Commenting this branch out means errno==0
736 ** will be handled by the "default:" case below.
737 */
drh734c9862008-11-28 15:37:20 +0000738 case 0:
739 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000740#endif
741
drh734c9862008-11-28 15:37:20 +0000742 case EAGAIN:
743 case ETIMEDOUT:
744 case EBUSY:
745 case EINTR:
746 case ENOLCK:
747 /* random NFS retry error, unless during file system support
748 * introspection, in which it actually means what it says */
749 return SQLITE_BUSY;
750
751 case EACCES:
752 /* EACCES is like EAGAIN during locking operations, but not any other time*/
753 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000754 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
755 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
756 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000757 return SQLITE_BUSY;
758 }
759 /* else fall through */
760 case EPERM:
761 return SQLITE_PERM;
762
danea83bc62011-04-01 11:56:32 +0000763 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
764 ** this module never makes such a call. And the code in SQLite itself
765 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
766 ** this case is also commented out. If the system does set errno to EDEADLK,
767 ** the default SQLITE_IOERR_XXX code will be returned. */
768#if 0
drh734c9862008-11-28 15:37:20 +0000769 case EDEADLK:
770 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000771#endif
drh734c9862008-11-28 15:37:20 +0000772
773#if EOPNOTSUPP!=ENOTSUP
774 case EOPNOTSUPP:
775 /* something went terribly awry, unless during file system support
776 * introspection, in which it actually means what it says */
777#endif
778#ifdef ENOTSUP
779 case ENOTSUP:
780 /* invalid fd, unless during file system support introspection, in which
781 * it actually means what it says */
782#endif
783 case EIO:
784 case EBADF:
785 case EINVAL:
786 case ENOTCONN:
787 case ENODEV:
788 case ENXIO:
789 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000790#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000791 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000792#endif
drh734c9862008-11-28 15:37:20 +0000793 case ENOSYS:
794 /* these should force the client to close the file and reconnect */
795
796 default:
797 return sqliteIOErr;
798 }
799}
800
801
802
803/******************************************************************************
804****************** Begin Unique File ID Utility Used By VxWorks ***************
805**
806** On most versions of unix, we can get a unique ID for a file by concatenating
807** the device number and the inode number. But this does not work on VxWorks.
808** On VxWorks, a unique file id must be based on the canonical filename.
809**
810** A pointer to an instance of the following structure can be used as a
811** unique file ID in VxWorks. Each instance of this structure contains
812** a copy of the canonical filename. There is also a reference count.
813** The structure is reclaimed when the number of pointers to it drops to
814** zero.
815**
816** There are never very many files open at one time and lookups are not
817** a performance-critical path, so it is sufficient to put these
818** structures on a linked list.
819*/
820struct vxworksFileId {
821 struct vxworksFileId *pNext; /* Next in a list of them all */
822 int nRef; /* Number of references to this one */
823 int nName; /* Length of the zCanonicalName[] string */
824 char *zCanonicalName; /* Canonical filename */
825};
826
827#if OS_VXWORKS
828/*
drh9b35ea62008-11-29 02:20:26 +0000829** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000830** variable:
831*/
832static struct vxworksFileId *vxworksFileList = 0;
833
834/*
835** Simplify a filename into its canonical form
836** by making the following changes:
837**
838** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000839** * convert /./ into just /
840** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000841**
842** Changes are made in-place. Return the new name length.
843**
844** The original filename is in z[0..n-1]. Return the number of
845** characters in the simplified name.
846*/
847static int vxworksSimplifyName(char *z, int n){
848 int i, j;
849 while( n>1 && z[n-1]=='/' ){ n--; }
850 for(i=j=0; i<n; i++){
851 if( z[i]=='/' ){
852 if( z[i+1]=='/' ) continue;
853 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
854 i += 1;
855 continue;
856 }
857 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
858 while( j>0 && z[j-1]!='/' ){ j--; }
859 if( j>0 ){ j--; }
860 i += 2;
861 continue;
862 }
863 }
864 z[j++] = z[i];
865 }
866 z[j] = 0;
867 return j;
868}
869
870/*
871** Find a unique file ID for the given absolute pathname. Return
872** a pointer to the vxworksFileId object. This pointer is the unique
873** file ID.
874**
875** The nRef field of the vxworksFileId object is incremented before
876** the object is returned. A new vxworksFileId object is created
877** and added to the global list if necessary.
878**
879** If a memory allocation error occurs, return NULL.
880*/
881static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
882 struct vxworksFileId *pNew; /* search key and new file ID */
883 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
884 int n; /* Length of zAbsoluteName string */
885
886 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000887 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000888 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
889 if( pNew==0 ) return 0;
890 pNew->zCanonicalName = (char*)&pNew[1];
891 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
892 n = vxworksSimplifyName(pNew->zCanonicalName, n);
893
894 /* Search for an existing entry that matching the canonical name.
895 ** If found, increment the reference count and return a pointer to
896 ** the existing file ID.
897 */
898 unixEnterMutex();
899 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
900 if( pCandidate->nName==n
901 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
902 ){
903 sqlite3_free(pNew);
904 pCandidate->nRef++;
905 unixLeaveMutex();
906 return pCandidate;
907 }
908 }
909
910 /* No match was found. We will make a new file ID */
911 pNew->nRef = 1;
912 pNew->nName = n;
913 pNew->pNext = vxworksFileList;
914 vxworksFileList = pNew;
915 unixLeaveMutex();
916 return pNew;
917}
918
919/*
920** Decrement the reference count on a vxworksFileId object. Free
921** the object when the reference count reaches zero.
922*/
923static void vxworksReleaseFileId(struct vxworksFileId *pId){
924 unixEnterMutex();
925 assert( pId->nRef>0 );
926 pId->nRef--;
927 if( pId->nRef==0 ){
928 struct vxworksFileId **pp;
929 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
930 assert( *pp==pId );
931 *pp = pId->pNext;
932 sqlite3_free(pId);
933 }
934 unixLeaveMutex();
935}
936#endif /* OS_VXWORKS */
937/*************** End of Unique File ID Utility Used By VxWorks ****************
938******************************************************************************/
939
940
941/******************************************************************************
942*************************** Posix Advisory Locking ****************************
943**
drh9b35ea62008-11-29 02:20:26 +0000944** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000945** section 6.5.2.2 lines 483 through 490 specify that when a process
946** sets or clears a lock, that operation overrides any prior locks set
947** by the same process. It does not explicitly say so, but this implies
948** that it overrides locks set by the same process using a different
949** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000950**
951** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000952** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
953**
954** Suppose ./file1 and ./file2 are really the same file (because
955** one is a hard or symbolic link to the other) then if you set
956** an exclusive lock on fd1, then try to get an exclusive lock
957** on fd2, it works. I would have expected the second lock to
958** fail since there was already a lock on the file due to fd1.
959** But not so. Since both locks came from the same process, the
960** second overrides the first, even though they were on different
961** file descriptors opened on different file names.
962**
drh734c9862008-11-28 15:37:20 +0000963** This means that we cannot use POSIX locks to synchronize file access
964** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000965** to synchronize access for threads in separate processes, but not
966** threads within the same process.
967**
968** To work around the problem, SQLite has to manage file locks internally
969** on its own. Whenever a new database is opened, we have to find the
970** specific inode of the database file (the inode is determined by the
971** st_dev and st_ino fields of the stat structure that fstat() fills in)
972** and check for locks already existing on that inode. When locks are
973** created or removed, we have to look at our own internal record of the
974** locks to see if another thread has previously set a lock on that same
975** inode.
976**
drh9b35ea62008-11-29 02:20:26 +0000977** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
978** For VxWorks, we have to use the alternative unique ID system based on
979** canonical filename and implemented in the previous division.)
980**
danielk1977ad94b582007-08-20 06:44:22 +0000981** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000982** descriptor. It is now a structure that holds the integer file
983** descriptor and a pointer to a structure that describes the internal
984** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000985** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000986** point to the same locking structure. The locking structure keeps
987** a reference count (so we will know when to delete it) and a "cnt"
988** field that tells us its internal lock status. cnt==0 means the
989** file is unlocked. cnt==-1 means the file has an exclusive lock.
990** cnt>0 means there are cnt shared locks on the file.
991**
992** Any attempt to lock or unlock a file first checks the locking
993** structure. The fcntl() system call is only invoked to set a
994** POSIX lock if the internal lock structure transitions between
995** a locked and an unlocked state.
996**
drh734c9862008-11-28 15:37:20 +0000997** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000998**
999** If you close a file descriptor that points to a file that has locks,
1000** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001001** released. To work around this problem, each unixInodeInfo object
1002** maintains a count of the number of pending locks on tha inode.
1003** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001004** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001005** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001006** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001007** be closed and that list is walked (and cleared) when the last lock
1008** clears.
1009**
drh9b35ea62008-11-29 02:20:26 +00001010** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001011**
drh9b35ea62008-11-29 02:20:26 +00001012** Many older versions of linux use the LinuxThreads library which is
1013** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001014** A cannot be modified or overridden by a different thread B.
1015** Only thread A can modify the lock. Locking behavior is correct
1016** if the appliation uses the newer Native Posix Thread Library (NPTL)
1017** on linux - with NPTL a lock created by thread A can override locks
1018** in thread B. But there is no way to know at compile-time which
1019** threading library is being used. So there is no way to know at
1020** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001021** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001022** current process.
drh5fdae772004-06-29 03:29:00 +00001023**
drh8af6c222010-05-14 12:43:01 +00001024** SQLite used to support LinuxThreads. But support for LinuxThreads
1025** was dropped beginning with version 3.7.0. SQLite will still work with
1026** LinuxThreads provided that (1) there is no more than one connection
1027** per database file in the same process and (2) database connections
1028** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001029*/
1030
1031/*
1032** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001033** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001034*/
1035struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001036 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001037#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001038 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001039#else
drh107886a2008-11-21 22:21:50 +00001040 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001041#endif
1042};
1043
1044/*
drhbbd42a62004-05-22 17:41:58 +00001045** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001046** inode. Or, on LinuxThreads, there is one of these structures for
1047** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001048**
danielk1977ad94b582007-08-20 06:44:22 +00001049** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001050** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001051** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001052*/
drh8af6c222010-05-14 12:43:01 +00001053struct unixInodeInfo {
1054 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001055 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001056 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1057 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001058 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001059 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1060 int nLock; /* Number of outstanding file locks */
1061 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1062 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1063 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001064#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001065 unsigned long long sharedByte; /* for AFP simulated shared lock */
1066#endif
drh6c7d5c52008-11-21 20:32:33 +00001067#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001068 sem_t *pSem; /* Named POSIX semaphore */
1069 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001070#endif
drhbbd42a62004-05-22 17:41:58 +00001071};
1072
drhda0e7682008-07-30 15:27:54 +00001073/*
drh8af6c222010-05-14 12:43:01 +00001074** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001075*/
drhd91c68f2010-05-14 14:52:25 +00001076static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001077
drh5fdae772004-06-29 03:29:00 +00001078/*
dane18d4952011-02-21 11:46:24 +00001079**
1080** This function - unixLogError_x(), is only ever called via the macro
1081** unixLogError().
1082**
1083** It is invoked after an error occurs in an OS function and errno has been
1084** set. It logs a message using sqlite3_log() containing the current value of
1085** errno and, if possible, the human-readable equivalent from strerror() or
1086** strerror_r().
1087**
1088** The first argument passed to the macro should be the error code that
1089** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1090** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001091** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001092** if any.
1093*/
drh0e9365c2011-03-02 02:08:13 +00001094#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1095static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001096 int errcode, /* SQLite error code */
1097 const char *zFunc, /* Name of OS function that failed */
1098 const char *zPath, /* File path associated with error */
1099 int iLine /* Source line number where error occurred */
1100){
1101 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001102 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001103
1104 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1105 ** the strerror() function to obtain the human-readable error message
1106 ** equivalent to errno. Otherwise, use strerror_r().
1107 */
1108#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1109 char aErr[80];
1110 memset(aErr, 0, sizeof(aErr));
1111 zErr = aErr;
1112
1113 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001114 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001115 ** returns a pointer to a buffer containing the error message. That pointer
1116 ** may point to aErr[], or it may point to some static storage somewhere.
1117 ** Otherwise, assume that the system provides the POSIX version of
1118 ** strerror_r(), which always writes an error message into aErr[].
1119 **
1120 ** If the code incorrectly assumes that it is the POSIX version that is
1121 ** available, the error message will often be an empty string. Not a
1122 ** huge problem. Incorrectly concluding that the GNU version is available
1123 ** could lead to a segfault though.
1124 */
1125#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1126 zErr =
1127# endif
drh0e9365c2011-03-02 02:08:13 +00001128 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001129
1130#elif SQLITE_THREADSAFE
1131 /* This is a threadsafe build, but strerror_r() is not available. */
1132 zErr = "";
1133#else
1134 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001135 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001136#endif
1137
drh0e9365c2011-03-02 02:08:13 +00001138 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001139 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001140 "os_unix.c:%d: (%d) %s(%s) - %s",
1141 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001142 );
1143
1144 return errcode;
1145}
1146
drh0e9365c2011-03-02 02:08:13 +00001147/*
1148** Close a file descriptor.
1149**
1150** We assume that close() almost always works, since it is only in a
1151** very sick application or on a very sick platform that it might fail.
1152** If it does fail, simply leak the file descriptor, but do log the
1153** error.
1154**
1155** Note that it is not safe to retry close() after EINTR since the
1156** file descriptor might have already been reused by another thread.
1157** So we don't even try to recover from an EINTR. Just log the error
1158** and move on.
1159*/
1160static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001161 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001162 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1163 pFile ? pFile->zPath : 0, lineno);
1164 }
1165}
dane18d4952011-02-21 11:46:24 +00001166
1167/*
danb0ac3e32010-06-16 10:55:42 +00001168** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001169*/
drh0e9365c2011-03-02 02:08:13 +00001170static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001171 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001172 UnixUnusedFd *p;
1173 UnixUnusedFd *pNext;
1174 for(p=pInode->pUnused; p; p=pNext){
1175 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001176 robust_close(pFile, p->fd, __LINE__);
1177 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001178 }
drh0e9365c2011-03-02 02:08:13 +00001179 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001180}
1181
1182/*
drh8af6c222010-05-14 12:43:01 +00001183** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001184**
1185** The mutex entered using the unixEnterMutex() function must be held
1186** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001187*/
danb0ac3e32010-06-16 10:55:42 +00001188static void releaseInodeInfo(unixFile *pFile){
1189 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001190 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001191 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001192 pInode->nRef--;
1193 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001194 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001195 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001196 if( pInode->pPrev ){
1197 assert( pInode->pPrev->pNext==pInode );
1198 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001199 }else{
drh8af6c222010-05-14 12:43:01 +00001200 assert( inodeList==pInode );
1201 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 if( pInode->pNext ){
1204 assert( pInode->pNext->pPrev==pInode );
1205 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001206 }
drh8af6c222010-05-14 12:43:01 +00001207 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001208 }
drhbbd42a62004-05-22 17:41:58 +00001209 }
1210}
1211
1212/*
drh8af6c222010-05-14 12:43:01 +00001213** Given a file descriptor, locate the unixInodeInfo object that
1214** describes that file descriptor. Create a new one if necessary. The
1215** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001216**
dan9359c7b2009-08-21 08:29:10 +00001217** The mutex entered using the unixEnterMutex() function must be held
1218** when this function is called.
1219**
drh6c7d5c52008-11-21 20:32:33 +00001220** Return an appropriate error code.
1221*/
drh8af6c222010-05-14 12:43:01 +00001222static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001223 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001224 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001225){
1226 int rc; /* System call return code */
1227 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001228 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1229 struct stat statbuf; /* Low-level file information */
1230 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001231
dan9359c7b2009-08-21 08:29:10 +00001232 assert( unixMutexHeld() );
1233
drh6c7d5c52008-11-21 20:32:33 +00001234 /* Get low-level information about the file that we can used to
1235 ** create a unique name for the file.
1236 */
1237 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001238 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001239 if( rc!=0 ){
1240 pFile->lastErrno = errno;
1241#ifdef EOVERFLOW
1242 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1243#endif
1244 return SQLITE_IOERR;
1245 }
1246
drheb0d74f2009-02-03 15:27:02 +00001247#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001248 /* On OS X on an msdos filesystem, the inode number is reported
1249 ** incorrectly for zero-size files. See ticket #3260. To work
1250 ** around this problem (we consider it a bug in OS X, not SQLite)
1251 ** we always increase the file size to 1 by writing a single byte
1252 ** prior to accessing the inode number. The one byte written is
1253 ** an ASCII 'S' character which also happens to be the first byte
1254 ** in the header of every SQLite database. In this way, if there
1255 ** is a race condition such that another thread has already populated
1256 ** the first page of the database, no damage is done.
1257 */
drh7ed97b92010-01-20 13:07:21 +00001258 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001259 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001260 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001261 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001262 return SQLITE_IOERR;
1263 }
drh99ab3b12011-03-02 15:09:07 +00001264 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001265 if( rc!=0 ){
1266 pFile->lastErrno = errno;
1267 return SQLITE_IOERR;
1268 }
1269 }
drheb0d74f2009-02-03 15:27:02 +00001270#endif
drh6c7d5c52008-11-21 20:32:33 +00001271
drh8af6c222010-05-14 12:43:01 +00001272 memset(&fileId, 0, sizeof(fileId));
1273 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001274#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001275 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001276#else
drh8af6c222010-05-14 12:43:01 +00001277 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001278#endif
drh8af6c222010-05-14 12:43:01 +00001279 pInode = inodeList;
1280 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1281 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001282 }
drh8af6c222010-05-14 12:43:01 +00001283 if( pInode==0 ){
1284 pInode = sqlite3_malloc( sizeof(*pInode) );
1285 if( pInode==0 ){
1286 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 memset(pInode, 0, sizeof(*pInode));
1289 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1290 pInode->nRef = 1;
1291 pInode->pNext = inodeList;
1292 pInode->pPrev = 0;
1293 if( inodeList ) inodeList->pPrev = pInode;
1294 inodeList = pInode;
1295 }else{
1296 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001297 }
drh8af6c222010-05-14 12:43:01 +00001298 *ppInode = pInode;
1299 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001300}
drh6c7d5c52008-11-21 20:32:33 +00001301
aswift5b1a2562008-08-22 00:22:35 +00001302
1303/*
danielk197713adf8a2004-06-03 16:08:41 +00001304** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001305** file by this or any other process. If such a lock is held, set *pResOut
1306** to a non-zero value otherwise *pResOut is set to zero. The return value
1307** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001308*/
danielk1977861f7452008-06-05 11:39:11 +00001309static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001310 int rc = SQLITE_OK;
1311 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001312 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001313
danielk1977861f7452008-06-05 11:39:11 +00001314 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1315
drh054889e2005-11-30 03:20:31 +00001316 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001317 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001318
1319 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001320 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001321 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001322 }
1323
drh2ac3ee92004-06-07 16:27:46 +00001324 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001325 */
danielk197709480a92009-02-09 05:32:32 +00001326#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001327 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001328 struct flock lock;
1329 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001330 lock.l_start = RESERVED_BYTE;
1331 lock.l_len = 1;
1332 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001333 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1334 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1335 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001336 } else if( lock.l_type!=F_UNLCK ){
1337 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001338 }
1339 }
danielk197709480a92009-02-09 05:32:32 +00001340#endif
danielk197713adf8a2004-06-03 16:08:41 +00001341
drh6c7d5c52008-11-21 20:32:33 +00001342 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001343 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001344
aswift5b1a2562008-08-22 00:22:35 +00001345 *pResOut = reserved;
1346 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001347}
1348
1349/*
drha7e61d82011-03-12 17:02:57 +00001350** Attempt to set a system-lock on the file pFile. The lock is
1351** described by pLock.
1352**
drh77197112011-03-15 19:08:48 +00001353** If the pFile was opened read/write from unix-excl, then the only lock
1354** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001355** the first time any lock is attempted. All subsequent system locking
1356** operations become no-ops. Locking operations still happen internally,
1357** in order to coordinate access between separate database connections
1358** within this process, but all of that is handled in memory and the
1359** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001360**
1361** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1362** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1363** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001364**
1365** Zero is returned if the call completes successfully, or -1 if a call
1366** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001367*/
1368static int unixFileLock(unixFile *pFile, struct flock *pLock){
1369 int rc;
drh3cb93392011-03-12 18:10:44 +00001370 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001371 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001372 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001373 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1374 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1375 ){
drh3cb93392011-03-12 18:10:44 +00001376 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001377 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001378 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001379 lock.l_whence = SEEK_SET;
1380 lock.l_start = SHARED_FIRST;
1381 lock.l_len = SHARED_SIZE;
1382 lock.l_type = F_WRLCK;
1383 rc = osFcntl(pFile->h, F_SETLK, &lock);
1384 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001385 pInode->bProcessLock = 1;
1386 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001387 }else{
1388 rc = 0;
1389 }
1390 }else{
1391 rc = osFcntl(pFile->h, F_SETLK, pLock);
1392 }
1393 return rc;
1394}
1395
1396/*
drh308c2a52010-05-14 11:30:18 +00001397** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001398** of the following:
1399**
drh2ac3ee92004-06-07 16:27:46 +00001400** (1) SHARED_LOCK
1401** (2) RESERVED_LOCK
1402** (3) PENDING_LOCK
1403** (4) EXCLUSIVE_LOCK
1404**
drhb3e04342004-06-08 00:47:47 +00001405** Sometimes when requesting one lock state, additional lock states
1406** are inserted in between. The locking might fail on one of the later
1407** transitions leaving the lock state different from what it started but
1408** still short of its goal. The following chart shows the allowed
1409** transitions and the inserted intermediate states:
1410**
1411** UNLOCKED -> SHARED
1412** SHARED -> RESERVED
1413** SHARED -> (PENDING) -> EXCLUSIVE
1414** RESERVED -> (PENDING) -> EXCLUSIVE
1415** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001416**
drha6abd042004-06-09 17:37:22 +00001417** This routine will only increase a lock. Use the sqlite3OsUnlock()
1418** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001419*/
drh308c2a52010-05-14 11:30:18 +00001420static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001421 /* The following describes the implementation of the various locks and
1422 ** lock transitions in terms of the POSIX advisory shared and exclusive
1423 ** lock primitives (called read-locks and write-locks below, to avoid
1424 ** confusion with SQLite lock names). The algorithms are complicated
1425 ** slightly in order to be compatible with windows systems simultaneously
1426 ** accessing the same database file, in case that is ever required.
1427 **
1428 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1429 ** byte', each single bytes at well known offsets, and the 'shared byte
1430 ** range', a range of 510 bytes at a well known offset.
1431 **
1432 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1433 ** byte'. If this is successful, a random byte from the 'shared byte
1434 ** range' is read-locked and the lock on the 'pending byte' released.
1435 **
danielk197790ba3bd2004-06-25 08:32:25 +00001436 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1437 ** A RESERVED lock is implemented by grabbing a write-lock on the
1438 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001439 **
1440 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001441 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1442 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1443 ** obtained, but existing SHARED locks are allowed to persist. A process
1444 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1445 ** This property is used by the algorithm for rolling back a journal file
1446 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001447 **
danielk197790ba3bd2004-06-25 08:32:25 +00001448 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1449 ** implemented by obtaining a write-lock on the entire 'shared byte
1450 ** range'. Since all other locks require a read-lock on one of the bytes
1451 ** within this range, this ensures that no other locks are held on the
1452 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001453 **
1454 ** The reason a single byte cannot be used instead of the 'shared byte
1455 ** range' is that some versions of windows do not support read-locks. By
1456 ** locking a random byte from a range, concurrent SHARED locks may exist
1457 ** even if the locking primitive used is always a write-lock.
1458 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001459 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001460 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001461 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001462 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001463 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001464
drh054889e2005-11-30 03:20:31 +00001465 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001466 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1467 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001468 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001469
1470 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001471 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001472 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001473 */
drh308c2a52010-05-14 11:30:18 +00001474 if( pFile->eFileLock>=eFileLock ){
1475 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1476 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001477 return SQLITE_OK;
1478 }
1479
drh0c2694b2009-09-03 16:23:44 +00001480 /* Make sure the locking sequence is correct.
1481 ** (1) We never move from unlocked to anything higher than shared lock.
1482 ** (2) SQLite never explicitly requests a pendig lock.
1483 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001484 */
drh308c2a52010-05-14 11:30:18 +00001485 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1486 assert( eFileLock!=PENDING_LOCK );
1487 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001488
drh8af6c222010-05-14 12:43:01 +00001489 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001490 */
drh6c7d5c52008-11-21 20:32:33 +00001491 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001492 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001493
danielk1977ad94b582007-08-20 06:44:22 +00001494 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001495 ** handle that precludes the requested lock, return BUSY.
1496 */
drh8af6c222010-05-14 12:43:01 +00001497 if( (pFile->eFileLock!=pInode->eFileLock &&
1498 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 ){
1500 rc = SQLITE_BUSY;
1501 goto end_lock;
1502 }
1503
1504 /* If a SHARED lock is requested, and some thread using this PID already
1505 ** has a SHARED or RESERVED lock, then increment reference counts and
1506 ** return SQLITE_OK.
1507 */
drh308c2a52010-05-14 11:30:18 +00001508 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001509 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001510 assert( eFileLock==SHARED_LOCK );
1511 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001512 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001513 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001514 pInode->nShared++;
1515 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001516 goto end_lock;
1517 }
1518
danielk19779a1d0ab2004-06-01 14:09:28 +00001519
drh3cde3bb2004-06-12 02:17:14 +00001520 /* A PENDING lock is needed before acquiring a SHARED lock and before
1521 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1522 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001523 */
drh0c2694b2009-09-03 16:23:44 +00001524 lock.l_len = 1L;
1525 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001526 if( eFileLock==SHARED_LOCK
1527 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001528 ){
drh308c2a52010-05-14 11:30:18 +00001529 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001530 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001531 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001532 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001533 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001534 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001535 pFile->lastErrno = tErrno;
1536 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 goto end_lock;
1538 }
drh3cde3bb2004-06-12 02:17:14 +00001539 }
1540
1541
1542 /* If control gets to this point, then actually go ahead and make
1543 ** operating system calls for the specified lock.
1544 */
drh308c2a52010-05-14 11:30:18 +00001545 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001546 assert( pInode->nShared==0 );
1547 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001548 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001549
drh2ac3ee92004-06-07 16:27:46 +00001550 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001551 lock.l_start = SHARED_FIRST;
1552 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001553 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001554 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001555 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001556 }
dan661d71a2011-03-30 19:08:03 +00001557
drh2ac3ee92004-06-07 16:27:46 +00001558 /* Drop the temporary PENDING lock */
1559 lock.l_start = PENDING_BYTE;
1560 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001561 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001562 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1563 /* This could happen with a network mount */
1564 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001565 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001566 }
dan661d71a2011-03-30 19:08:03 +00001567
1568 if( rc ){
1569 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001570 pFile->lastErrno = tErrno;
1571 }
dan661d71a2011-03-30 19:08:03 +00001572 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001573 }else{
drh308c2a52010-05-14 11:30:18 +00001574 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001575 pInode->nLock++;
1576 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001577 }
drh8af6c222010-05-14 12:43:01 +00001578 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001579 /* We are trying for an exclusive lock but another thread in this
1580 ** same process is still holding a shared lock. */
1581 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001582 }else{
drh3cde3bb2004-06-12 02:17:14 +00001583 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001584 ** assumed that there is a SHARED or greater lock on the file
1585 ** already.
1586 */
drh308c2a52010-05-14 11:30:18 +00001587 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001588 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001589
1590 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1591 if( eFileLock==RESERVED_LOCK ){
1592 lock.l_start = RESERVED_BYTE;
1593 lock.l_len = 1L;
1594 }else{
1595 lock.l_start = SHARED_FIRST;
1596 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001597 }
dan661d71a2011-03-30 19:08:03 +00001598
1599 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001600 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001601 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001602 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001603 pFile->lastErrno = tErrno;
1604 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001605 }
drhbbd42a62004-05-22 17:41:58 +00001606 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001607
drh8f941bc2009-01-14 23:03:40 +00001608
drhd3d8c042012-05-29 17:02:40 +00001609#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001610 /* Set up the transaction-counter change checking flags when
1611 ** transitioning from a SHARED to a RESERVED lock. The change
1612 ** from SHARED to RESERVED marks the beginning of a normal
1613 ** write operation (not a hot journal rollback).
1614 */
1615 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001616 && pFile->eFileLock<=SHARED_LOCK
1617 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001618 ){
1619 pFile->transCntrChng = 0;
1620 pFile->dbUpdate = 0;
1621 pFile->inNormalWrite = 1;
1622 }
1623#endif
1624
1625
danielk1977ecb2a962004-06-02 06:30:16 +00001626 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001627 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001628 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001629 }else if( eFileLock==EXCLUSIVE_LOCK ){
1630 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001631 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001632 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001633
1634end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001635 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001636 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1637 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001638 return rc;
1639}
1640
1641/*
dan08da86a2009-08-21 17:18:03 +00001642** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001643** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001644*/
1645static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001646 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001647 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001648 p->pNext = pInode->pUnused;
1649 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001650 pFile->h = -1;
1651 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001652}
1653
1654/*
drh308c2a52010-05-14 11:30:18 +00001655** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001656** must be either NO_LOCK or SHARED_LOCK.
1657**
1658** If the locking level of the file descriptor is already at or below
1659** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001660**
1661** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1662** the byte range is divided into 2 parts and the first part is unlocked then
1663** set to a read lock, then the other part is simply unlocked. This works
1664** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1665** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001666*/
drha7e61d82011-03-12 17:02:57 +00001667static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001668 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001669 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001670 struct flock lock;
1671 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001672
drh054889e2005-11-30 03:20:31 +00001673 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001674 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001675 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001676 getpid()));
drha6abd042004-06-09 17:37:22 +00001677
drh308c2a52010-05-14 11:30:18 +00001678 assert( eFileLock<=SHARED_LOCK );
1679 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001680 return SQLITE_OK;
1681 }
drh6c7d5c52008-11-21 20:32:33 +00001682 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001683 pInode = pFile->pInode;
1684 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001685 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001686 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001687
drhd3d8c042012-05-29 17:02:40 +00001688#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001689 /* When reducing a lock such that other processes can start
1690 ** reading the database file again, make sure that the
1691 ** transaction counter was updated if any part of the database
1692 ** file changed. If the transaction counter is not updated,
1693 ** other connections to the same file might not realize that
1694 ** the file has changed and hence might not know to flush their
1695 ** cache. The use of a stale cache can lead to database corruption.
1696 */
drh8f941bc2009-01-14 23:03:40 +00001697 pFile->inNormalWrite = 0;
1698#endif
1699
drh7ed97b92010-01-20 13:07:21 +00001700 /* downgrading to a shared lock on NFS involves clearing the write lock
1701 ** before establishing the readlock - to avoid a race condition we downgrade
1702 ** the lock in 2 blocks, so that part of the range will be covered by a
1703 ** write lock until the rest is covered by a read lock:
1704 ** 1: [WWWWW]
1705 ** 2: [....W]
1706 ** 3: [RRRRW]
1707 ** 4: [RRRR.]
1708 */
drh308c2a52010-05-14 11:30:18 +00001709 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001710
1711#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001712 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001713 assert( handleNFSUnlock==0 );
1714#endif
1715#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001716 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001717 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001718 off_t divSize = SHARED_SIZE - 1;
1719
1720 lock.l_type = F_UNLCK;
1721 lock.l_whence = SEEK_SET;
1722 lock.l_start = SHARED_FIRST;
1723 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001724 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001725 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001726 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001727 if( IS_LOCK_ERROR(rc) ){
1728 pFile->lastErrno = tErrno;
1729 }
1730 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001731 }
drh7ed97b92010-01-20 13:07:21 +00001732 lock.l_type = F_RDLCK;
1733 lock.l_whence = SEEK_SET;
1734 lock.l_start = SHARED_FIRST;
1735 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001736 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001737 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001738 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1739 if( IS_LOCK_ERROR(rc) ){
1740 pFile->lastErrno = tErrno;
1741 }
1742 goto end_unlock;
1743 }
1744 lock.l_type = F_UNLCK;
1745 lock.l_whence = SEEK_SET;
1746 lock.l_start = SHARED_FIRST+divSize;
1747 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001748 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001749 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001750 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001751 if( IS_LOCK_ERROR(rc) ){
1752 pFile->lastErrno = tErrno;
1753 }
1754 goto end_unlock;
1755 }
drh30f776f2011-02-25 03:25:07 +00001756 }else
1757#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1758 {
drh7ed97b92010-01-20 13:07:21 +00001759 lock.l_type = F_RDLCK;
1760 lock.l_whence = SEEK_SET;
1761 lock.l_start = SHARED_FIRST;
1762 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001763 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001764 /* In theory, the call to unixFileLock() cannot fail because another
1765 ** process is holding an incompatible lock. If it does, this
1766 ** indicates that the other process is not following the locking
1767 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1768 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1769 ** an assert to fail). */
1770 rc = SQLITE_IOERR_RDLOCK;
1771 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001772 goto end_unlock;
1773 }
drh9c105bb2004-10-02 20:38:28 +00001774 }
1775 }
drhbbd42a62004-05-22 17:41:58 +00001776 lock.l_type = F_UNLCK;
1777 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001778 lock.l_start = PENDING_BYTE;
1779 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001780 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001781 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001782 }else{
danea83bc62011-04-01 11:56:32 +00001783 rc = SQLITE_IOERR_UNLOCK;
1784 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001785 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001786 }
drhbbd42a62004-05-22 17:41:58 +00001787 }
drh308c2a52010-05-14 11:30:18 +00001788 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001789 /* Decrement the shared lock counter. Release the lock using an
1790 ** OS call only when all threads in this same process have released
1791 ** the lock.
1792 */
drh8af6c222010-05-14 12:43:01 +00001793 pInode->nShared--;
1794 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001795 lock.l_type = F_UNLCK;
1796 lock.l_whence = SEEK_SET;
1797 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001798 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001799 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001800 }else{
danea83bc62011-04-01 11:56:32 +00001801 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001802 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001803 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001804 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001805 }
drha6abd042004-06-09 17:37:22 +00001806 }
1807
drhbbd42a62004-05-22 17:41:58 +00001808 /* Decrement the count of locks against this same file. When the
1809 ** count reaches zero, close any other file descriptors whose close
1810 ** was deferred because of outstanding locks.
1811 */
drh8af6c222010-05-14 12:43:01 +00001812 pInode->nLock--;
1813 assert( pInode->nLock>=0 );
1814 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001815 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001816 }
1817 }
drhf2f105d2012-08-20 15:53:54 +00001818
aswift5b1a2562008-08-22 00:22:35 +00001819end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001820 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001821 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001822 return rc;
drhbbd42a62004-05-22 17:41:58 +00001823}
1824
1825/*
drh308c2a52010-05-14 11:30:18 +00001826** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001827** must be either NO_LOCK or SHARED_LOCK.
1828**
1829** If the locking level of the file descriptor is already at or below
1830** the requested locking level, this routine is a no-op.
1831*/
drh308c2a52010-05-14 11:30:18 +00001832static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001833 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001834 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001835}
1836
danf23da962013-03-23 21:00:41 +00001837static int unixMapfile(unixFile *pFd, i64 nByte);
1838static void unixUnmapfile(unixFile *pFd);
1839
drh7ed97b92010-01-20 13:07:21 +00001840/*
danielk1977e339d652008-06-28 11:23:00 +00001841** This function performs the parts of the "close file" operation
1842** common to all locking schemes. It closes the directory and file
1843** handles, if they are valid, and sets all fields of the unixFile
1844** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001845**
1846** It is *not* necessary to hold the mutex when this routine is called,
1847** even on VxWorks. A mutex will be acquired on VxWorks by the
1848** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001849*/
1850static int closeUnixFile(sqlite3_file *id){
1851 unixFile *pFile = (unixFile*)id;
danf23da962013-03-23 21:00:41 +00001852 unixUnmapfile(pFile);
dan661d71a2011-03-30 19:08:03 +00001853 if( pFile->h>=0 ){
1854 robust_close(pFile, pFile->h, __LINE__);
1855 pFile->h = -1;
1856 }
1857#if OS_VXWORKS
1858 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001859 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001860 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001861 }
1862 vxworksReleaseFileId(pFile->pId);
1863 pFile->pId = 0;
1864 }
1865#endif
1866 OSTRACE(("CLOSE %-3d\n", pFile->h));
1867 OpenCounter(-1);
1868 sqlite3_free(pFile->pUnused);
1869 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001870 return SQLITE_OK;
1871}
1872
1873/*
danielk1977e3026632004-06-22 11:29:02 +00001874** Close a file.
1875*/
danielk197762079062007-08-15 17:08:46 +00001876static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001877 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001878 unixFile *pFile = (unixFile *)id;
1879 unixUnlock(id, NO_LOCK);
1880 unixEnterMutex();
1881
1882 /* unixFile.pInode is always valid here. Otherwise, a different close
1883 ** routine (e.g. nolockClose()) would be called instead.
1884 */
1885 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1886 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1887 /* If there are outstanding locks, do not actually close the file just
1888 ** yet because that would clear those locks. Instead, add the file
1889 ** descriptor to pInode->pUnused list. It will be automatically closed
1890 ** when the last lock is cleared.
1891 */
1892 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001893 }
dan661d71a2011-03-30 19:08:03 +00001894 releaseInodeInfo(pFile);
1895 rc = closeUnixFile(id);
1896 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001897 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001898}
1899
drh734c9862008-11-28 15:37:20 +00001900/************** End of the posix advisory lock implementation *****************
1901******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001902
drh734c9862008-11-28 15:37:20 +00001903/******************************************************************************
1904****************************** No-op Locking **********************************
1905**
1906** Of the various locking implementations available, this is by far the
1907** simplest: locking is ignored. No attempt is made to lock the database
1908** file for reading or writing.
1909**
1910** This locking mode is appropriate for use on read-only databases
1911** (ex: databases that are burned into CD-ROM, for example.) It can
1912** also be used if the application employs some external mechanism to
1913** prevent simultaneous access of the same database by two or more
1914** database connections. But there is a serious risk of database
1915** corruption if this locking mode is used in situations where multiple
1916** database connections are accessing the same database file at the same
1917** time and one or more of those connections are writing.
1918*/
drhbfe66312006-10-03 17:40:40 +00001919
drh734c9862008-11-28 15:37:20 +00001920static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1921 UNUSED_PARAMETER(NotUsed);
1922 *pResOut = 0;
1923 return SQLITE_OK;
1924}
drh734c9862008-11-28 15:37:20 +00001925static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1926 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1927 return SQLITE_OK;
1928}
drh734c9862008-11-28 15:37:20 +00001929static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1930 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1931 return SQLITE_OK;
1932}
1933
1934/*
drh9b35ea62008-11-29 02:20:26 +00001935** Close the file.
drh734c9862008-11-28 15:37:20 +00001936*/
1937static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001938 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001939}
1940
1941/******************* End of the no-op lock implementation *********************
1942******************************************************************************/
1943
1944/******************************************************************************
1945************************* Begin dot-file Locking ******************************
1946**
mistachkin48864df2013-03-21 21:20:32 +00001947** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001948** files (really a directory) to control access to the database. This works
1949** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001950**
1951** (1) There is zero concurrency. A single reader blocks all other
1952** connections from reading or writing the database.
1953**
1954** (2) An application crash or power loss can leave stale lock files
1955** sitting around that need to be cleared manually.
1956**
1957** Nevertheless, a dotlock is an appropriate locking mode for use if no
1958** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001959**
drh9ef6bc42011-11-04 02:24:02 +00001960** Dotfile locking works by creating a subdirectory in the same directory as
1961** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00001962** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00001963** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001964*/
1965
1966/*
1967** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001968** lock directory.
drh734c9862008-11-28 15:37:20 +00001969*/
1970#define DOTLOCK_SUFFIX ".lock"
1971
drh7708e972008-11-29 00:56:52 +00001972/*
1973** This routine checks if there is a RESERVED lock held on the specified
1974** file by this or any other process. If such a lock is held, set *pResOut
1975** to a non-zero value otherwise *pResOut is set to zero. The return value
1976** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1977**
1978** In dotfile locking, either a lock exists or it does not. So in this
1979** variation of CheckReservedLock(), *pResOut is set to true if any lock
1980** is held on the file and false if the file is unlocked.
1981*/
drh734c9862008-11-28 15:37:20 +00001982static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1983 int rc = SQLITE_OK;
1984 int reserved = 0;
1985 unixFile *pFile = (unixFile*)id;
1986
1987 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1988
1989 assert( pFile );
1990
1991 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001992 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001993 /* Either this connection or some other connection in the same process
1994 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001995 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001996 }else{
1997 /* The lock is held if and only if the lockfile exists */
1998 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001999 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002000 }
drh308c2a52010-05-14 11:30:18 +00002001 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002002 *pResOut = reserved;
2003 return rc;
2004}
2005
drh7708e972008-11-29 00:56:52 +00002006/*
drh308c2a52010-05-14 11:30:18 +00002007** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002008** of the following:
2009**
2010** (1) SHARED_LOCK
2011** (2) RESERVED_LOCK
2012** (3) PENDING_LOCK
2013** (4) EXCLUSIVE_LOCK
2014**
2015** Sometimes when requesting one lock state, additional lock states
2016** are inserted in between. The locking might fail on one of the later
2017** transitions leaving the lock state different from what it started but
2018** still short of its goal. The following chart shows the allowed
2019** transitions and the inserted intermediate states:
2020**
2021** UNLOCKED -> SHARED
2022** SHARED -> RESERVED
2023** SHARED -> (PENDING) -> EXCLUSIVE
2024** RESERVED -> (PENDING) -> EXCLUSIVE
2025** PENDING -> EXCLUSIVE
2026**
2027** This routine will only increase a lock. Use the sqlite3OsUnlock()
2028** routine to lower a locking level.
2029**
2030** With dotfile locking, we really only support state (4): EXCLUSIVE.
2031** But we track the other locking levels internally.
2032*/
drh308c2a52010-05-14 11:30:18 +00002033static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002034 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002035 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002036 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002037
drh7708e972008-11-29 00:56:52 +00002038
2039 /* If we have any lock, then the lock file already exists. All we have
2040 ** to do is adjust our internal record of the lock level.
2041 */
drh308c2a52010-05-14 11:30:18 +00002042 if( pFile->eFileLock > NO_LOCK ){
2043 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002044 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002045#ifdef HAVE_UTIME
2046 utime(zLockFile, NULL);
2047#else
drh734c9862008-11-28 15:37:20 +00002048 utimes(zLockFile, NULL);
2049#endif
drh7708e972008-11-29 00:56:52 +00002050 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002051 }
2052
2053 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002054 rc = osMkdir(zLockFile, 0777);
2055 if( rc<0 ){
2056 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002057 int tErrno = errno;
2058 if( EEXIST == tErrno ){
2059 rc = SQLITE_BUSY;
2060 } else {
2061 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2062 if( IS_LOCK_ERROR(rc) ){
2063 pFile->lastErrno = tErrno;
2064 }
2065 }
drh7708e972008-11-29 00:56:52 +00002066 return rc;
drh734c9862008-11-28 15:37:20 +00002067 }
drh734c9862008-11-28 15:37:20 +00002068
2069 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002070 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002071 return rc;
2072}
2073
drh7708e972008-11-29 00:56:52 +00002074/*
drh308c2a52010-05-14 11:30:18 +00002075** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002076** must be either NO_LOCK or SHARED_LOCK.
2077**
2078** If the locking level of the file descriptor is already at or below
2079** the requested locking level, this routine is a no-op.
2080**
2081** When the locking level reaches NO_LOCK, delete the lock file.
2082*/
drh308c2a52010-05-14 11:30:18 +00002083static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002084 unixFile *pFile = (unixFile*)id;
2085 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002086 int rc;
drh734c9862008-11-28 15:37:20 +00002087
2088 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002089 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002090 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002091 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002092
2093 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002094 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002095 return SQLITE_OK;
2096 }
drh7708e972008-11-29 00:56:52 +00002097
2098 /* To downgrade to shared, simply update our internal notion of the
2099 ** lock state. No need to mess with the file on disk.
2100 */
drh308c2a52010-05-14 11:30:18 +00002101 if( eFileLock==SHARED_LOCK ){
2102 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002103 return SQLITE_OK;
2104 }
2105
drh7708e972008-11-29 00:56:52 +00002106 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002107 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002108 rc = osRmdir(zLockFile);
2109 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2110 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002111 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002112 rc = 0;
drh734c9862008-11-28 15:37:20 +00002113 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002114 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002115 }
2116 if( IS_LOCK_ERROR(rc) ){
2117 pFile->lastErrno = tErrno;
2118 }
2119 return rc;
2120 }
drh308c2a52010-05-14 11:30:18 +00002121 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002122 return SQLITE_OK;
2123}
2124
2125/*
drh9b35ea62008-11-29 02:20:26 +00002126** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002127*/
2128static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002129 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002130 if( id ){
2131 unixFile *pFile = (unixFile*)id;
2132 dotlockUnlock(id, NO_LOCK);
2133 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002134 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002135 }
drh734c9862008-11-28 15:37:20 +00002136 return rc;
2137}
2138/****************** End of the dot-file lock implementation *******************
2139******************************************************************************/
2140
2141/******************************************************************************
2142************************** Begin flock Locking ********************************
2143**
2144** Use the flock() system call to do file locking.
2145**
drh6b9d6dd2008-12-03 19:34:47 +00002146** flock() locking is like dot-file locking in that the various
2147** fine-grain locking levels supported by SQLite are collapsed into
2148** a single exclusive lock. In other words, SHARED, RESERVED, and
2149** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2150** still works when you do this, but concurrency is reduced since
2151** only a single process can be reading the database at a time.
2152**
drh734c9862008-11-28 15:37:20 +00002153** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2154** compiling for VXWORKS.
2155*/
2156#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002157
drh6b9d6dd2008-12-03 19:34:47 +00002158/*
drhff812312011-02-23 13:33:46 +00002159** Retry flock() calls that fail with EINTR
2160*/
2161#ifdef EINTR
2162static int robust_flock(int fd, int op){
2163 int rc;
2164 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2165 return rc;
2166}
2167#else
drh5c819272011-02-23 14:00:12 +00002168# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002169#endif
2170
2171
2172/*
drh6b9d6dd2008-12-03 19:34:47 +00002173** This routine checks if there is a RESERVED lock held on the specified
2174** file by this or any other process. If such a lock is held, set *pResOut
2175** to a non-zero value otherwise *pResOut is set to zero. The return value
2176** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2177*/
drh734c9862008-11-28 15:37:20 +00002178static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2179 int rc = SQLITE_OK;
2180 int reserved = 0;
2181 unixFile *pFile = (unixFile*)id;
2182
2183 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2184
2185 assert( pFile );
2186
2187 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002188 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002189 reserved = 1;
2190 }
2191
2192 /* Otherwise see if some other process holds it. */
2193 if( !reserved ){
2194 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002195 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002196 if( !lrc ){
2197 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002198 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002199 if ( lrc ) {
2200 int tErrno = errno;
2201 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002202 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002203 if( IS_LOCK_ERROR(lrc) ){
2204 pFile->lastErrno = tErrno;
2205 rc = lrc;
2206 }
2207 }
2208 } else {
2209 int tErrno = errno;
2210 reserved = 1;
2211 /* someone else might have it reserved */
2212 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2213 if( IS_LOCK_ERROR(lrc) ){
2214 pFile->lastErrno = tErrno;
2215 rc = lrc;
2216 }
2217 }
2218 }
drh308c2a52010-05-14 11:30:18 +00002219 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002220
2221#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2222 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2223 rc = SQLITE_OK;
2224 reserved=1;
2225 }
2226#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2227 *pResOut = reserved;
2228 return rc;
2229}
2230
drh6b9d6dd2008-12-03 19:34:47 +00002231/*
drh308c2a52010-05-14 11:30:18 +00002232** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002233** of the following:
2234**
2235** (1) SHARED_LOCK
2236** (2) RESERVED_LOCK
2237** (3) PENDING_LOCK
2238** (4) EXCLUSIVE_LOCK
2239**
2240** Sometimes when requesting one lock state, additional lock states
2241** are inserted in between. The locking might fail on one of the later
2242** transitions leaving the lock state different from what it started but
2243** still short of its goal. The following chart shows the allowed
2244** transitions and the inserted intermediate states:
2245**
2246** UNLOCKED -> SHARED
2247** SHARED -> RESERVED
2248** SHARED -> (PENDING) -> EXCLUSIVE
2249** RESERVED -> (PENDING) -> EXCLUSIVE
2250** PENDING -> EXCLUSIVE
2251**
2252** flock() only really support EXCLUSIVE locks. We track intermediate
2253** lock states in the sqlite3_file structure, but all locks SHARED or
2254** above are really EXCLUSIVE locks and exclude all other processes from
2255** access the file.
2256**
2257** This routine will only increase a lock. Use the sqlite3OsUnlock()
2258** routine to lower a locking level.
2259*/
drh308c2a52010-05-14 11:30:18 +00002260static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002261 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002262 unixFile *pFile = (unixFile*)id;
2263
2264 assert( pFile );
2265
2266 /* if we already have a lock, it is exclusive.
2267 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002268 if (pFile->eFileLock > NO_LOCK) {
2269 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002270 return SQLITE_OK;
2271 }
2272
2273 /* grab an exclusive lock */
2274
drhff812312011-02-23 13:33:46 +00002275 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002276 int tErrno = errno;
2277 /* didn't get, must be busy */
2278 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2279 if( IS_LOCK_ERROR(rc) ){
2280 pFile->lastErrno = tErrno;
2281 }
2282 } else {
2283 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002284 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002285 }
drh308c2a52010-05-14 11:30:18 +00002286 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2287 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002288#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2289 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2290 rc = SQLITE_BUSY;
2291 }
2292#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2293 return rc;
2294}
2295
drh6b9d6dd2008-12-03 19:34:47 +00002296
2297/*
drh308c2a52010-05-14 11:30:18 +00002298** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002299** must be either NO_LOCK or SHARED_LOCK.
2300**
2301** If the locking level of the file descriptor is already at or below
2302** the requested locking level, this routine is a no-op.
2303*/
drh308c2a52010-05-14 11:30:18 +00002304static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002305 unixFile *pFile = (unixFile*)id;
2306
2307 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002308 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2309 pFile->eFileLock, getpid()));
2310 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002311
2312 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002313 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002314 return SQLITE_OK;
2315 }
2316
2317 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002318 if (eFileLock==SHARED_LOCK) {
2319 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002320 return SQLITE_OK;
2321 }
2322
2323 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002324 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002325#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002326 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002327#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002328 return SQLITE_IOERR_UNLOCK;
2329 }else{
drh308c2a52010-05-14 11:30:18 +00002330 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002331 return SQLITE_OK;
2332 }
2333}
2334
2335/*
2336** Close a file.
2337*/
2338static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002339 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002340 if( id ){
2341 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002342 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002343 }
drh5a05be12012-10-09 18:51:44 +00002344 return rc;
drh734c9862008-11-28 15:37:20 +00002345}
2346
2347#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2348
2349/******************* End of the flock lock implementation *********************
2350******************************************************************************/
2351
2352/******************************************************************************
2353************************ Begin Named Semaphore Locking ************************
2354**
2355** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002356**
2357** Semaphore locking is like dot-lock and flock in that it really only
2358** supports EXCLUSIVE locking. Only a single process can read or write
2359** the database file at a time. This reduces potential concurrency, but
2360** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002361*/
2362#if OS_VXWORKS
2363
drh6b9d6dd2008-12-03 19:34:47 +00002364/*
2365** This routine checks if there is a RESERVED lock held on the specified
2366** file by this or any other process. If such a lock is held, set *pResOut
2367** to a non-zero value otherwise *pResOut is set to zero. The return value
2368** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2369*/
drh734c9862008-11-28 15:37:20 +00002370static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2371 int rc = SQLITE_OK;
2372 int reserved = 0;
2373 unixFile *pFile = (unixFile*)id;
2374
2375 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2376
2377 assert( pFile );
2378
2379 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002380 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002381 reserved = 1;
2382 }
2383
2384 /* Otherwise see if some other process holds it. */
2385 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002386 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002387 struct stat statBuf;
2388
2389 if( sem_trywait(pSem)==-1 ){
2390 int tErrno = errno;
2391 if( EAGAIN != tErrno ){
2392 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2393 pFile->lastErrno = tErrno;
2394 } else {
2395 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002396 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002397 }
2398 }else{
2399 /* we could have it if we want it */
2400 sem_post(pSem);
2401 }
2402 }
drh308c2a52010-05-14 11:30:18 +00002403 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002404
2405 *pResOut = reserved;
2406 return rc;
2407}
2408
drh6b9d6dd2008-12-03 19:34:47 +00002409/*
drh308c2a52010-05-14 11:30:18 +00002410** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002411** of the following:
2412**
2413** (1) SHARED_LOCK
2414** (2) RESERVED_LOCK
2415** (3) PENDING_LOCK
2416** (4) EXCLUSIVE_LOCK
2417**
2418** Sometimes when requesting one lock state, additional lock states
2419** are inserted in between. The locking might fail on one of the later
2420** transitions leaving the lock state different from what it started but
2421** still short of its goal. The following chart shows the allowed
2422** transitions and the inserted intermediate states:
2423**
2424** UNLOCKED -> SHARED
2425** SHARED -> RESERVED
2426** SHARED -> (PENDING) -> EXCLUSIVE
2427** RESERVED -> (PENDING) -> EXCLUSIVE
2428** PENDING -> EXCLUSIVE
2429**
2430** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2431** lock states in the sqlite3_file structure, but all locks SHARED or
2432** above are really EXCLUSIVE locks and exclude all other processes from
2433** access the file.
2434**
2435** This routine will only increase a lock. Use the sqlite3OsUnlock()
2436** routine to lower a locking level.
2437*/
drh308c2a52010-05-14 11:30:18 +00002438static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002439 unixFile *pFile = (unixFile*)id;
2440 int fd;
drh8af6c222010-05-14 12:43:01 +00002441 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002442 int rc = SQLITE_OK;
2443
2444 /* if we already have a lock, it is exclusive.
2445 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002446 if (pFile->eFileLock > NO_LOCK) {
2447 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002448 rc = SQLITE_OK;
2449 goto sem_end_lock;
2450 }
2451
2452 /* lock semaphore now but bail out when already locked. */
2453 if( sem_trywait(pSem)==-1 ){
2454 rc = SQLITE_BUSY;
2455 goto sem_end_lock;
2456 }
2457
2458 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002459 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002460
2461 sem_end_lock:
2462 return rc;
2463}
2464
drh6b9d6dd2008-12-03 19:34:47 +00002465/*
drh308c2a52010-05-14 11:30:18 +00002466** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002467** must be either NO_LOCK or SHARED_LOCK.
2468**
2469** If the locking level of the file descriptor is already at or below
2470** the requested locking level, this routine is a no-op.
2471*/
drh308c2a52010-05-14 11:30:18 +00002472static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002473 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002474 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002475
2476 assert( pFile );
2477 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002478 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002479 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002480 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002481
2482 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002483 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002484 return SQLITE_OK;
2485 }
2486
2487 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002488 if (eFileLock==SHARED_LOCK) {
2489 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002490 return SQLITE_OK;
2491 }
2492
2493 /* no, really unlock. */
2494 if ( sem_post(pSem)==-1 ) {
2495 int rc, tErrno = errno;
2496 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2497 if( IS_LOCK_ERROR(rc) ){
2498 pFile->lastErrno = tErrno;
2499 }
2500 return rc;
2501 }
drh308c2a52010-05-14 11:30:18 +00002502 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002503 return SQLITE_OK;
2504}
2505
2506/*
2507 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002508 */
drh734c9862008-11-28 15:37:20 +00002509static int semClose(sqlite3_file *id) {
2510 if( id ){
2511 unixFile *pFile = (unixFile*)id;
2512 semUnlock(id, NO_LOCK);
2513 assert( pFile );
2514 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002515 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002516 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002517 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002518 }
2519 return SQLITE_OK;
2520}
2521
2522#endif /* OS_VXWORKS */
2523/*
2524** Named semaphore locking is only available on VxWorks.
2525**
2526*************** End of the named semaphore lock implementation ****************
2527******************************************************************************/
2528
2529
2530/******************************************************************************
2531*************************** Begin AFP Locking *********************************
2532**
2533** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2534** on Apple Macintosh computers - both OS9 and OSX.
2535**
2536** Third-party implementations of AFP are available. But this code here
2537** only works on OSX.
2538*/
2539
drhd2cb50b2009-01-09 21:41:17 +00002540#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002541/*
2542** The afpLockingContext structure contains all afp lock specific state
2543*/
drhbfe66312006-10-03 17:40:40 +00002544typedef struct afpLockingContext afpLockingContext;
2545struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002546 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002547 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002548};
2549
2550struct ByteRangeLockPB2
2551{
2552 unsigned long long offset; /* offset to first byte to lock */
2553 unsigned long long length; /* nbr of bytes to lock */
2554 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2555 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2556 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2557 int fd; /* file desc to assoc this lock with */
2558};
2559
drhfd131da2007-08-07 17:13:03 +00002560#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002561
drh6b9d6dd2008-12-03 19:34:47 +00002562/*
2563** This is a utility for setting or clearing a bit-range lock on an
2564** AFP filesystem.
2565**
2566** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2567*/
2568static int afpSetLock(
2569 const char *path, /* Name of the file to be locked or unlocked */
2570 unixFile *pFile, /* Open file descriptor on path */
2571 unsigned long long offset, /* First byte to be locked */
2572 unsigned long long length, /* Number of bytes to lock */
2573 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002574){
drh6b9d6dd2008-12-03 19:34:47 +00002575 struct ByteRangeLockPB2 pb;
2576 int err;
drhbfe66312006-10-03 17:40:40 +00002577
2578 pb.unLockFlag = setLockFlag ? 0 : 1;
2579 pb.startEndFlag = 0;
2580 pb.offset = offset;
2581 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002582 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002583
drh308c2a52010-05-14 11:30:18 +00002584 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002585 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002586 offset, length));
drhbfe66312006-10-03 17:40:40 +00002587 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2588 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002589 int rc;
2590 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002591 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2592 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002593#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2594 rc = SQLITE_BUSY;
2595#else
drh734c9862008-11-28 15:37:20 +00002596 rc = sqliteErrorFromPosixError(tErrno,
2597 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002598#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002599 if( IS_LOCK_ERROR(rc) ){
2600 pFile->lastErrno = tErrno;
2601 }
2602 return rc;
drhbfe66312006-10-03 17:40:40 +00002603 } else {
aswift5b1a2562008-08-22 00:22:35 +00002604 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002605 }
2606}
2607
drh6b9d6dd2008-12-03 19:34:47 +00002608/*
2609** This routine checks if there is a RESERVED lock held on the specified
2610** file by this or any other process. If such a lock is held, set *pResOut
2611** to a non-zero value otherwise *pResOut is set to zero. The return value
2612** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2613*/
danielk1977e339d652008-06-28 11:23:00 +00002614static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002615 int rc = SQLITE_OK;
2616 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002617 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002618 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002619
aswift5b1a2562008-08-22 00:22:35 +00002620 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2621
2622 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002623 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002624 if( context->reserved ){
2625 *pResOut = 1;
2626 return SQLITE_OK;
2627 }
drh8af6c222010-05-14 12:43:01 +00002628 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002629
2630 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002631 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002632 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002633 }
2634
2635 /* Otherwise see if some other process holds it.
2636 */
aswift5b1a2562008-08-22 00:22:35 +00002637 if( !reserved ){
2638 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002639 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002640 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002641 /* if we succeeded in taking the reserved lock, unlock it to restore
2642 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002643 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002644 } else {
2645 /* if we failed to get the lock then someone else must have it */
2646 reserved = 1;
2647 }
2648 if( IS_LOCK_ERROR(lrc) ){
2649 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002650 }
2651 }
drhbfe66312006-10-03 17:40:40 +00002652
drh7ed97b92010-01-20 13:07:21 +00002653 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002654 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002655
2656 *pResOut = reserved;
2657 return rc;
drhbfe66312006-10-03 17:40:40 +00002658}
2659
drh6b9d6dd2008-12-03 19:34:47 +00002660/*
drh308c2a52010-05-14 11:30:18 +00002661** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002662** of the following:
2663**
2664** (1) SHARED_LOCK
2665** (2) RESERVED_LOCK
2666** (3) PENDING_LOCK
2667** (4) EXCLUSIVE_LOCK
2668**
2669** Sometimes when requesting one lock state, additional lock states
2670** are inserted in between. The locking might fail on one of the later
2671** transitions leaving the lock state different from what it started but
2672** still short of its goal. The following chart shows the allowed
2673** transitions and the inserted intermediate states:
2674**
2675** UNLOCKED -> SHARED
2676** SHARED -> RESERVED
2677** SHARED -> (PENDING) -> EXCLUSIVE
2678** RESERVED -> (PENDING) -> EXCLUSIVE
2679** PENDING -> EXCLUSIVE
2680**
2681** This routine will only increase a lock. Use the sqlite3OsUnlock()
2682** routine to lower a locking level.
2683*/
drh308c2a52010-05-14 11:30:18 +00002684static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002685 int rc = SQLITE_OK;
2686 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002687 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002688 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002689
2690 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002691 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2692 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002693 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002694
drhbfe66312006-10-03 17:40:40 +00002695 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002696 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002697 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002698 */
drh308c2a52010-05-14 11:30:18 +00002699 if( pFile->eFileLock>=eFileLock ){
2700 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2701 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002702 return SQLITE_OK;
2703 }
2704
2705 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002706 ** (1) We never move from unlocked to anything higher than shared lock.
2707 ** (2) SQLite never explicitly requests a pendig lock.
2708 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002709 */
drh308c2a52010-05-14 11:30:18 +00002710 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2711 assert( eFileLock!=PENDING_LOCK );
2712 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002713
drh8af6c222010-05-14 12:43:01 +00002714 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002715 */
drh6c7d5c52008-11-21 20:32:33 +00002716 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002717 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002718
2719 /* If some thread using this PID has a lock via a different unixFile*
2720 ** handle that precludes the requested lock, return BUSY.
2721 */
drh8af6c222010-05-14 12:43:01 +00002722 if( (pFile->eFileLock!=pInode->eFileLock &&
2723 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002724 ){
2725 rc = SQLITE_BUSY;
2726 goto afp_end_lock;
2727 }
2728
2729 /* If a SHARED lock is requested, and some thread using this PID already
2730 ** has a SHARED or RESERVED lock, then increment reference counts and
2731 ** return SQLITE_OK.
2732 */
drh308c2a52010-05-14 11:30:18 +00002733 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002734 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002735 assert( eFileLock==SHARED_LOCK );
2736 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002737 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002738 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002739 pInode->nShared++;
2740 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002741 goto afp_end_lock;
2742 }
drhbfe66312006-10-03 17:40:40 +00002743
2744 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002745 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2746 ** be released.
2747 */
drh308c2a52010-05-14 11:30:18 +00002748 if( eFileLock==SHARED_LOCK
2749 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002750 ){
2751 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002752 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002753 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002754 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002755 goto afp_end_lock;
2756 }
2757 }
2758
2759 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002760 ** operating system calls for the specified lock.
2761 */
drh308c2a52010-05-14 11:30:18 +00002762 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002763 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002764 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002765
drh8af6c222010-05-14 12:43:01 +00002766 assert( pInode->nShared==0 );
2767 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002768
2769 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002770 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002771 /* note that the quality of the randomness doesn't matter that much */
2772 lk = random();
drh8af6c222010-05-14 12:43:01 +00002773 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002774 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002775 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002776 if( IS_LOCK_ERROR(lrc1) ){
2777 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002778 }
aswift5b1a2562008-08-22 00:22:35 +00002779 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002780 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002781
aswift5b1a2562008-08-22 00:22:35 +00002782 if( IS_LOCK_ERROR(lrc1) ) {
2783 pFile->lastErrno = lrc1Errno;
2784 rc = lrc1;
2785 goto afp_end_lock;
2786 } else if( IS_LOCK_ERROR(lrc2) ){
2787 rc = lrc2;
2788 goto afp_end_lock;
2789 } else if( lrc1 != SQLITE_OK ) {
2790 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002791 } else {
drh308c2a52010-05-14 11:30:18 +00002792 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002793 pInode->nLock++;
2794 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002795 }
drh8af6c222010-05-14 12:43:01 +00002796 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002797 /* We are trying for an exclusive lock but another thread in this
2798 ** same process is still holding a shared lock. */
2799 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002800 }else{
2801 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2802 ** assumed that there is a SHARED or greater lock on the file
2803 ** already.
2804 */
2805 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002806 assert( 0!=pFile->eFileLock );
2807 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002808 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002809 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002810 if( !failed ){
2811 context->reserved = 1;
2812 }
drhbfe66312006-10-03 17:40:40 +00002813 }
drh308c2a52010-05-14 11:30:18 +00002814 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002815 /* Acquire an EXCLUSIVE lock */
2816
2817 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002818 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002819 */
drh6b9d6dd2008-12-03 19:34:47 +00002820 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002821 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002822 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002823 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002824 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002825 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002826 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002827 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002828 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2829 ** a critical I/O error
2830 */
2831 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2832 SQLITE_IOERR_LOCK;
2833 goto afp_end_lock;
2834 }
2835 }else{
aswift5b1a2562008-08-22 00:22:35 +00002836 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002837 }
2838 }
aswift5b1a2562008-08-22 00:22:35 +00002839 if( failed ){
2840 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002841 }
2842 }
2843
2844 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002845 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002846 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002847 }else if( eFileLock==EXCLUSIVE_LOCK ){
2848 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002849 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002850 }
2851
2852afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002853 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002854 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2855 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002856 return rc;
2857}
2858
2859/*
drh308c2a52010-05-14 11:30:18 +00002860** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002861** must be either NO_LOCK or SHARED_LOCK.
2862**
2863** If the locking level of the file descriptor is already at or below
2864** the requested locking level, this routine is a no-op.
2865*/
drh308c2a52010-05-14 11:30:18 +00002866static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002867 int rc = SQLITE_OK;
2868 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002869 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002870 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2871 int skipShared = 0;
2872#ifdef SQLITE_TEST
2873 int h = pFile->h;
2874#endif
drhbfe66312006-10-03 17:40:40 +00002875
2876 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002877 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002878 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002879 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002880
drh308c2a52010-05-14 11:30:18 +00002881 assert( eFileLock<=SHARED_LOCK );
2882 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002883 return SQLITE_OK;
2884 }
drh6c7d5c52008-11-21 20:32:33 +00002885 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002886 pInode = pFile->pInode;
2887 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002888 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002889 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002890 SimulateIOErrorBenign(1);
2891 SimulateIOError( h=(-1) )
2892 SimulateIOErrorBenign(0);
2893
drhd3d8c042012-05-29 17:02:40 +00002894#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002895 /* When reducing a lock such that other processes can start
2896 ** reading the database file again, make sure that the
2897 ** transaction counter was updated if any part of the database
2898 ** file changed. If the transaction counter is not updated,
2899 ** other connections to the same file might not realize that
2900 ** the file has changed and hence might not know to flush their
2901 ** cache. The use of a stale cache can lead to database corruption.
2902 */
2903 assert( pFile->inNormalWrite==0
2904 || pFile->dbUpdate==0
2905 || pFile->transCntrChng==1 );
2906 pFile->inNormalWrite = 0;
2907#endif
aswiftaebf4132008-11-21 00:10:35 +00002908
drh308c2a52010-05-14 11:30:18 +00002909 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002910 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002911 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002912 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002913 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002914 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2915 } else {
2916 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002917 }
2918 }
drh308c2a52010-05-14 11:30:18 +00002919 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002920 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002921 }
drh308c2a52010-05-14 11:30:18 +00002922 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002923 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2924 if( !rc ){
2925 context->reserved = 0;
2926 }
aswiftaebf4132008-11-21 00:10:35 +00002927 }
drh8af6c222010-05-14 12:43:01 +00002928 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2929 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002930 }
aswiftaebf4132008-11-21 00:10:35 +00002931 }
drh308c2a52010-05-14 11:30:18 +00002932 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002933
drh7ed97b92010-01-20 13:07:21 +00002934 /* Decrement the shared lock counter. Release the lock using an
2935 ** OS call only when all threads in this same process have released
2936 ** the lock.
2937 */
drh8af6c222010-05-14 12:43:01 +00002938 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2939 pInode->nShared--;
2940 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002941 SimulateIOErrorBenign(1);
2942 SimulateIOError( h=(-1) )
2943 SimulateIOErrorBenign(0);
2944 if( !skipShared ){
2945 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2946 }
2947 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002948 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002949 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002950 }
2951 }
2952 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002953 pInode->nLock--;
2954 assert( pInode->nLock>=0 );
2955 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002956 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002957 }
2958 }
drhbfe66312006-10-03 17:40:40 +00002959 }
drh7ed97b92010-01-20 13:07:21 +00002960
drh6c7d5c52008-11-21 20:32:33 +00002961 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002962 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002963 return rc;
2964}
2965
2966/*
drh339eb0b2008-03-07 15:34:11 +00002967** Close a file & cleanup AFP specific locking context
2968*/
danielk1977e339d652008-06-28 11:23:00 +00002969static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002970 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002971 if( id ){
2972 unixFile *pFile = (unixFile*)id;
2973 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002974 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002975 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002976 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002977 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002978 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002979 ** the last lock is cleared.
2980 */
dan08da86a2009-08-21 17:18:03 +00002981 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002982 }
danb0ac3e32010-06-16 10:55:42 +00002983 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002984 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002985 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002986 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002987 }
drh7ed97b92010-01-20 13:07:21 +00002988 return rc;
drhbfe66312006-10-03 17:40:40 +00002989}
2990
drhd2cb50b2009-01-09 21:41:17 +00002991#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002992/*
2993** The code above is the AFP lock implementation. The code is specific
2994** to MacOSX and does not work on other unix platforms. No alternative
2995** is available. If you don't compile for a mac, then the "unix-afp"
2996** VFS is not available.
2997**
2998********************* End of the AFP lock implementation **********************
2999******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003000
drh7ed97b92010-01-20 13:07:21 +00003001/******************************************************************************
3002*************************** Begin NFS Locking ********************************/
3003
3004#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3005/*
drh308c2a52010-05-14 11:30:18 +00003006 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003007 ** must be either NO_LOCK or SHARED_LOCK.
3008 **
3009 ** If the locking level of the file descriptor is already at or below
3010 ** the requested locking level, this routine is a no-op.
3011 */
drh308c2a52010-05-14 11:30:18 +00003012static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003013 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003014}
3015
3016#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3017/*
3018** The code above is the NFS lock implementation. The code is specific
3019** to MacOSX and does not work on other unix platforms. No alternative
3020** is available.
3021**
3022********************* End of the NFS lock implementation **********************
3023******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003024
3025/******************************************************************************
3026**************** Non-locking sqlite3_file methods *****************************
3027**
3028** The next division contains implementations for all methods of the
3029** sqlite3_file object other than the locking methods. The locking
3030** methods were defined in divisions above (one locking method per
3031** division). Those methods that are common to all locking modes
3032** are gather together into this division.
3033*/
drhbfe66312006-10-03 17:40:40 +00003034
3035/*
drh734c9862008-11-28 15:37:20 +00003036** Seek to the offset passed as the second argument, then read cnt
3037** bytes into pBuf. Return the number of bytes actually read.
3038**
3039** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3040** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3041** one system to another. Since SQLite does not define USE_PREAD
3042** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3043** See tickets #2741 and #2681.
3044**
3045** To avoid stomping the errno value on a failed read the lastErrno value
3046** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003047*/
drh734c9862008-11-28 15:37:20 +00003048static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3049 int got;
drh58024642011-11-07 18:16:00 +00003050 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003051#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003052 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003053#endif
drh734c9862008-11-28 15:37:20 +00003054 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003055 assert( cnt==(cnt&0x1ffff) );
3056 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003057 do{
drh734c9862008-11-28 15:37:20 +00003058#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003059 got = osPread(id->h, pBuf, cnt, offset);
3060 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003061#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003062 got = osPread64(id->h, pBuf, cnt, offset);
3063 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003064#else
drh58024642011-11-07 18:16:00 +00003065 newOffset = lseek(id->h, offset, SEEK_SET);
3066 SimulateIOError( newOffset-- );
3067 if( newOffset!=offset ){
3068 if( newOffset == -1 ){
3069 ((unixFile*)id)->lastErrno = errno;
3070 }else{
drhf2f105d2012-08-20 15:53:54 +00003071 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003072 }
3073 return -1;
drh734c9862008-11-28 15:37:20 +00003074 }
drh58024642011-11-07 18:16:00 +00003075 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003076#endif
drh58024642011-11-07 18:16:00 +00003077 if( got==cnt ) break;
3078 if( got<0 ){
3079 if( errno==EINTR ){ got = 1; continue; }
3080 prior = 0;
3081 ((unixFile*)id)->lastErrno = errno;
3082 break;
3083 }else if( got>0 ){
3084 cnt -= got;
3085 offset += got;
3086 prior += got;
3087 pBuf = (void*)(got + (char*)pBuf);
3088 }
3089 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003090 TIMER_END;
drh58024642011-11-07 18:16:00 +00003091 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3092 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3093 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003094}
3095
3096/*
drh734c9862008-11-28 15:37:20 +00003097** Read data from a file into a buffer. Return SQLITE_OK if all
3098** bytes were read successfully and SQLITE_IOERR if anything goes
3099** wrong.
drh339eb0b2008-03-07 15:34:11 +00003100*/
drh734c9862008-11-28 15:37:20 +00003101static int unixRead(
3102 sqlite3_file *id,
3103 void *pBuf,
3104 int amt,
3105 sqlite3_int64 offset
3106){
dan08da86a2009-08-21 17:18:03 +00003107 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003108 int got;
3109 assert( id );
drh08c6d442009-02-09 17:34:07 +00003110
dan08da86a2009-08-21 17:18:03 +00003111 /* If this is a database file (not a journal, master-journal or temp
3112 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003113#if 0
dane946c392009-08-22 11:39:46 +00003114 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003115 || offset>=PENDING_BYTE+512
3116 || offset+amt<=PENDING_BYTE
3117 );
dan7c246102010-04-12 19:00:29 +00003118#endif
drh08c6d442009-02-09 17:34:07 +00003119
drh6e0b6d52013-04-09 16:19:20 +00003120#if !defined(SQLITE_DISABLE_MMAP)
drh6c569632013-03-26 18:48:11 +00003121 /* Deal with as much of this read request as possible by transfering
3122 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003123 if( offset<pFile->mmapSize ){
3124 if( offset+amt <= pFile->mmapSize ){
3125 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3126 return SQLITE_OK;
3127 }else{
3128 int nCopy = pFile->mmapSize - offset;
3129 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3130 pBuf = &((u8 *)pBuf)[nCopy];
3131 amt -= nCopy;
3132 offset += nCopy;
3133 }
3134 }
drh6e0b6d52013-04-09 16:19:20 +00003135#endif
danf23da962013-03-23 21:00:41 +00003136
dan08da86a2009-08-21 17:18:03 +00003137 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003138 if( got==amt ){
3139 return SQLITE_OK;
3140 }else if( got<0 ){
3141 /* lastErrno set by seekAndRead */
3142 return SQLITE_IOERR_READ;
3143 }else{
dan08da86a2009-08-21 17:18:03 +00003144 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003145 /* Unread parts of the buffer must be zero-filled */
3146 memset(&((char*)pBuf)[got], 0, amt-got);
3147 return SQLITE_IOERR_SHORT_READ;
3148 }
3149}
3150
3151/*
3152** Seek to the offset in id->offset then read cnt bytes into pBuf.
3153** Return the number of bytes actually read. Update the offset.
3154**
3155** To avoid stomping the errno value on a failed write the lastErrno value
3156** is set before returning.
3157*/
3158static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3159 int got;
drh7ed97b92010-01-20 13:07:21 +00003160#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003161 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003162#endif
drhc1fd2cf2012-10-01 12:16:26 +00003163 assert( cnt==(cnt&0x1ffff) );
3164 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003165 TIMER_START;
3166#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003167 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003168#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003169 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003170#else
drhbd1e50c2011-08-19 14:54:12 +00003171 do{
3172 newOffset = lseek(id->h, offset, SEEK_SET);
3173 SimulateIOError( newOffset-- );
3174 if( newOffset!=offset ){
3175 if( newOffset == -1 ){
3176 ((unixFile*)id)->lastErrno = errno;
3177 }else{
drhf2f105d2012-08-20 15:53:54 +00003178 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003179 }
3180 return -1;
drh734c9862008-11-28 15:37:20 +00003181 }
drhbd1e50c2011-08-19 14:54:12 +00003182 got = osWrite(id->h, pBuf, cnt);
3183 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003184#endif
3185 TIMER_END;
3186 if( got<0 ){
3187 ((unixFile*)id)->lastErrno = errno;
3188 }
3189
drh308c2a52010-05-14 11:30:18 +00003190 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003191 return got;
3192}
3193
3194
3195/*
3196** Write data from a buffer into a file. Return SQLITE_OK on success
3197** or some other error code on failure.
3198*/
3199static int unixWrite(
3200 sqlite3_file *id,
3201 const void *pBuf,
3202 int amt,
3203 sqlite3_int64 offset
3204){
dan08da86a2009-08-21 17:18:03 +00003205 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003206 int wrote = 0;
3207 assert( id );
3208 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003209
dan08da86a2009-08-21 17:18:03 +00003210 /* If this is a database file (not a journal, master-journal or temp
3211 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003212#if 0
dane946c392009-08-22 11:39:46 +00003213 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003214 || offset>=PENDING_BYTE+512
3215 || offset+amt<=PENDING_BYTE
3216 );
dan7c246102010-04-12 19:00:29 +00003217#endif
drh08c6d442009-02-09 17:34:07 +00003218
drhd3d8c042012-05-29 17:02:40 +00003219#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003220 /* If we are doing a normal write to a database file (as opposed to
3221 ** doing a hot-journal rollback or a write to some file other than a
3222 ** normal database file) then record the fact that the database
3223 ** has changed. If the transaction counter is modified, record that
3224 ** fact too.
3225 */
dan08da86a2009-08-21 17:18:03 +00003226 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003227 pFile->dbUpdate = 1; /* The database has been modified */
3228 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003229 int rc;
drh8f941bc2009-01-14 23:03:40 +00003230 char oldCntr[4];
3231 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003232 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003233 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003234 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003235 pFile->transCntrChng = 1; /* The transaction counter has changed */
3236 }
3237 }
3238 }
3239#endif
3240
drh6e0b6d52013-04-09 16:19:20 +00003241#if !defined(SQLITE_DISABLE_MMAP)
danf23da962013-03-23 21:00:41 +00003242 /* Deal with as much of this write request as possible by transfering
3243 ** data from the memory mapping using memcpy(). */
3244 if( offset<pFile->mmapSize ){
3245 if( offset+amt <= pFile->mmapSize ){
3246 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3247 return SQLITE_OK;
3248 }else{
3249 int nCopy = pFile->mmapSize - offset;
3250 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3251 pBuf = &((u8 *)pBuf)[nCopy];
3252 amt -= nCopy;
3253 offset += nCopy;
3254 }
3255 }
drh6e0b6d52013-04-09 16:19:20 +00003256#endif
danf23da962013-03-23 21:00:41 +00003257
dan08da86a2009-08-21 17:18:03 +00003258 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003259 amt -= wrote;
3260 offset += wrote;
3261 pBuf = &((char*)pBuf)[wrote];
3262 }
3263 SimulateIOError(( wrote=(-1), amt=1 ));
3264 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003265
drh734c9862008-11-28 15:37:20 +00003266 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003267 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003268 /* lastErrno set by seekAndWrite */
3269 return SQLITE_IOERR_WRITE;
3270 }else{
dan08da86a2009-08-21 17:18:03 +00003271 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003272 return SQLITE_FULL;
3273 }
3274 }
dan6e09d692010-07-27 18:34:15 +00003275
drh734c9862008-11-28 15:37:20 +00003276 return SQLITE_OK;
3277}
3278
3279#ifdef SQLITE_TEST
3280/*
3281** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003282** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003283*/
3284int sqlite3_sync_count = 0;
3285int sqlite3_fullsync_count = 0;
3286#endif
3287
3288/*
drh89240432009-03-25 01:06:01 +00003289** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003290** Others do no. To be safe, we will stick with the (slightly slower)
3291** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003292** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003293*/
drh20f8e132011-08-31 21:01:55 +00003294#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003295# define fdatasync fsync
3296#endif
3297
3298/*
3299** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3300** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3301** only available on Mac OS X. But that could change.
3302*/
3303#ifdef F_FULLFSYNC
3304# define HAVE_FULLFSYNC 1
3305#else
3306# define HAVE_FULLFSYNC 0
3307#endif
3308
3309
3310/*
3311** The fsync() system call does not work as advertised on many
3312** unix systems. The following procedure is an attempt to make
3313** it work better.
3314**
3315** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3316** for testing when we want to run through the test suite quickly.
3317** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3318** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3319** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003320**
3321** SQLite sets the dataOnly flag if the size of the file is unchanged.
3322** The idea behind dataOnly is that it should only write the file content
3323** to disk, not the inode. We only set dataOnly if the file size is
3324** unchanged since the file size is part of the inode. However,
3325** Ted Ts'o tells us that fdatasync() will also write the inode if the
3326** file size has changed. The only real difference between fdatasync()
3327** and fsync(), Ted tells us, is that fdatasync() will not flush the
3328** inode if the mtime or owner or other inode attributes have changed.
3329** We only care about the file size, not the other file attributes, so
3330** as far as SQLite is concerned, an fdatasync() is always adequate.
3331** So, we always use fdatasync() if it is available, regardless of
3332** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003333*/
3334static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003335 int rc;
drh734c9862008-11-28 15:37:20 +00003336
3337 /* The following "ifdef/elif/else/" block has the same structure as
3338 ** the one below. It is replicated here solely to avoid cluttering
3339 ** up the real code with the UNUSED_PARAMETER() macros.
3340 */
3341#ifdef SQLITE_NO_SYNC
3342 UNUSED_PARAMETER(fd);
3343 UNUSED_PARAMETER(fullSync);
3344 UNUSED_PARAMETER(dataOnly);
3345#elif HAVE_FULLFSYNC
3346 UNUSED_PARAMETER(dataOnly);
3347#else
3348 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003349 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003350#endif
3351
3352 /* Record the number of times that we do a normal fsync() and
3353 ** FULLSYNC. This is used during testing to verify that this procedure
3354 ** gets called with the correct arguments.
3355 */
3356#ifdef SQLITE_TEST
3357 if( fullSync ) sqlite3_fullsync_count++;
3358 sqlite3_sync_count++;
3359#endif
3360
3361 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3362 ** no-op
3363 */
3364#ifdef SQLITE_NO_SYNC
3365 rc = SQLITE_OK;
3366#elif HAVE_FULLFSYNC
3367 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003368 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003369 }else{
3370 rc = 1;
3371 }
3372 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003373 ** It shouldn't be possible for fullfsync to fail on the local
3374 ** file system (on OSX), so failure indicates that FULLFSYNC
3375 ** isn't supported for this file system. So, attempt an fsync
3376 ** and (for now) ignore the overhead of a superfluous fcntl call.
3377 ** It'd be better to detect fullfsync support once and avoid
3378 ** the fcntl call every time sync is called.
3379 */
drh734c9862008-11-28 15:37:20 +00003380 if( rc ) rc = fsync(fd);
3381
drh7ed97b92010-01-20 13:07:21 +00003382#elif defined(__APPLE__)
3383 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3384 ** so currently we default to the macro that redefines fdatasync to fsync
3385 */
3386 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003387#else
drh0b647ff2009-03-21 14:41:04 +00003388 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003389#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003390 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003391 rc = fsync(fd);
3392 }
drh0b647ff2009-03-21 14:41:04 +00003393#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003394#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3395
3396 if( OS_VXWORKS && rc!= -1 ){
3397 rc = 0;
3398 }
chw97185482008-11-17 08:05:31 +00003399 return rc;
drhbfe66312006-10-03 17:40:40 +00003400}
3401
drh734c9862008-11-28 15:37:20 +00003402/*
drh0059eae2011-08-08 23:48:40 +00003403** Open a file descriptor to the directory containing file zFilename.
3404** If successful, *pFd is set to the opened file descriptor and
3405** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3406** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3407** value.
3408**
drh90315a22011-08-10 01:52:12 +00003409** The directory file descriptor is used for only one thing - to
3410** fsync() a directory to make sure file creation and deletion events
3411** are flushed to disk. Such fsyncs are not needed on newer
3412** journaling filesystems, but are required on older filesystems.
3413**
3414** This routine can be overridden using the xSetSysCall interface.
3415** The ability to override this routine was added in support of the
3416** chromium sandbox. Opening a directory is a security risk (we are
3417** told) so making it overrideable allows the chromium sandbox to
3418** replace this routine with a harmless no-op. To make this routine
3419** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3420** *pFd set to a negative number.
3421**
drh0059eae2011-08-08 23:48:40 +00003422** If SQLITE_OK is returned, the caller is responsible for closing
3423** the file descriptor *pFd using close().
3424*/
3425static int openDirectory(const char *zFilename, int *pFd){
3426 int ii;
3427 int fd = -1;
3428 char zDirname[MAX_PATHNAME+1];
3429
3430 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3431 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3432 if( ii>0 ){
3433 zDirname[ii] = '\0';
3434 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3435 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003436 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3437 }
3438 }
3439 *pFd = fd;
3440 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3441}
3442
3443/*
drh734c9862008-11-28 15:37:20 +00003444** Make sure all writes to a particular file are committed to disk.
3445**
3446** If dataOnly==0 then both the file itself and its metadata (file
3447** size, access time, etc) are synced. If dataOnly!=0 then only the
3448** file data is synced.
3449**
3450** Under Unix, also make sure that the directory entry for the file
3451** has been created by fsync-ing the directory that contains the file.
3452** If we do not do this and we encounter a power failure, the directory
3453** entry for the journal might not exist after we reboot. The next
3454** SQLite to access the file will not know that the journal exists (because
3455** the directory entry for the journal was never created) and the transaction
3456** will not roll back - possibly leading to database corruption.
3457*/
3458static int unixSync(sqlite3_file *id, int flags){
3459 int rc;
3460 unixFile *pFile = (unixFile*)id;
3461
3462 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3463 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3464
3465 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3466 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3467 || (flags&0x0F)==SQLITE_SYNC_FULL
3468 );
3469
3470 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3471 ** line is to test that doing so does not cause any problems.
3472 */
3473 SimulateDiskfullError( return SQLITE_FULL );
3474
3475 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003476 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003477 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3478 SimulateIOError( rc=1 );
3479 if( rc ){
3480 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003481 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003482 }
drh0059eae2011-08-08 23:48:40 +00003483
3484 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003485 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003486 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003487 */
3488 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3489 int dirfd;
3490 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003491 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003492 rc = osOpenDirectory(pFile->zPath, &dirfd);
3493 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003494 full_fsync(dirfd, 0, 0);
3495 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003496 }else if( rc==SQLITE_CANTOPEN ){
3497 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003498 }
drh0059eae2011-08-08 23:48:40 +00003499 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003500 }
3501 return rc;
3502}
3503
3504/*
3505** Truncate an open file to a specified size
3506*/
3507static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003508 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003509 int rc;
dan6e09d692010-07-27 18:34:15 +00003510 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003511 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003512
3513 /* If the user has configured a chunk-size for this file, truncate the
3514 ** file so that it consists of an integer number of chunks (i.e. the
3515 ** actual file size after the operation may be larger than the requested
3516 ** size).
3517 */
drhb8af4b72012-04-05 20:04:39 +00003518 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003519 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3520 }
3521
drhff812312011-02-23 13:33:46 +00003522 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003523 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003524 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003525 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003526 }else{
drhd3d8c042012-05-29 17:02:40 +00003527#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003528 /* If we are doing a normal write to a database file (as opposed to
3529 ** doing a hot-journal rollback or a write to some file other than a
3530 ** normal database file) and we truncate the file to zero length,
3531 ** that effectively updates the change counter. This might happen
3532 ** when restoring a database using the backup API from a zero-length
3533 ** source.
3534 */
dan6e09d692010-07-27 18:34:15 +00003535 if( pFile->inNormalWrite && nByte==0 ){
3536 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003537 }
danf23da962013-03-23 21:00:41 +00003538#endif
danc0003312013-03-22 17:46:11 +00003539
3540 /* If the file was just truncated to a size smaller than the currently
3541 ** mapped region, reduce the effective mapping size as well. SQLite will
3542 ** use read() and write() to access data beyond this point from now on.
3543 */
3544 if( nByte<pFile->mmapSize ){
3545 pFile->mmapSize = nByte;
3546 }
drh3313b142009-11-06 04:13:18 +00003547
drh734c9862008-11-28 15:37:20 +00003548 return SQLITE_OK;
3549 }
3550}
3551
3552/*
3553** Determine the current size of a file in bytes
3554*/
3555static int unixFileSize(sqlite3_file *id, i64 *pSize){
3556 int rc;
3557 struct stat buf;
3558 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003559 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003560 SimulateIOError( rc=1 );
3561 if( rc!=0 ){
3562 ((unixFile*)id)->lastErrno = errno;
3563 return SQLITE_IOERR_FSTAT;
3564 }
3565 *pSize = buf.st_size;
3566
drh8af6c222010-05-14 12:43:01 +00003567 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003568 ** writes a single byte into that file in order to work around a bug
3569 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3570 ** layers, we need to report this file size as zero even though it is
3571 ** really 1. Ticket #3260.
3572 */
3573 if( *pSize==1 ) *pSize = 0;
3574
3575
3576 return SQLITE_OK;
3577}
3578
drhd2cb50b2009-01-09 21:41:17 +00003579#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003580/*
3581** Handler for proxy-locking file-control verbs. Defined below in the
3582** proxying locking division.
3583*/
3584static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003585#endif
drh715ff302008-12-03 22:32:44 +00003586
dan502019c2010-07-28 14:26:17 +00003587/*
3588** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003589** file-control operation. Enlarge the database to nBytes in size
3590** (rounded up to the next chunk-size). If the database is already
3591** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003592*/
3593static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003594 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003595 i64 nSize; /* Required file size */
3596 struct stat buf; /* Used to hold return values of fstat() */
3597
drh99ab3b12011-03-02 15:09:07 +00003598 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003599
3600 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3601 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003602
dan502019c2010-07-28 14:26:17 +00003603#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003604 /* The code below is handling the return value of osFallocate()
3605 ** correctly. posix_fallocate() is defined to "returns zero on success,
3606 ** or an error number on failure". See the manpage for details. */
3607 int err;
drhff812312011-02-23 13:33:46 +00003608 do{
dan661d71a2011-03-30 19:08:03 +00003609 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3610 }while( err==EINTR );
3611 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003612#else
3613 /* If the OS does not have posix_fallocate(), fake it. First use
3614 ** ftruncate() to set the file size, then write a single byte to
3615 ** the last byte in each block within the extended region. This
3616 ** is the same technique used by glibc to implement posix_fallocate()
3617 ** on systems that do not have a real fallocate() system call.
3618 */
3619 int nBlk = buf.st_blksize; /* File-system block size */
3620 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003621
drhff812312011-02-23 13:33:46 +00003622 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003623 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003624 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003625 }
3626 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003627 while( iWrite<nSize ){
3628 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3629 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003630 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003631 }
dan502019c2010-07-28 14:26:17 +00003632#endif
3633 }
3634 }
3635
dane6ecd662013-04-01 17:56:59 +00003636 if( pFile->mmapLimit>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003637 int rc;
3638 if( pFile->szChunk<=0 ){
3639 if( robust_ftruncate(pFile->h, nByte) ){
3640 pFile->lastErrno = errno;
3641 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3642 }
3643 }
3644
3645 rc = unixMapfile(pFile, nByte);
3646 return rc;
3647 }
3648
dan502019c2010-07-28 14:26:17 +00003649 return SQLITE_OK;
3650}
danielk1977ad94b582007-08-20 06:44:22 +00003651
danielk1977e3026632004-06-22 11:29:02 +00003652/*
drhf12b3f62011-12-21 14:42:29 +00003653** If *pArg is inititially negative then this is a query. Set *pArg to
3654** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3655**
3656** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3657*/
3658static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3659 if( *pArg<0 ){
3660 *pArg = (pFile->ctrlFlags & mask)!=0;
3661 }else if( (*pArg)==0 ){
3662 pFile->ctrlFlags &= ~mask;
3663 }else{
3664 pFile->ctrlFlags |= mask;
3665 }
3666}
3667
drh696b33e2012-12-06 19:01:42 +00003668/* Forward declaration */
3669static int unixGetTempname(int nBuf, char *zBuf);
3670
drhf12b3f62011-12-21 14:42:29 +00003671/*
drh9e33c2c2007-08-31 18:34:59 +00003672** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003673*/
drhcc6bb3e2007-08-31 16:11:35 +00003674static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003675 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003676 switch( op ){
3677 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003678 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003679 return SQLITE_OK;
3680 }
drh7708e972008-11-29 00:56:52 +00003681 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003682 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003683 return SQLITE_OK;
3684 }
dan6e09d692010-07-27 18:34:15 +00003685 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003686 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003687 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003688 }
drh9ff27ec2010-05-19 19:26:05 +00003689 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003690 int rc;
3691 SimulateIOErrorBenign(1);
3692 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3693 SimulateIOErrorBenign(0);
3694 return rc;
drhf0b190d2011-07-26 16:03:07 +00003695 }
3696 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003697 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3698 return SQLITE_OK;
3699 }
drhcb15f352011-12-23 01:04:17 +00003700 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3701 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003702 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003703 }
drhde60fc22011-12-14 17:53:36 +00003704 case SQLITE_FCNTL_VFSNAME: {
3705 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3706 return SQLITE_OK;
3707 }
drh696b33e2012-12-06 19:01:42 +00003708 case SQLITE_FCNTL_TEMPFILENAME: {
3709 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3710 if( zTFile ){
3711 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3712 *(char**)pArg = zTFile;
3713 }
3714 return SQLITE_OK;
3715 }
drh0d0614b2013-03-25 23:09:28 +00003716 case SQLITE_FCNTL_MMAP_LIMIT: {
drh34f74902013-04-03 13:09:18 +00003717 i64 newLimit = *(i64*)pArg;
3718 *(i64*)pArg = pFile->mmapLimit;
danbcb8a862013-04-08 15:30:41 +00003719 if( newLimit>=0 ){
3720 pFile->mmapLimit = newLimit;
3721 if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
3722 }
danb2d3de32013-03-14 18:34:37 +00003723 return SQLITE_OK;
3724 }
drhd3d8c042012-05-29 17:02:40 +00003725#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003726 /* The pager calls this method to signal that it has done
3727 ** a rollback and that the database is therefore unchanged and
3728 ** it hence it is OK for the transaction change counter to be
3729 ** unchanged.
3730 */
3731 case SQLITE_FCNTL_DB_UNCHANGED: {
3732 ((unixFile*)id)->dbUpdate = 0;
3733 return SQLITE_OK;
3734 }
3735#endif
drhd2cb50b2009-01-09 21:41:17 +00003736#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003737 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003738 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003739 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003740 }
drhd2cb50b2009-01-09 21:41:17 +00003741#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003742 }
drh0b52b7d2011-01-26 19:46:22 +00003743 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003744}
3745
3746/*
danielk1977a3d4c882007-03-23 10:08:38 +00003747** Return the sector size in bytes of the underlying block device for
3748** the specified file. This is almost always 512 bytes, but may be
3749** larger for some devices.
3750**
3751** SQLite code assumes this function cannot fail. It also assumes that
3752** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003753** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003754** same for both.
3755*/
drh537dddf2012-10-26 13:46:24 +00003756#ifndef __QNXNTO__
3757static int unixSectorSize(sqlite3_file *NotUsed){
3758 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003759 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003760}
drh537dddf2012-10-26 13:46:24 +00003761#endif
3762
3763/*
3764** The following version of unixSectorSize() is optimized for QNX.
3765*/
3766#ifdef __QNXNTO__
3767#include <sys/dcmd_blk.h>
3768#include <sys/statvfs.h>
3769static int unixSectorSize(sqlite3_file *id){
3770 unixFile *pFile = (unixFile*)id;
3771 if( pFile->sectorSize == 0 ){
3772 struct statvfs fsInfo;
3773
3774 /* Set defaults for non-supported filesystems */
3775 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3776 pFile->deviceCharacteristics = 0;
3777 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3778 return pFile->sectorSize;
3779 }
3780
3781 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3782 pFile->sectorSize = fsInfo.f_bsize;
3783 pFile->deviceCharacteristics =
3784 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3785 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3786 ** the write succeeds */
3787 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3788 ** so it is ordered */
3789 0;
3790 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3791 pFile->sectorSize = fsInfo.f_bsize;
3792 pFile->deviceCharacteristics =
3793 /* etfs cluster size writes are atomic */
3794 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3795 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3796 ** the write succeeds */
3797 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3798 ** so it is ordered */
3799 0;
3800 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3801 pFile->sectorSize = fsInfo.f_bsize;
3802 pFile->deviceCharacteristics =
3803 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3804 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3805 ** the write succeeds */
3806 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3807 ** so it is ordered */
3808 0;
3809 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3810 pFile->sectorSize = fsInfo.f_bsize;
3811 pFile->deviceCharacteristics =
3812 /* full bitset of atomics from max sector size and smaller */
3813 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3814 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3815 ** so it is ordered */
3816 0;
3817 }else if( strstr(fsInfo.f_basetype, "dos") ){
3818 pFile->sectorSize = fsInfo.f_bsize;
3819 pFile->deviceCharacteristics =
3820 /* full bitset of atomics from max sector size and smaller */
3821 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3822 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3823 ** so it is ordered */
3824 0;
3825 }else{
3826 pFile->deviceCharacteristics =
3827 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3828 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3829 ** the write succeeds */
3830 0;
3831 }
3832 }
3833 /* Last chance verification. If the sector size isn't a multiple of 512
3834 ** then it isn't valid.*/
3835 if( pFile->sectorSize % 512 != 0 ){
3836 pFile->deviceCharacteristics = 0;
3837 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3838 }
3839 return pFile->sectorSize;
3840}
3841#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003842
danielk197790949c22007-08-17 16:50:38 +00003843/*
drhf12b3f62011-12-21 14:42:29 +00003844** Return the device characteristics for the file.
3845**
drhcb15f352011-12-23 01:04:17 +00003846** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3847** However, that choice is contraversial since technically the underlying
3848** file system does not always provide powersafe overwrites. (In other
3849** words, after a power-loss event, parts of the file that were never
3850** written might end up being altered.) However, non-PSOW behavior is very,
3851** very rare. And asserting PSOW makes a large reduction in the amount
3852** of required I/O for journaling, since a lot of padding is eliminated.
3853** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3854** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003855*/
drhf12b3f62011-12-21 14:42:29 +00003856static int unixDeviceCharacteristics(sqlite3_file *id){
3857 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003858 int rc = 0;
3859#ifdef __QNXNTO__
3860 if( p->sectorSize==0 ) unixSectorSize(id);
3861 rc = p->deviceCharacteristics;
3862#endif
drhcb15f352011-12-23 01:04:17 +00003863 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003864 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003865 }
drh537dddf2012-10-26 13:46:24 +00003866 return rc;
danielk197762079062007-08-15 17:08:46 +00003867}
3868
drhd9e5c4f2010-05-12 18:01:39 +00003869#ifndef SQLITE_OMIT_WAL
3870
3871
3872/*
drhd91c68f2010-05-14 14:52:25 +00003873** Object used to represent an shared memory buffer.
3874**
3875** When multiple threads all reference the same wal-index, each thread
3876** has its own unixShm object, but they all point to a single instance
3877** of this unixShmNode object. In other words, each wal-index is opened
3878** only once per process.
3879**
3880** Each unixShmNode object is connected to a single unixInodeInfo object.
3881** We could coalesce this object into unixInodeInfo, but that would mean
3882** every open file that does not use shared memory (in other words, most
3883** open files) would have to carry around this extra information. So
3884** the unixInodeInfo object contains a pointer to this unixShmNode object
3885** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003886**
3887** unixMutexHeld() must be true when creating or destroying
3888** this object or while reading or writing the following fields:
3889**
3890** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003891**
3892** The following fields are read-only after the object is created:
3893**
3894** fid
3895** zFilename
3896**
drhd91c68f2010-05-14 14:52:25 +00003897** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003898** unixMutexHeld() is true when reading or writing any other field
3899** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003900*/
drhd91c68f2010-05-14 14:52:25 +00003901struct unixShmNode {
3902 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003903 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003904 char *zFilename; /* Name of the mmapped file */
3905 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003906 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003907 u16 nRegion; /* Size of array apRegion */
3908 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003909 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003910 int nRef; /* Number of unixShm objects pointing to this */
3911 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003912#ifdef SQLITE_DEBUG
3913 u8 exclMask; /* Mask of exclusive locks held */
3914 u8 sharedMask; /* Mask of shared locks held */
3915 u8 nextShmId; /* Next available unixShm.id value */
3916#endif
3917};
3918
3919/*
drhd9e5c4f2010-05-12 18:01:39 +00003920** Structure used internally by this VFS to record the state of an
3921** open shared memory connection.
3922**
drhd91c68f2010-05-14 14:52:25 +00003923** The following fields are initialized when this object is created and
3924** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003925**
drhd91c68f2010-05-14 14:52:25 +00003926** unixShm.pFile
3927** unixShm.id
3928**
3929** All other fields are read/write. The unixShm.pFile->mutex must be held
3930** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003931*/
3932struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003933 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3934 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003935 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003936 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003937 u16 sharedMask; /* Mask of shared locks held */
3938 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003939};
3940
3941/*
drhd9e5c4f2010-05-12 18:01:39 +00003942** Constants used for locking
3943*/
drhbd9676c2010-06-23 17:58:38 +00003944#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003945#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003946
drhd9e5c4f2010-05-12 18:01:39 +00003947/*
drh73b64e42010-05-30 19:55:15 +00003948** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003949**
3950** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3951** otherwise.
3952*/
3953static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003954 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3955 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003956 int ofst, /* First byte of the locking range */
3957 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003958){
3959 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003960 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003961
drhd91c68f2010-05-14 14:52:25 +00003962 /* Access to the unixShmNode object is serialized by the caller */
3963 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003964
drh73b64e42010-05-30 19:55:15 +00003965 /* Shared locks never span more than one byte */
3966 assert( n==1 || lockType!=F_RDLCK );
3967
3968 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003969 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003970
drh3cb93392011-03-12 18:10:44 +00003971 if( pShmNode->h>=0 ){
3972 /* Initialize the locking parameters */
3973 memset(&f, 0, sizeof(f));
3974 f.l_type = lockType;
3975 f.l_whence = SEEK_SET;
3976 f.l_start = ofst;
3977 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003978
drh3cb93392011-03-12 18:10:44 +00003979 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3980 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3981 }
drhd9e5c4f2010-05-12 18:01:39 +00003982
3983 /* Update the global lock state and do debug tracing */
3984#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003985 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003986 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003987 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003988 if( rc==SQLITE_OK ){
3989 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003990 OSTRACE(("unlock %d ok", ofst));
3991 pShmNode->exclMask &= ~mask;
3992 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003993 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003994 OSTRACE(("read-lock %d ok", ofst));
3995 pShmNode->exclMask &= ~mask;
3996 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003997 }else{
3998 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003999 OSTRACE(("write-lock %d ok", ofst));
4000 pShmNode->exclMask |= mask;
4001 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004002 }
4003 }else{
4004 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004005 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004006 }else if( lockType==F_RDLCK ){
4007 OSTRACE(("read-lock failed"));
4008 }else{
4009 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004010 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004011 }
4012 }
drh20e1f082010-05-31 16:10:12 +00004013 OSTRACE((" - afterwards %03x,%03x\n",
4014 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004015 }
drhd9e5c4f2010-05-12 18:01:39 +00004016#endif
4017
4018 return rc;
4019}
4020
drhd9e5c4f2010-05-12 18:01:39 +00004021
4022/*
drhd91c68f2010-05-14 14:52:25 +00004023** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004024**
4025** This is not a VFS shared-memory method; it is a utility function called
4026** by VFS shared-memory methods.
4027*/
drhd91c68f2010-05-14 14:52:25 +00004028static void unixShmPurge(unixFile *pFd){
4029 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004030 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004031 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004032 int i;
drhd91c68f2010-05-14 14:52:25 +00004033 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004034 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004035 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004036 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004037 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004038 }else{
4039 sqlite3_free(p->apRegion[i]);
4040 }
dan13a3cb82010-06-11 19:04:21 +00004041 }
dan18801912010-06-14 14:07:50 +00004042 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004043 if( p->h>=0 ){
4044 robust_close(pFd, p->h, __LINE__);
4045 p->h = -1;
4046 }
drhd91c68f2010-05-14 14:52:25 +00004047 p->pInode->pShmNode = 0;
4048 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004049 }
4050}
4051
4052/*
danda9fe0c2010-07-13 18:44:03 +00004053** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004054** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004055**
drh7234c6d2010-06-19 15:10:09 +00004056** The file used to implement shared-memory is in the same directory
4057** as the open database file and has the same name as the open database
4058** file with the "-shm" suffix added. For example, if the database file
4059** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004060** for shared memory will be called "/home/user1/config.db-shm".
4061**
4062** Another approach to is to use files in /dev/shm or /dev/tmp or an
4063** some other tmpfs mount. But if a file in a different directory
4064** from the database file is used, then differing access permissions
4065** or a chroot() might cause two different processes on the same
4066** database to end up using different files for shared memory -
4067** meaning that their memory would not really be shared - resulting
4068** in database corruption. Nevertheless, this tmpfs file usage
4069** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4070** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4071** option results in an incompatible build of SQLite; builds of SQLite
4072** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4073** same database file at the same time, database corruption will likely
4074** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4075** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004076**
4077** When opening a new shared-memory file, if no other instances of that
4078** file are currently open, in this process or in other processes, then
4079** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004080**
4081** If the original database file (pDbFd) is using the "unix-excl" VFS
4082** that means that an exclusive lock is held on the database file and
4083** that no other processes are able to read or write the database. In
4084** that case, we do not really need shared memory. No shared memory
4085** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004086*/
danda9fe0c2010-07-13 18:44:03 +00004087static int unixOpenSharedMemory(unixFile *pDbFd){
4088 struct unixShm *p = 0; /* The connection to be opened */
4089 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4090 int rc; /* Result code */
4091 unixInodeInfo *pInode; /* The inode of fd */
4092 char *zShmFilename; /* Name of the file used for SHM */
4093 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004094
danda9fe0c2010-07-13 18:44:03 +00004095 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004096 p = sqlite3_malloc( sizeof(*p) );
4097 if( p==0 ) return SQLITE_NOMEM;
4098 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004099 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004100
danda9fe0c2010-07-13 18:44:03 +00004101 /* Check to see if a unixShmNode object already exists. Reuse an existing
4102 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004103 */
4104 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004105 pInode = pDbFd->pInode;
4106 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004107 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004108 struct stat sStat; /* fstat() info for database file */
4109
4110 /* Call fstat() to figure out the permissions on the database file. If
4111 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004112 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004113 */
drh3cb93392011-03-12 18:10:44 +00004114 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004115 rc = SQLITE_IOERR_FSTAT;
4116 goto shm_open_err;
4117 }
4118
drha4ced192010-07-15 18:32:40 +00004119#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004120 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004121#else
drh52bcde02012-01-03 14:50:45 +00004122 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004123#endif
drh7234c6d2010-06-19 15:10:09 +00004124 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004125 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004126 rc = SQLITE_NOMEM;
4127 goto shm_open_err;
4128 }
drh9cb5a0d2012-01-05 21:19:54 +00004129 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004130 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004131#ifdef SQLITE_SHM_DIRECTORY
4132 sqlite3_snprintf(nShmFilename, zShmFilename,
4133 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4134 (u32)sStat.st_ino, (u32)sStat.st_dev);
4135#else
drh7234c6d2010-06-19 15:10:09 +00004136 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004137 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004138#endif
drhd91c68f2010-05-14 14:52:25 +00004139 pShmNode->h = -1;
4140 pDbFd->pInode->pShmNode = pShmNode;
4141 pShmNode->pInode = pDbFd->pInode;
4142 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4143 if( pShmNode->mutex==0 ){
4144 rc = SQLITE_NOMEM;
4145 goto shm_open_err;
4146 }
drhd9e5c4f2010-05-12 18:01:39 +00004147
drh3cb93392011-03-12 18:10:44 +00004148 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004149 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004150 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004151 openFlags = O_RDONLY;
4152 pShmNode->isReadonly = 1;
4153 }
4154 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004155 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004156 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4157 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004158 }
drhac7c3ac2012-02-11 19:23:48 +00004159
4160 /* If this process is running as root, make sure that the SHM file
4161 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004162 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004163 */
drhed466822012-05-31 13:10:49 +00004164 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004165
4166 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004167 ** If not, truncate the file to zero length.
4168 */
4169 rc = SQLITE_OK;
4170 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4171 if( robust_ftruncate(pShmNode->h, 0) ){
4172 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004173 }
4174 }
drh66dfec8b2011-06-01 20:01:49 +00004175 if( rc==SQLITE_OK ){
4176 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4177 }
4178 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004179 }
drhd9e5c4f2010-05-12 18:01:39 +00004180 }
4181
drhd91c68f2010-05-14 14:52:25 +00004182 /* Make the new connection a child of the unixShmNode */
4183 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004184#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004185 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004186#endif
drhd91c68f2010-05-14 14:52:25 +00004187 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004188 pDbFd->pShm = p;
4189 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004190
4191 /* The reference count on pShmNode has already been incremented under
4192 ** the cover of the unixEnterMutex() mutex and the pointer from the
4193 ** new (struct unixShm) object to the pShmNode has been set. All that is
4194 ** left to do is to link the new object into the linked list starting
4195 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4196 ** mutex.
4197 */
4198 sqlite3_mutex_enter(pShmNode->mutex);
4199 p->pNext = pShmNode->pFirst;
4200 pShmNode->pFirst = p;
4201 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004202 return SQLITE_OK;
4203
4204 /* Jump here on any error */
4205shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004206 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004207 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004208 unixLeaveMutex();
4209 return rc;
4210}
4211
4212/*
danda9fe0c2010-07-13 18:44:03 +00004213** This function is called to obtain a pointer to region iRegion of the
4214** shared-memory associated with the database file fd. Shared-memory regions
4215** are numbered starting from zero. Each shared-memory region is szRegion
4216** bytes in size.
4217**
4218** If an error occurs, an error code is returned and *pp is set to NULL.
4219**
4220** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4221** region has not been allocated (by any client, including one running in a
4222** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4223** bExtend is non-zero and the requested shared-memory region has not yet
4224** been allocated, it is allocated by this function.
4225**
4226** If the shared-memory region has already been allocated or is allocated by
4227** this call as described above, then it is mapped into this processes
4228** address space (if it is not already), *pp is set to point to the mapped
4229** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004230*/
danda9fe0c2010-07-13 18:44:03 +00004231static int unixShmMap(
4232 sqlite3_file *fd, /* Handle open on database file */
4233 int iRegion, /* Region to retrieve */
4234 int szRegion, /* Size of regions */
4235 int bExtend, /* True to extend file if necessary */
4236 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004237){
danda9fe0c2010-07-13 18:44:03 +00004238 unixFile *pDbFd = (unixFile*)fd;
4239 unixShm *p;
4240 unixShmNode *pShmNode;
4241 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004242
danda9fe0c2010-07-13 18:44:03 +00004243 /* If the shared-memory file has not yet been opened, open it now. */
4244 if( pDbFd->pShm==0 ){
4245 rc = unixOpenSharedMemory(pDbFd);
4246 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004247 }
drhd9e5c4f2010-05-12 18:01:39 +00004248
danda9fe0c2010-07-13 18:44:03 +00004249 p = pDbFd->pShm;
4250 pShmNode = p->pShmNode;
4251 sqlite3_mutex_enter(pShmNode->mutex);
4252 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004253 assert( pShmNode->pInode==pDbFd->pInode );
4254 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4255 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004256
4257 if( pShmNode->nRegion<=iRegion ){
4258 char **apNew; /* New apRegion[] array */
4259 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4260 struct stat sStat; /* Used by fstat() */
4261
4262 pShmNode->szRegion = szRegion;
4263
drh3cb93392011-03-12 18:10:44 +00004264 if( pShmNode->h>=0 ){
4265 /* The requested region is not mapped into this processes address space.
4266 ** Check to see if it has been allocated (i.e. if the wal-index file is
4267 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004268 */
drh3cb93392011-03-12 18:10:44 +00004269 if( osFstat(pShmNode->h, &sStat) ){
4270 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004271 goto shmpage_out;
4272 }
drh3cb93392011-03-12 18:10:44 +00004273
4274 if( sStat.st_size<nByte ){
4275 /* The requested memory region does not exist. If bExtend is set to
4276 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4277 **
4278 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4279 ** the requested memory region.
4280 */
4281 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004282#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4283 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4284 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4285 pShmNode->zFilename);
4286 goto shmpage_out;
4287 }
4288#else
drh3cb93392011-03-12 18:10:44 +00004289 if( robust_ftruncate(pShmNode->h, nByte) ){
4290 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4291 pShmNode->zFilename);
4292 goto shmpage_out;
4293 }
drh0fbb50e2012-11-13 10:54:12 +00004294#endif
drh3cb93392011-03-12 18:10:44 +00004295 }
danda9fe0c2010-07-13 18:44:03 +00004296 }
4297
4298 /* Map the requested memory region into this processes address space. */
4299 apNew = (char **)sqlite3_realloc(
4300 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4301 );
4302 if( !apNew ){
4303 rc = SQLITE_IOERR_NOMEM;
4304 goto shmpage_out;
4305 }
4306 pShmNode->apRegion = apNew;
4307 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004308 void *pMem;
4309 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004310 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004311 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004312 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004313 );
4314 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004315 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004316 goto shmpage_out;
4317 }
4318 }else{
4319 pMem = sqlite3_malloc(szRegion);
4320 if( pMem==0 ){
4321 rc = SQLITE_NOMEM;
4322 goto shmpage_out;
4323 }
4324 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004325 }
4326 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4327 pShmNode->nRegion++;
4328 }
4329 }
4330
4331shmpage_out:
4332 if( pShmNode->nRegion>iRegion ){
4333 *pp = pShmNode->apRegion[iRegion];
4334 }else{
4335 *pp = 0;
4336 }
drh66dfec8b2011-06-01 20:01:49 +00004337 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004338 sqlite3_mutex_leave(pShmNode->mutex);
4339 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004340}
4341
4342/*
drhd9e5c4f2010-05-12 18:01:39 +00004343** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004344**
4345** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4346** different here than in posix. In xShmLock(), one can go from unlocked
4347** to shared and back or from unlocked to exclusive and back. But one may
4348** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004349*/
4350static int unixShmLock(
4351 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004352 int ofst, /* First lock to acquire or release */
4353 int n, /* Number of locks to acquire or release */
4354 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004355){
drh73b64e42010-05-30 19:55:15 +00004356 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4357 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4358 unixShm *pX; /* For looping over all siblings */
4359 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4360 int rc = SQLITE_OK; /* Result code */
4361 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004362
drhd91c68f2010-05-14 14:52:25 +00004363 assert( pShmNode==pDbFd->pInode->pShmNode );
4364 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004365 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004366 assert( n>=1 );
4367 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4368 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4369 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4370 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4371 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004372 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4373 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004374
drhc99597c2010-05-31 01:41:15 +00004375 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004376 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004377 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004378 if( flags & SQLITE_SHM_UNLOCK ){
4379 u16 allMask = 0; /* Mask of locks held by siblings */
4380
4381 /* See if any siblings hold this same lock */
4382 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4383 if( pX==p ) continue;
4384 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4385 allMask |= pX->sharedMask;
4386 }
4387
4388 /* Unlock the system-level locks */
4389 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004390 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004391 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004392 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004393 }
drh73b64e42010-05-30 19:55:15 +00004394
4395 /* Undo the local locks */
4396 if( rc==SQLITE_OK ){
4397 p->exclMask &= ~mask;
4398 p->sharedMask &= ~mask;
4399 }
4400 }else if( flags & SQLITE_SHM_SHARED ){
4401 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4402
4403 /* Find out which shared locks are already held by sibling connections.
4404 ** If any sibling already holds an exclusive lock, go ahead and return
4405 ** SQLITE_BUSY.
4406 */
4407 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004408 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004409 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004410 break;
4411 }
4412 allShared |= pX->sharedMask;
4413 }
4414
4415 /* Get shared locks at the system level, if necessary */
4416 if( rc==SQLITE_OK ){
4417 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004418 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004419 }else{
drh73b64e42010-05-30 19:55:15 +00004420 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004421 }
drhd9e5c4f2010-05-12 18:01:39 +00004422 }
drh73b64e42010-05-30 19:55:15 +00004423
4424 /* Get the local shared locks */
4425 if( rc==SQLITE_OK ){
4426 p->sharedMask |= mask;
4427 }
4428 }else{
4429 /* Make sure no sibling connections hold locks that will block this
4430 ** lock. If any do, return SQLITE_BUSY right away.
4431 */
4432 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004433 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4434 rc = SQLITE_BUSY;
4435 break;
4436 }
4437 }
4438
4439 /* Get the exclusive locks at the system level. Then if successful
4440 ** also mark the local connection as being locked.
4441 */
4442 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004443 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004444 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004445 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004446 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004447 }
drhd9e5c4f2010-05-12 18:01:39 +00004448 }
4449 }
drhd91c68f2010-05-14 14:52:25 +00004450 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004451 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4452 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004453 return rc;
4454}
4455
drh286a2882010-05-20 23:51:06 +00004456/*
4457** Implement a memory barrier or memory fence on shared memory.
4458**
4459** All loads and stores begun before the barrier must complete before
4460** any load or store begun after the barrier.
4461*/
4462static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004463 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004464){
drhff828942010-06-26 21:34:06 +00004465 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004466 unixEnterMutex();
4467 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004468}
4469
dan18801912010-06-14 14:07:50 +00004470/*
danda9fe0c2010-07-13 18:44:03 +00004471** Close a connection to shared-memory. Delete the underlying
4472** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004473**
4474** If there is no shared memory associated with the connection then this
4475** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004476*/
danda9fe0c2010-07-13 18:44:03 +00004477static int unixShmUnmap(
4478 sqlite3_file *fd, /* The underlying database file */
4479 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004480){
danda9fe0c2010-07-13 18:44:03 +00004481 unixShm *p; /* The connection to be closed */
4482 unixShmNode *pShmNode; /* The underlying shared-memory file */
4483 unixShm **pp; /* For looping over sibling connections */
4484 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004485
danda9fe0c2010-07-13 18:44:03 +00004486 pDbFd = (unixFile*)fd;
4487 p = pDbFd->pShm;
4488 if( p==0 ) return SQLITE_OK;
4489 pShmNode = p->pShmNode;
4490
4491 assert( pShmNode==pDbFd->pInode->pShmNode );
4492 assert( pShmNode->pInode==pDbFd->pInode );
4493
4494 /* Remove connection p from the set of connections associated
4495 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004496 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004497 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4498 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004499
danda9fe0c2010-07-13 18:44:03 +00004500 /* Free the connection p */
4501 sqlite3_free(p);
4502 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004503 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004504
4505 /* If pShmNode->nRef has reached 0, then close the underlying
4506 ** shared-memory file, too */
4507 unixEnterMutex();
4508 assert( pShmNode->nRef>0 );
4509 pShmNode->nRef--;
4510 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004511 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004512 unixShmPurge(pDbFd);
4513 }
4514 unixLeaveMutex();
4515
4516 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004517}
drh286a2882010-05-20 23:51:06 +00004518
danda9fe0c2010-07-13 18:44:03 +00004519
drhd9e5c4f2010-05-12 18:01:39 +00004520#else
drh6b017cc2010-06-14 18:01:46 +00004521# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004522# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004523# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004524# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004525#endif /* #ifndef SQLITE_OMIT_WAL */
4526
drh734c9862008-11-28 15:37:20 +00004527/*
danaef49d72013-03-25 16:28:54 +00004528** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004529*/
danf23da962013-03-23 21:00:41 +00004530static void unixUnmapfile(unixFile *pFd){
4531 assert( pFd->nFetchOut==0 );
drh6e0b6d52013-04-09 16:19:20 +00004532#ifndef SQLITE_DISABLE_MMAP
danf23da962013-03-23 21:00:41 +00004533 if( pFd->pMapRegion ){
drhd1ab8062013-03-25 20:50:25 +00004534 osMunmap(pFd->pMapRegion, pFd->mmapOrigsize);
danf23da962013-03-23 21:00:41 +00004535 pFd->pMapRegion = 0;
4536 pFd->mmapSize = 0;
4537 pFd->mmapOrigsize = 0;
4538 }
drh6e0b6d52013-04-09 16:19:20 +00004539#endif
danf23da962013-03-23 21:00:41 +00004540}
dan5d8a1372013-03-19 19:28:06 +00004541
danaef49d72013-03-25 16:28:54 +00004542/*
dane6ecd662013-04-01 17:56:59 +00004543** Return the system page size.
4544*/
4545static int unixGetPagesize(void){
4546#if HAVE_MREMAP
4547 return 512;
drh85830a72013-04-03 00:42:01 +00004548#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004549 return getpagesize();
4550#else
4551 return (int)sysconf(_SC_PAGESIZE);
4552#endif
4553}
4554
drh6e0b6d52013-04-09 16:19:20 +00004555#ifndef SQLITE_DISABLE_MMAP
dane6ecd662013-04-01 17:56:59 +00004556/*
4557** Attempt to set the size of the memory mapping maintained by file
4558** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4559**
4560** If successful, this function sets the following variables:
4561**
4562** unixFile.pMapRegion
4563** unixFile.mmapSize
4564** unixFile.mmapOrigsize
4565**
4566** If unsuccessful, an error message is logged via sqlite3_log() and
4567** the three variables above are zeroed. In this case SQLite should
4568** continue accessing the database using the xRead() and xWrite()
4569** methods.
4570*/
4571static void unixRemapfile(
4572 unixFile *pFd, /* File descriptor object */
4573 i64 nNew /* Required mapping size */
4574){
dan4ff7bc42013-04-02 12:04:09 +00004575 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004576 int h = pFd->h; /* File descriptor open on db file */
4577 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
4578 i64 nOrig = pFd->mmapOrigsize; /* Size of pOrig region in bytes */
4579 u8 *pNew = 0; /* Location of new mapping */
4580 int flags = PROT_READ; /* Flags to pass to mmap() */
4581
4582 assert( pFd->nFetchOut==0 );
4583 assert( nNew>pFd->mmapSize );
4584 assert( nNew<=pFd->mmapLimit );
4585 assert( nNew>0 );
4586 assert( pFd->mmapOrigsize>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004587 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004588
4589 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4590
4591 if( pOrig ){
4592 const int szSyspage = unixGetPagesize();
4593 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4594 u8 *pReq = &pOrig[nReuse];
4595
4596 /* Unmap any pages of the existing mapping that cannot be reused. */
4597 if( nReuse!=nOrig ){
4598 osMunmap(pReq, nOrig-nReuse);
4599 }
4600
4601#if HAVE_MREMAP
4602 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004603 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004604#else
4605 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4606 if( pNew!=MAP_FAILED ){
4607 if( pNew!=pReq ){
4608 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004609 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004610 }else{
4611 pNew = pOrig;
4612 }
4613 }
4614#endif
4615
dan48ccef82013-04-02 20:55:01 +00004616 /* The attempt to extend the existing mapping failed. Free it. */
4617 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004618 osMunmap(pOrig, nReuse);
4619 }
4620 }
4621
4622 /* If pNew is still NULL, try to create an entirely new mapping. */
4623 if( pNew==0 ){
4624 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004625 }
4626
dan4ff7bc42013-04-02 12:04:09 +00004627 if( pNew==MAP_FAILED ){
4628 pNew = 0;
4629 nNew = 0;
4630 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4631
4632 /* If the mmap() above failed, assume that all subsequent mmap() calls
4633 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4634 ** in this case. */
4635 pFd->mmapLimit = 0;
4636 }
dane6ecd662013-04-01 17:56:59 +00004637 pFd->pMapRegion = (void *)pNew;
4638 pFd->mmapSize = pFd->mmapOrigsize = nNew;
4639}
drh6e0b6d52013-04-09 16:19:20 +00004640#endif
dane6ecd662013-04-01 17:56:59 +00004641
4642/*
danaef49d72013-03-25 16:28:54 +00004643** Memory map or remap the file opened by file-descriptor pFd (if the file
4644** is already mapped, the existing mapping is replaced by the new). Or, if
4645** there already exists a mapping for this file, and there are still
4646** outstanding xFetch() references to it, this function is a no-op.
4647**
4648** If parameter nByte is non-negative, then it is the requested size of
4649** the mapping to create. Otherwise, if nByte is less than zero, then the
4650** requested size is the size of the file on disk. The actual size of the
4651** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004652** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004653**
4654** SQLITE_OK is returned if no error occurs (even if the mapping is not
4655** recreated as a result of outstanding references) or an SQLite error
4656** code otherwise.
4657*/
danf23da962013-03-23 21:00:41 +00004658static int unixMapfile(unixFile *pFd, i64 nByte){
4659 i64 nMap = nByte;
4660 int rc;
daneb97b292013-03-20 14:26:59 +00004661
drh6e0b6d52013-04-09 16:19:20 +00004662#ifndef SQLITE_DISABLE_MMAP
danf23da962013-03-23 21:00:41 +00004663 assert( nMap>=0 || pFd->nFetchOut==0 );
4664 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4665
4666 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004667 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004668 rc = osFstat(pFd->h, &statbuf);
4669 if( rc!=SQLITE_OK ){
4670 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004671 }
danf23da962013-03-23 21:00:41 +00004672 nMap = statbuf.st_size;
4673 }
4674 if( nMap>pFd->mmapLimit ){
4675 nMap = pFd->mmapLimit;
daneb97b292013-03-20 14:26:59 +00004676 }
4677
danf23da962013-03-23 21:00:41 +00004678 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004679 if( nMap>0 ){
4680 unixRemapfile(pFd, nMap);
4681 }else{
danb7e3a322013-03-25 20:30:13 +00004682 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004683 }
4684 }
drh6e0b6d52013-04-09 16:19:20 +00004685#endif
dan5d8a1372013-03-19 19:28:06 +00004686
danf23da962013-03-23 21:00:41 +00004687 return SQLITE_OK;
4688}
4689
danaef49d72013-03-25 16:28:54 +00004690/*
4691** If possible, return a pointer to a mapping of file fd starting at offset
4692** iOff. The mapping must be valid for at least nAmt bytes.
4693**
4694** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4695** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4696** Finally, if an error does occur, return an SQLite error code. The final
4697** value of *pp is undefined in this case.
4698**
4699** If this function does return a pointer, the caller must eventually
4700** release the reference by calling unixUnfetch().
4701*/
danf23da962013-03-23 21:00:41 +00004702static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4703 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4704 *pp = 0;
4705
drh6e0b6d52013-04-09 16:19:20 +00004706#ifndef SQLITE_DISABLE_MMAP
danf23da962013-03-23 21:00:41 +00004707 if( pFd->mmapLimit>0 ){
4708 if( pFd->pMapRegion==0 ){
4709 int rc = unixMapfile(pFd, -1);
4710 if( rc!=SQLITE_OK ) return rc;
4711 }
4712 if( pFd->mmapSize >= iOff+nAmt ){
4713 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4714 pFd->nFetchOut++;
4715 }
4716 }
drh6e0b6d52013-04-09 16:19:20 +00004717#endif
danf23da962013-03-23 21:00:41 +00004718 return SQLITE_OK;
4719}
4720
danaef49d72013-03-25 16:28:54 +00004721/*
dandf737fe2013-03-25 17:00:24 +00004722** If the third argument is non-NULL, then this function releases a
4723** reference obtained by an earlier call to unixFetch(). The second
4724** argument passed to this function must be the same as the corresponding
4725** argument that was passed to the unixFetch() invocation.
4726**
4727** Or, if the third argument is NULL, then this function is being called
4728** to inform the VFS layer that, according to POSIX, any existing mapping
4729** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004730*/
dandf737fe2013-03-25 17:00:24 +00004731static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004732 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4733
danaef49d72013-03-25 16:28:54 +00004734 /* If p==0 (unmap the entire file) then there must be no outstanding
4735 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4736 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004737 assert( (p==0)==(pFd->nFetchOut==0) );
4738
dandf737fe2013-03-25 17:00:24 +00004739 /* If p!=0, it must match the iOff value. */
4740 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4741
danf23da962013-03-23 21:00:41 +00004742 if( p ){
4743 pFd->nFetchOut--;
4744 }else{
4745 unixUnmapfile(pFd);
4746 }
4747
4748 assert( pFd->nFetchOut>=0 );
4749 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004750}
4751
4752/*
drh734c9862008-11-28 15:37:20 +00004753** Here ends the implementation of all sqlite3_file methods.
4754**
4755********************** End sqlite3_file Methods *******************************
4756******************************************************************************/
4757
4758/*
drh6b9d6dd2008-12-03 19:34:47 +00004759** This division contains definitions of sqlite3_io_methods objects that
4760** implement various file locking strategies. It also contains definitions
4761** of "finder" functions. A finder-function is used to locate the appropriate
4762** sqlite3_io_methods object for a particular database file. The pAppData
4763** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4764** the correct finder-function for that VFS.
4765**
4766** Most finder functions return a pointer to a fixed sqlite3_io_methods
4767** object. The only interesting finder-function is autolockIoFinder, which
4768** looks at the filesystem type and tries to guess the best locking
4769** strategy from that.
4770**
drh1875f7a2008-12-08 18:19:17 +00004771** For finder-funtion F, two objects are created:
4772**
4773** (1) The real finder-function named "FImpt()".
4774**
dane946c392009-08-22 11:39:46 +00004775** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004776**
4777**
4778** A pointer to the F pointer is used as the pAppData value for VFS
4779** objects. We have to do this instead of letting pAppData point
4780** directly at the finder-function since C90 rules prevent a void*
4781** from be cast into a function pointer.
4782**
drh6b9d6dd2008-12-03 19:34:47 +00004783**
drh7708e972008-11-29 00:56:52 +00004784** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004785**
drh7708e972008-11-29 00:56:52 +00004786** * A constant sqlite3_io_methods object call METHOD that has locking
4787** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4788**
4789** * An I/O method finder function called FINDER that returns a pointer
4790** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004791*/
drhd9e5c4f2010-05-12 18:01:39 +00004792#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004793static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004794 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004795 CLOSE, /* xClose */ \
4796 unixRead, /* xRead */ \
4797 unixWrite, /* xWrite */ \
4798 unixTruncate, /* xTruncate */ \
4799 unixSync, /* xSync */ \
4800 unixFileSize, /* xFileSize */ \
4801 LOCK, /* xLock */ \
4802 UNLOCK, /* xUnlock */ \
4803 CKLOCK, /* xCheckReservedLock */ \
4804 unixFileControl, /* xFileControl */ \
4805 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004806 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004807 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004808 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004809 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004810 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004811 unixFetch, /* xFetch */ \
4812 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004813}; \
drh0c2694b2009-09-03 16:23:44 +00004814static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4815 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004816 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004817} \
drh0c2694b2009-09-03 16:23:44 +00004818static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004819 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004820
4821/*
4822** Here are all of the sqlite3_io_methods objects for each of the
4823** locking strategies. Functions that return pointers to these methods
4824** are also created.
4825*/
4826IOMETHODS(
4827 posixIoFinder, /* Finder function name */
4828 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004829 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004830 unixClose, /* xClose method */
4831 unixLock, /* xLock method */
4832 unixUnlock, /* xUnlock method */
4833 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004834)
drh7708e972008-11-29 00:56:52 +00004835IOMETHODS(
4836 nolockIoFinder, /* Finder function name */
4837 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004838 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004839 nolockClose, /* xClose method */
4840 nolockLock, /* xLock method */
4841 nolockUnlock, /* xUnlock method */
4842 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004843)
drh7708e972008-11-29 00:56:52 +00004844IOMETHODS(
4845 dotlockIoFinder, /* Finder function name */
4846 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004847 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004848 dotlockClose, /* xClose method */
4849 dotlockLock, /* xLock method */
4850 dotlockUnlock, /* xUnlock method */
4851 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004852)
drh7708e972008-11-29 00:56:52 +00004853
chw78a13182009-04-07 05:35:03 +00004854#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004855IOMETHODS(
4856 flockIoFinder, /* Finder function name */
4857 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004858 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004859 flockClose, /* xClose method */
4860 flockLock, /* xLock method */
4861 flockUnlock, /* xUnlock method */
4862 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004863)
drh7708e972008-11-29 00:56:52 +00004864#endif
4865
drh6c7d5c52008-11-21 20:32:33 +00004866#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004867IOMETHODS(
4868 semIoFinder, /* Finder function name */
4869 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004870 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004871 semClose, /* xClose method */
4872 semLock, /* xLock method */
4873 semUnlock, /* xUnlock method */
4874 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004875)
aswiftaebf4132008-11-21 00:10:35 +00004876#endif
drh7708e972008-11-29 00:56:52 +00004877
drhd2cb50b2009-01-09 21:41:17 +00004878#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004879IOMETHODS(
4880 afpIoFinder, /* Finder function name */
4881 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004882 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004883 afpClose, /* xClose method */
4884 afpLock, /* xLock method */
4885 afpUnlock, /* xUnlock method */
4886 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004887)
drh715ff302008-12-03 22:32:44 +00004888#endif
4889
4890/*
4891** The proxy locking method is a "super-method" in the sense that it
4892** opens secondary file descriptors for the conch and lock files and
4893** it uses proxy, dot-file, AFP, and flock() locking methods on those
4894** secondary files. For this reason, the division that implements
4895** proxy locking is located much further down in the file. But we need
4896** to go ahead and define the sqlite3_io_methods and finder function
4897** for proxy locking here. So we forward declare the I/O methods.
4898*/
drhd2cb50b2009-01-09 21:41:17 +00004899#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004900static int proxyClose(sqlite3_file*);
4901static int proxyLock(sqlite3_file*, int);
4902static int proxyUnlock(sqlite3_file*, int);
4903static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004904IOMETHODS(
4905 proxyIoFinder, /* Finder function name */
4906 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004907 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004908 proxyClose, /* xClose method */
4909 proxyLock, /* xLock method */
4910 proxyUnlock, /* xUnlock method */
4911 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004912)
aswiftaebf4132008-11-21 00:10:35 +00004913#endif
drh7708e972008-11-29 00:56:52 +00004914
drh7ed97b92010-01-20 13:07:21 +00004915/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4916#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4917IOMETHODS(
4918 nfsIoFinder, /* Finder function name */
4919 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004920 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004921 unixClose, /* xClose method */
4922 unixLock, /* xLock method */
4923 nfsUnlock, /* xUnlock method */
4924 unixCheckReservedLock /* xCheckReservedLock method */
4925)
4926#endif
drh7708e972008-11-29 00:56:52 +00004927
drhd2cb50b2009-01-09 21:41:17 +00004928#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004929/*
drh6b9d6dd2008-12-03 19:34:47 +00004930** This "finder" function attempts to determine the best locking strategy
4931** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004932** object that implements that strategy.
4933**
4934** This is for MacOSX only.
4935*/
drh1875f7a2008-12-08 18:19:17 +00004936static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004937 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004938 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004939){
4940 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004941 const char *zFilesystem; /* Filesystem type name */
4942 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004943 } aMap[] = {
4944 { "hfs", &posixIoMethods },
4945 { "ufs", &posixIoMethods },
4946 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004947 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004948 { "webdav", &nolockIoMethods },
4949 { 0, 0 }
4950 };
4951 int i;
4952 struct statfs fsInfo;
4953 struct flock lockInfo;
4954
4955 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004956 /* If filePath==NULL that means we are dealing with a transient file
4957 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004958 return &nolockIoMethods;
4959 }
4960 if( statfs(filePath, &fsInfo) != -1 ){
4961 if( fsInfo.f_flags & MNT_RDONLY ){
4962 return &nolockIoMethods;
4963 }
4964 for(i=0; aMap[i].zFilesystem; i++){
4965 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4966 return aMap[i].pMethods;
4967 }
4968 }
4969 }
4970
4971 /* Default case. Handles, amongst others, "nfs".
4972 ** Test byte-range lock using fcntl(). If the call succeeds,
4973 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004974 */
drh7708e972008-11-29 00:56:52 +00004975 lockInfo.l_len = 1;
4976 lockInfo.l_start = 0;
4977 lockInfo.l_whence = SEEK_SET;
4978 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004979 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004980 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4981 return &nfsIoMethods;
4982 } else {
4983 return &posixIoMethods;
4984 }
drh7708e972008-11-29 00:56:52 +00004985 }else{
4986 return &dotlockIoMethods;
4987 }
4988}
drh0c2694b2009-09-03 16:23:44 +00004989static const sqlite3_io_methods
4990 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004991
drhd2cb50b2009-01-09 21:41:17 +00004992#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004993
chw78a13182009-04-07 05:35:03 +00004994#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4995/*
4996** This "finder" function attempts to determine the best locking strategy
4997** for the database file "filePath". It then returns the sqlite3_io_methods
4998** object that implements that strategy.
4999**
5000** This is for VXWorks only.
5001*/
5002static const sqlite3_io_methods *autolockIoFinderImpl(
5003 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005004 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005005){
5006 struct flock lockInfo;
5007
5008 if( !filePath ){
5009 /* If filePath==NULL that means we are dealing with a transient file
5010 ** that does not need to be locked. */
5011 return &nolockIoMethods;
5012 }
5013
5014 /* Test if fcntl() is supported and use POSIX style locks.
5015 ** Otherwise fall back to the named semaphore method.
5016 */
5017 lockInfo.l_len = 1;
5018 lockInfo.l_start = 0;
5019 lockInfo.l_whence = SEEK_SET;
5020 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005021 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005022 return &posixIoMethods;
5023 }else{
5024 return &semIoMethods;
5025 }
5026}
drh0c2694b2009-09-03 16:23:44 +00005027static const sqlite3_io_methods
5028 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005029
5030#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5031
drh7708e972008-11-29 00:56:52 +00005032/*
5033** An abstract type for a pointer to a IO method finder function:
5034*/
drh0c2694b2009-09-03 16:23:44 +00005035typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005036
aswiftaebf4132008-11-21 00:10:35 +00005037
drh734c9862008-11-28 15:37:20 +00005038/****************************************************************************
5039**************************** sqlite3_vfs methods ****************************
5040**
5041** This division contains the implementation of methods on the
5042** sqlite3_vfs object.
5043*/
5044
danielk1977a3d4c882007-03-23 10:08:38 +00005045/*
danielk1977e339d652008-06-28 11:23:00 +00005046** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005047*/
5048static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005049 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005050 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005051 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005052 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005053 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005054){
drh7708e972008-11-29 00:56:52 +00005055 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005056 unixFile *pNew = (unixFile *)pId;
5057 int rc = SQLITE_OK;
5058
drh8af6c222010-05-14 12:43:01 +00005059 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005060
dan00157392010-10-05 11:33:15 +00005061 /* Usually the path zFilename should not be a relative pathname. The
5062 ** exception is when opening the proxy "conch" file in builds that
5063 ** include the special Apple locking styles.
5064 */
dan00157392010-10-05 11:33:15 +00005065#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005066 assert( zFilename==0 || zFilename[0]=='/'
5067 || pVfs->pAppData==(void*)&autolockIoFinder );
5068#else
5069 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005070#endif
dan00157392010-10-05 11:33:15 +00005071
drhb07028f2011-10-14 21:49:18 +00005072 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005073 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005074
drh308c2a52010-05-14 11:30:18 +00005075 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005076 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005077 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005078 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005079 pNew->ctrlFlags = (u8)ctrlFlags;
drh2b8246e2013-04-03 10:50:02 +00005080 pNew->mmapLimit = sqlite3GlobalConfig.mxMmap;
drhc02a43a2012-01-10 23:18:38 +00005081 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5082 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005083 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005084 }
drh503a6862013-03-01 01:07:17 +00005085 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005086 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005087 }
drh339eb0b2008-03-07 15:34:11 +00005088
drh6c7d5c52008-11-21 20:32:33 +00005089#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005090 pNew->pId = vxworksFindFileId(zFilename);
5091 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005092 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005093 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005094 }
5095#endif
5096
drhc02a43a2012-01-10 23:18:38 +00005097 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005098 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005099 }else{
drh0c2694b2009-09-03 16:23:44 +00005100 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005101#if SQLITE_ENABLE_LOCKING_STYLE
5102 /* Cache zFilename in the locking context (AFP and dotlock override) for
5103 ** proxyLock activation is possible (remote proxy is based on db name)
5104 ** zFilename remains valid until file is closed, to support */
5105 pNew->lockingContext = (void*)zFilename;
5106#endif
drhda0e7682008-07-30 15:27:54 +00005107 }
danielk1977e339d652008-06-28 11:23:00 +00005108
drh7ed97b92010-01-20 13:07:21 +00005109 if( pLockingStyle == &posixIoMethods
5110#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5111 || pLockingStyle == &nfsIoMethods
5112#endif
5113 ){
drh7708e972008-11-29 00:56:52 +00005114 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005115 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005116 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005117 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005118 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005119 ** in two scenarios:
5120 **
5121 ** (a) A call to fstat() failed.
5122 ** (b) A malloc failed.
5123 **
5124 ** Scenario (b) may only occur if the process is holding no other
5125 ** file descriptors open on the same file. If there were other file
5126 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005127 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005128 ** handle h - as it is guaranteed that no posix locks will be released
5129 ** by doing so.
5130 **
5131 ** If scenario (a) caused the error then things are not so safe. The
5132 ** implicit assumption here is that if fstat() fails, things are in
5133 ** such bad shape that dropping a lock or two doesn't matter much.
5134 */
drh0e9365c2011-03-02 02:08:13 +00005135 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005136 h = -1;
5137 }
drh7708e972008-11-29 00:56:52 +00005138 unixLeaveMutex();
5139 }
danielk1977e339d652008-06-28 11:23:00 +00005140
drhd2cb50b2009-01-09 21:41:17 +00005141#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005142 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005143 /* AFP locking uses the file path so it needs to be included in
5144 ** the afpLockingContext.
5145 */
5146 afpLockingContext *pCtx;
5147 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5148 if( pCtx==0 ){
5149 rc = SQLITE_NOMEM;
5150 }else{
5151 /* NB: zFilename exists and remains valid until the file is closed
5152 ** according to requirement F11141. So we do not need to make a
5153 ** copy of the filename. */
5154 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005155 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005156 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005157 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005158 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005159 if( rc!=SQLITE_OK ){
5160 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005161 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005162 h = -1;
5163 }
drh7708e972008-11-29 00:56:52 +00005164 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005165 }
drh7708e972008-11-29 00:56:52 +00005166 }
5167#endif
danielk1977e339d652008-06-28 11:23:00 +00005168
drh7708e972008-11-29 00:56:52 +00005169 else if( pLockingStyle == &dotlockIoMethods ){
5170 /* Dotfile locking uses the file path so it needs to be included in
5171 ** the dotlockLockingContext
5172 */
5173 char *zLockFile;
5174 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005175 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005176 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005177 zLockFile = (char *)sqlite3_malloc(nFilename);
5178 if( zLockFile==0 ){
5179 rc = SQLITE_NOMEM;
5180 }else{
5181 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005182 }
drh7708e972008-11-29 00:56:52 +00005183 pNew->lockingContext = zLockFile;
5184 }
danielk1977e339d652008-06-28 11:23:00 +00005185
drh6c7d5c52008-11-21 20:32:33 +00005186#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005187 else if( pLockingStyle == &semIoMethods ){
5188 /* Named semaphore locking uses the file path so it needs to be
5189 ** included in the semLockingContext
5190 */
5191 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005192 rc = findInodeInfo(pNew, &pNew->pInode);
5193 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5194 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005195 int n;
drh2238dcc2009-08-27 17:56:20 +00005196 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005197 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005198 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005199 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005200 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5201 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005202 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005203 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005204 }
chw97185482008-11-17 08:05:31 +00005205 }
drh7708e972008-11-29 00:56:52 +00005206 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005207 }
drh7708e972008-11-29 00:56:52 +00005208#endif
aswift5b1a2562008-08-22 00:22:35 +00005209
5210 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005211#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005212 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005213 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005214 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005215 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00005216 isDelete = 0;
5217 }
drhc02a43a2012-01-10 23:18:38 +00005218 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005219#endif
danielk1977e339d652008-06-28 11:23:00 +00005220 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005221 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005222 }else{
drh7708e972008-11-29 00:56:52 +00005223 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005224 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00005225 }
danielk1977e339d652008-06-28 11:23:00 +00005226 return rc;
drh054889e2005-11-30 03:20:31 +00005227}
drh9c06c952005-11-26 00:25:00 +00005228
danielk1977ad94b582007-08-20 06:44:22 +00005229/*
drh8b3cf822010-06-01 21:02:51 +00005230** Return the name of a directory in which to put temporary files.
5231** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005232*/
drh7234c6d2010-06-19 15:10:09 +00005233static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005234 static const char *azDirs[] = {
5235 0,
aswiftaebf4132008-11-21 00:10:35 +00005236 0,
danielk197717b90b52008-06-06 11:11:25 +00005237 "/var/tmp",
5238 "/usr/tmp",
5239 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005240 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005241 };
drh8b3cf822010-06-01 21:02:51 +00005242 unsigned int i;
5243 struct stat buf;
5244 const char *zDir = 0;
5245
5246 azDirs[0] = sqlite3_temp_directory;
5247 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005248 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005249 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005250 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005251 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005252 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005253 break;
5254 }
5255 return zDir;
5256}
5257
5258/*
5259** Create a temporary file name in zBuf. zBuf must be allocated
5260** by the calling process and must be big enough to hold at least
5261** pVfs->mxPathname bytes.
5262*/
5263static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005264 static const unsigned char zChars[] =
5265 "abcdefghijklmnopqrstuvwxyz"
5266 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5267 "0123456789";
drh41022642008-11-21 00:24:42 +00005268 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005269 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005270
5271 /* It's odd to simulate an io-error here, but really this is just
5272 ** using the io-error infrastructure to test that SQLite handles this
5273 ** function failing.
5274 */
5275 SimulateIOError( return SQLITE_IOERR );
5276
drh7234c6d2010-06-19 15:10:09 +00005277 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005278 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005279
5280 /* Check that the output buffer is large enough for the temporary file
5281 ** name. If it is not, return SQLITE_ERROR.
5282 */
drhc02a43a2012-01-10 23:18:38 +00005283 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005284 return SQLITE_ERROR;
5285 }
5286
5287 do{
drhc02a43a2012-01-10 23:18:38 +00005288 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005289 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005290 sqlite3_randomness(15, &zBuf[j]);
5291 for(i=0; i<15; i++, j++){
5292 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5293 }
5294 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005295 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005296 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005297 return SQLITE_OK;
5298}
5299
drhd2cb50b2009-01-09 21:41:17 +00005300#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005301/*
5302** Routine to transform a unixFile into a proxy-locking unixFile.
5303** Implementation in the proxy-lock division, but used by unixOpen()
5304** if SQLITE_PREFER_PROXY_LOCKING is defined.
5305*/
5306static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005307#endif
drhc66d5b62008-12-03 22:48:32 +00005308
dan08da86a2009-08-21 17:18:03 +00005309/*
5310** Search for an unused file descriptor that was opened on the database
5311** file (not a journal or master-journal file) identified by pathname
5312** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5313** argument to this function.
5314**
5315** Such a file descriptor may exist if a database connection was closed
5316** but the associated file descriptor could not be closed because some
5317** other file descriptor open on the same file is holding a file-lock.
5318** Refer to comments in the unixClose() function and the lengthy comment
5319** describing "Posix Advisory Locking" at the start of this file for
5320** further details. Also, ticket #4018.
5321**
5322** If a suitable file descriptor is found, then it is returned. If no
5323** such file descriptor is located, -1 is returned.
5324*/
dane946c392009-08-22 11:39:46 +00005325static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5326 UnixUnusedFd *pUnused = 0;
5327
5328 /* Do not search for an unused file descriptor on vxworks. Not because
5329 ** vxworks would not benefit from the change (it might, we're not sure),
5330 ** but because no way to test it is currently available. It is better
5331 ** not to risk breaking vxworks support for the sake of such an obscure
5332 ** feature. */
5333#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005334 struct stat sStat; /* Results of stat() call */
5335
5336 /* A stat() call may fail for various reasons. If this happens, it is
5337 ** almost certain that an open() call on the same path will also fail.
5338 ** For this reason, if an error occurs in the stat() call here, it is
5339 ** ignored and -1 is returned. The caller will try to open a new file
5340 ** descriptor on the same path, fail, and return an error to SQLite.
5341 **
5342 ** Even if a subsequent open() call does succeed, the consequences of
5343 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005344 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005345 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005346
5347 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005348 pInode = inodeList;
5349 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5350 || pInode->fileId.ino!=sStat.st_ino) ){
5351 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005352 }
drh8af6c222010-05-14 12:43:01 +00005353 if( pInode ){
dane946c392009-08-22 11:39:46 +00005354 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005355 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005356 pUnused = *pp;
5357 if( pUnused ){
5358 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005359 }
5360 }
5361 unixLeaveMutex();
5362 }
dane946c392009-08-22 11:39:46 +00005363#endif /* if !OS_VXWORKS */
5364 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005365}
danielk197717b90b52008-06-06 11:11:25 +00005366
5367/*
danddb0ac42010-07-14 14:48:58 +00005368** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005369** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005370** and a value suitable for passing as the third argument to open(2) is
5371** written to *pMode. If an IO error occurs, an SQLite error code is
5372** returned and the value of *pMode is not modified.
5373**
drh8c815d12012-02-13 20:16:37 +00005374** In most cases cases, this routine sets *pMode to 0, which will become
5375** an indication to robust_open() to create the file using
5376** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5377** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005378** this function queries the file-system for the permissions on the
5379** corresponding database file and sets *pMode to this value. Whenever
5380** possible, WAL and journal files are created using the same permissions
5381** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005382**
5383** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5384** original filename is unavailable. But 8_3_NAMES is only used for
5385** FAT filesystems and permissions do not matter there, so just use
5386** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005387*/
5388static int findCreateFileMode(
5389 const char *zPath, /* Path of file (possibly) being created */
5390 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005391 mode_t *pMode, /* OUT: Permissions to open file with */
5392 uid_t *pUid, /* OUT: uid to set on the file */
5393 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005394){
5395 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005396 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005397 *pUid = 0;
5398 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005399 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005400 char zDb[MAX_PATHNAME+1]; /* Database file path */
5401 int nDb; /* Number of valid bytes in zDb */
5402 struct stat sStat; /* Output of stat() on database file */
5403
dana0c989d2010-11-05 18:07:37 +00005404 /* zPath is a path to a WAL or journal file. The following block derives
5405 ** the path to the associated database file from zPath. This block handles
5406 ** the following naming conventions:
5407 **
5408 ** "<path to db>-journal"
5409 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005410 ** "<path to db>-journalNN"
5411 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005412 **
drhd337c5b2011-10-20 18:23:35 +00005413 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005414 ** used by the test_multiplex.c module.
5415 */
5416 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005417#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005418 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005419 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005420#else
5421 while( zPath[nDb]!='-' ){
5422 assert( nDb>0 );
5423 assert( zPath[nDb]!='\n' );
5424 nDb--;
5425 }
5426#endif
danddb0ac42010-07-14 14:48:58 +00005427 memcpy(zDb, zPath, nDb);
5428 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005429
drh58384f12011-07-28 00:14:45 +00005430 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005431 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005432 *pUid = sStat.st_uid;
5433 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005434 }else{
5435 rc = SQLITE_IOERR_FSTAT;
5436 }
5437 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5438 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005439 }
5440 return rc;
5441}
5442
5443/*
danielk1977ad94b582007-08-20 06:44:22 +00005444** Open the file zPath.
5445**
danielk1977b4b47412007-08-17 15:53:36 +00005446** Previously, the SQLite OS layer used three functions in place of this
5447** one:
5448**
5449** sqlite3OsOpenReadWrite();
5450** sqlite3OsOpenReadOnly();
5451** sqlite3OsOpenExclusive();
5452**
5453** These calls correspond to the following combinations of flags:
5454**
5455** ReadWrite() -> (READWRITE | CREATE)
5456** ReadOnly() -> (READONLY)
5457** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5458**
5459** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5460** true, the file was configured to be automatically deleted when the
5461** file handle closed. To achieve the same effect using this new
5462** interface, add the DELETEONCLOSE flag to those specified above for
5463** OpenExclusive().
5464*/
5465static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005466 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5467 const char *zPath, /* Pathname of file to be opened */
5468 sqlite3_file *pFile, /* The file descriptor to be filled in */
5469 int flags, /* Input flags to control the opening */
5470 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005471){
dan08da86a2009-08-21 17:18:03 +00005472 unixFile *p = (unixFile *)pFile;
5473 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005474 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005475 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005476 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005477 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005478 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005479
5480 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5481 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5482 int isCreate = (flags & SQLITE_OPEN_CREATE);
5483 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5484 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005485#if SQLITE_ENABLE_LOCKING_STYLE
5486 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5487#endif
drh3d4435b2011-08-26 20:55:50 +00005488#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5489 struct statfs fsInfo;
5490#endif
danielk1977b4b47412007-08-17 15:53:36 +00005491
danielk1977fee2d252007-08-18 10:59:19 +00005492 /* If creating a master or main-file journal, this function will open
5493 ** a file-descriptor on the directory too. The first time unixSync()
5494 ** is called the directory file descriptor will be fsync()ed and close()d.
5495 */
drh0059eae2011-08-08 23:48:40 +00005496 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005497 eType==SQLITE_OPEN_MASTER_JOURNAL
5498 || eType==SQLITE_OPEN_MAIN_JOURNAL
5499 || eType==SQLITE_OPEN_WAL
5500 ));
danielk1977fee2d252007-08-18 10:59:19 +00005501
danielk197717b90b52008-06-06 11:11:25 +00005502 /* If argument zPath is a NULL pointer, this function is required to open
5503 ** a temporary file. Use this buffer to store the file name in.
5504 */
drhc02a43a2012-01-10 23:18:38 +00005505 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005506 const char *zName = zPath;
5507
danielk1977fee2d252007-08-18 10:59:19 +00005508 /* Check the following statements are true:
5509 **
5510 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5511 ** (b) if CREATE is set, then READWRITE must also be set, and
5512 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005513 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005514 */
danielk1977b4b47412007-08-17 15:53:36 +00005515 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005516 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005517 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005518 assert(isDelete==0 || isCreate);
5519
danddb0ac42010-07-14 14:48:58 +00005520 /* The main DB, main journal, WAL file and master journal are never
5521 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005522 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5523 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5524 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005525 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005526
danielk1977fee2d252007-08-18 10:59:19 +00005527 /* Assert that the upper layer has set one of the "file-type" flags. */
5528 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5529 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5530 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005531 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005532 );
5533
dan08da86a2009-08-21 17:18:03 +00005534 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005535
dan08da86a2009-08-21 17:18:03 +00005536 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005537 UnixUnusedFd *pUnused;
5538 pUnused = findReusableFd(zName, flags);
5539 if( pUnused ){
5540 fd = pUnused->fd;
5541 }else{
dan6aa657f2009-08-24 18:57:58 +00005542 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005543 if( !pUnused ){
5544 return SQLITE_NOMEM;
5545 }
5546 }
5547 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005548
5549 /* Database filenames are double-zero terminated if they are not
5550 ** URIs with parameters. Hence, they can always be passed into
5551 ** sqlite3_uri_parameter(). */
5552 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5553
dan08da86a2009-08-21 17:18:03 +00005554 }else if( !zName ){
5555 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005556 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005557 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005558 if( rc!=SQLITE_OK ){
5559 return rc;
5560 }
5561 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005562
5563 /* Generated temporary filenames are always double-zero terminated
5564 ** for use by sqlite3_uri_parameter(). */
5565 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005566 }
5567
dan08da86a2009-08-21 17:18:03 +00005568 /* Determine the value of the flags parameter passed to POSIX function
5569 ** open(). These must be calculated even if open() is not called, as
5570 ** they may be stored as part of the file handle and used by the
5571 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005572 if( isReadonly ) openFlags |= O_RDONLY;
5573 if( isReadWrite ) openFlags |= O_RDWR;
5574 if( isCreate ) openFlags |= O_CREAT;
5575 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5576 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005577
danielk1977b4b47412007-08-17 15:53:36 +00005578 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005579 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005580 uid_t uid; /* Userid for the file */
5581 gid_t gid; /* Groupid for the file */
5582 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005583 if( rc!=SQLITE_OK ){
5584 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005585 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005586 return rc;
5587 }
drhad4f1e52011-03-04 15:43:57 +00005588 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005589 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005590 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5591 /* Failed to open the file for read/write access. Try read-only. */
5592 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005593 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005594 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005595 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005596 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005597 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005598 }
5599 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005600 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005601 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005602 }
drhac7c3ac2012-02-11 19:23:48 +00005603
5604 /* If this process is running as root and if creating a new rollback
5605 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005606 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005607 */
5608 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005609 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005610 }
danielk1977b4b47412007-08-17 15:53:36 +00005611 }
dan08da86a2009-08-21 17:18:03 +00005612 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005613 if( pOutFlags ){
5614 *pOutFlags = flags;
5615 }
5616
dane946c392009-08-22 11:39:46 +00005617 if( p->pUnused ){
5618 p->pUnused->fd = fd;
5619 p->pUnused->flags = flags;
5620 }
5621
danielk1977b4b47412007-08-17 15:53:36 +00005622 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005623#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005624 zPath = zName;
5625#else
drh036ac7f2011-08-08 23:18:05 +00005626 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005627#endif
danielk1977b4b47412007-08-17 15:53:36 +00005628 }
drh41022642008-11-21 00:24:42 +00005629#if SQLITE_ENABLE_LOCKING_STYLE
5630 else{
dan08da86a2009-08-21 17:18:03 +00005631 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005632 }
5633#endif
5634
drhda0e7682008-07-30 15:27:54 +00005635 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005636
drh7ed97b92010-01-20 13:07:21 +00005637
5638#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005639 if( fstatfs(fd, &fsInfo) == -1 ){
5640 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005641 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005642 return SQLITE_IOERR_ACCESS;
5643 }
5644 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5645 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5646 }
5647#endif
drhc02a43a2012-01-10 23:18:38 +00005648
5649 /* Set up appropriate ctrlFlags */
5650 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5651 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5652 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5653 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5654 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5655
drh7ed97b92010-01-20 13:07:21 +00005656#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005657#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005658 isAutoProxy = 1;
5659#endif
5660 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005661 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5662 int useProxy = 0;
5663
dan08da86a2009-08-21 17:18:03 +00005664 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5665 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005666 if( envforce!=NULL ){
5667 useProxy = atoi(envforce)>0;
5668 }else{
aswiftaebf4132008-11-21 00:10:35 +00005669 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005670 /* In theory, the close(fd) call is sub-optimal. If the file opened
5671 ** with fd is a database file, and there are other connections open
5672 ** on that file that are currently holding advisory locks on it,
5673 ** then the call to close() will cancel those locks. In practice,
5674 ** we're assuming that statfs() doesn't fail very often. At least
5675 ** not while other file descriptors opened by the same process on
5676 ** the same file are working. */
5677 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005678 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005679 rc = SQLITE_IOERR_ACCESS;
5680 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005681 }
5682 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5683 }
5684 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005685 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005686 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005687 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005688 if( rc!=SQLITE_OK ){
5689 /* Use unixClose to clean up the resources added in fillInUnixFile
5690 ** and clear all the structure's references. Specifically,
5691 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5692 */
5693 unixClose(pFile);
5694 return rc;
5695 }
aswiftaebf4132008-11-21 00:10:35 +00005696 }
dane946c392009-08-22 11:39:46 +00005697 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005698 }
5699 }
5700#endif
5701
drhc02a43a2012-01-10 23:18:38 +00005702 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5703
dane946c392009-08-22 11:39:46 +00005704open_finished:
5705 if( rc!=SQLITE_OK ){
5706 sqlite3_free(p->pUnused);
5707 }
5708 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005709}
5710
dane946c392009-08-22 11:39:46 +00005711
danielk1977b4b47412007-08-17 15:53:36 +00005712/*
danielk1977fee2d252007-08-18 10:59:19 +00005713** Delete the file at zPath. If the dirSync argument is true, fsync()
5714** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005715*/
drh6b9d6dd2008-12-03 19:34:47 +00005716static int unixDelete(
5717 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5718 const char *zPath, /* Name of file to be deleted */
5719 int dirSync /* If true, fsync() directory after deleting file */
5720){
danielk1977fee2d252007-08-18 10:59:19 +00005721 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005722 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005723 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005724 if( osUnlink(zPath)==(-1) ){
5725 if( errno==ENOENT ){
5726 rc = SQLITE_IOERR_DELETE_NOENT;
5727 }else{
drhb4308162012-11-09 21:40:02 +00005728 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005729 }
drhb4308162012-11-09 21:40:02 +00005730 return rc;
drh5d4feff2010-07-14 01:45:22 +00005731 }
danielk1977d39fa702008-10-16 13:27:40 +00005732#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005733 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005734 int fd;
drh90315a22011-08-10 01:52:12 +00005735 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005736 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005737#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005738 if( fsync(fd)==-1 )
5739#else
5740 if( fsync(fd) )
5741#endif
5742 {
dane18d4952011-02-21 11:46:24 +00005743 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005744 }
drh0e9365c2011-03-02 02:08:13 +00005745 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005746 }else if( rc==SQLITE_CANTOPEN ){
5747 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005748 }
5749 }
danielk1977d138dd82008-10-15 16:02:48 +00005750#endif
danielk1977fee2d252007-08-18 10:59:19 +00005751 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005752}
5753
danielk197790949c22007-08-17 16:50:38 +00005754/*
mistachkin48864df2013-03-21 21:20:32 +00005755** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005756** test performed depends on the value of flags:
5757**
5758** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5759** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5760** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5761**
5762** Otherwise return 0.
5763*/
danielk1977861f7452008-06-05 11:39:11 +00005764static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005765 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5766 const char *zPath, /* Path of the file to examine */
5767 int flags, /* What do we want to learn about the zPath file? */
5768 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005769){
rse25c0d1a2007-09-20 08:38:14 +00005770 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005771 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005772 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005773 switch( flags ){
5774 case SQLITE_ACCESS_EXISTS:
5775 amode = F_OK;
5776 break;
5777 case SQLITE_ACCESS_READWRITE:
5778 amode = W_OK|R_OK;
5779 break;
drh50d3f902007-08-27 21:10:36 +00005780 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005781 amode = R_OK;
5782 break;
5783
5784 default:
5785 assert(!"Invalid flags argument");
5786 }
drh99ab3b12011-03-02 15:09:07 +00005787 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005788 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5789 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005790 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005791 *pResOut = 0;
5792 }
5793 }
danielk1977861f7452008-06-05 11:39:11 +00005794 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005795}
5796
danielk1977b4b47412007-08-17 15:53:36 +00005797
5798/*
5799** Turn a relative pathname into a full pathname. The relative path
5800** is stored as a nul-terminated string in the buffer pointed to by
5801** zPath.
5802**
5803** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5804** (in this case, MAX_PATHNAME bytes). The full-path is written to
5805** this buffer before returning.
5806*/
danielk1977adfb9b02007-09-17 07:02:56 +00005807static int unixFullPathname(
5808 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5809 const char *zPath, /* Possibly relative input path */
5810 int nOut, /* Size of output buffer in bytes */
5811 char *zOut /* Output buffer */
5812){
danielk1977843e65f2007-09-01 16:16:15 +00005813
5814 /* It's odd to simulate an io-error here, but really this is just
5815 ** using the io-error infrastructure to test that SQLite handles this
5816 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005817 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005818 */
5819 SimulateIOError( return SQLITE_ERROR );
5820
drh153c62c2007-08-24 03:51:33 +00005821 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005822 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005823
drh3c7f2dc2007-12-06 13:26:20 +00005824 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005825 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005826 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005827 }else{
5828 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005829 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005830 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005831 }
drhea678832008-12-10 19:26:22 +00005832 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005833 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005834 }
5835 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005836}
5837
drh0ccebe72005-06-07 22:22:50 +00005838
drh761df872006-12-21 01:29:22 +00005839#ifndef SQLITE_OMIT_LOAD_EXTENSION
5840/*
5841** Interfaces for opening a shared library, finding entry points
5842** within the shared library, and closing the shared library.
5843*/
5844#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005845static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5846 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005847 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5848}
danielk197795c8a542007-09-01 06:51:27 +00005849
5850/*
5851** SQLite calls this function immediately after a call to unixDlSym() or
5852** unixDlOpen() fails (returns a null pointer). If a more detailed error
5853** message is available, it is written to zBufOut. If no error message
5854** is available, zBufOut is left unmodified and SQLite uses a default
5855** error message.
5856*/
danielk1977397d65f2008-11-19 11:35:39 +00005857static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005858 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005859 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005860 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005861 zErr = dlerror();
5862 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005863 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005864 }
drh6c7d5c52008-11-21 20:32:33 +00005865 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005866}
drh1875f7a2008-12-08 18:19:17 +00005867static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5868 /*
5869 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5870 ** cast into a pointer to a function. And yet the library dlsym() routine
5871 ** returns a void* which is really a pointer to a function. So how do we
5872 ** use dlsym() with -pedantic-errors?
5873 **
5874 ** Variable x below is defined to be a pointer to a function taking
5875 ** parameters void* and const char* and returning a pointer to a function.
5876 ** We initialize x by assigning it a pointer to the dlsym() function.
5877 ** (That assignment requires a cast.) Then we call the function that
5878 ** x points to.
5879 **
5880 ** This work-around is unlikely to work correctly on any system where
5881 ** you really cannot cast a function pointer into void*. But then, on the
5882 ** other hand, dlsym() will not work on such a system either, so we have
5883 ** not really lost anything.
5884 */
5885 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005886 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005887 x = (void(*(*)(void*,const char*))(void))dlsym;
5888 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005889}
danielk1977397d65f2008-11-19 11:35:39 +00005890static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5891 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005892 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005893}
danielk1977b4b47412007-08-17 15:53:36 +00005894#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5895 #define unixDlOpen 0
5896 #define unixDlError 0
5897 #define unixDlSym 0
5898 #define unixDlClose 0
5899#endif
5900
5901/*
danielk197790949c22007-08-17 16:50:38 +00005902** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005903*/
danielk1977397d65f2008-11-19 11:35:39 +00005904static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5905 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005906 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005907
drhbbd42a62004-05-22 17:41:58 +00005908 /* We have to initialize zBuf to prevent valgrind from reporting
5909 ** errors. The reports issued by valgrind are incorrect - we would
5910 ** prefer that the randomness be increased by making use of the
5911 ** uninitialized space in zBuf - but valgrind errors tend to worry
5912 ** some users. Rather than argue, it seems easier just to initialize
5913 ** the whole array and silence valgrind, even if that means less randomness
5914 ** in the random seed.
5915 **
5916 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005917 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005918 ** tests repeatable.
5919 */
danielk1977b4b47412007-08-17 15:53:36 +00005920 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005921#if !defined(SQLITE_TEST)
5922 {
drhc18b4042012-02-10 03:10:27 +00005923 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005924 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005925 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005926 time_t t;
5927 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005928 memcpy(zBuf, &t, sizeof(t));
5929 pid = getpid();
5930 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005931 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005932 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005933 }else{
drhc18b4042012-02-10 03:10:27 +00005934 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005935 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005936 }
drhbbd42a62004-05-22 17:41:58 +00005937 }
5938#endif
drh72cbd072008-10-14 17:58:38 +00005939 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005940}
5941
danielk1977b4b47412007-08-17 15:53:36 +00005942
drhbbd42a62004-05-22 17:41:58 +00005943/*
5944** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005945** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005946** The return value is the number of microseconds of sleep actually
5947** requested from the underlying operating system, a number which
5948** might be greater than or equal to the argument, but not less
5949** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005950*/
danielk1977397d65f2008-11-19 11:35:39 +00005951static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005952#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005953 struct timespec sp;
5954
5955 sp.tv_sec = microseconds / 1000000;
5956 sp.tv_nsec = (microseconds % 1000000) * 1000;
5957 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005958 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005959 return microseconds;
5960#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005961 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005962 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005963 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005964#else
danielk1977b4b47412007-08-17 15:53:36 +00005965 int seconds = (microseconds+999999)/1000000;
5966 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005967 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005968 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005969#endif
drh88f474a2006-01-02 20:00:12 +00005970}
5971
5972/*
drh6b9d6dd2008-12-03 19:34:47 +00005973** The following variable, if set to a non-zero value, is interpreted as
5974** the number of seconds since 1970 and is used to set the result of
5975** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005976*/
5977#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005978int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005979#endif
5980
5981/*
drhb7e8ea22010-05-03 14:32:30 +00005982** Find the current time (in Universal Coordinated Time). Write into *piNow
5983** the current time and date as a Julian Day number times 86_400_000. In
5984** other words, write into *piNow the number of milliseconds since the Julian
5985** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5986** proleptic Gregorian calendar.
5987**
drh31702252011-10-12 23:13:43 +00005988** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5989** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005990*/
5991static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5992 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005993 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005994#if defined(NO_GETTOD)
5995 time_t t;
5996 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005997 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005998#elif OS_VXWORKS
5999 struct timespec sNow;
6000 clock_gettime(CLOCK_REALTIME, &sNow);
6001 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6002#else
6003 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006004 if( gettimeofday(&sNow, 0)==0 ){
6005 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6006 }else{
6007 rc = SQLITE_ERROR;
6008 }
drhb7e8ea22010-05-03 14:32:30 +00006009#endif
6010
6011#ifdef SQLITE_TEST
6012 if( sqlite3_current_time ){
6013 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6014 }
6015#endif
6016 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006017 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006018}
6019
6020/*
drhbbd42a62004-05-22 17:41:58 +00006021** Find the current time (in Universal Coordinated Time). Write the
6022** current time and date as a Julian Day number into *prNow and
6023** return 0. Return 1 if the time and date cannot be found.
6024*/
danielk1977397d65f2008-11-19 11:35:39 +00006025static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006026 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006027 int rc;
drhff828942010-06-26 21:34:06 +00006028 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006029 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006030 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006031 return rc;
drhbbd42a62004-05-22 17:41:58 +00006032}
danielk1977b4b47412007-08-17 15:53:36 +00006033
drh6b9d6dd2008-12-03 19:34:47 +00006034/*
6035** We added the xGetLastError() method with the intention of providing
6036** better low-level error messages when operating-system problems come up
6037** during SQLite operation. But so far, none of that has been implemented
6038** in the core. So this routine is never called. For now, it is merely
6039** a place-holder.
6040*/
danielk1977397d65f2008-11-19 11:35:39 +00006041static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6042 UNUSED_PARAMETER(NotUsed);
6043 UNUSED_PARAMETER(NotUsed2);
6044 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006045 return 0;
6046}
6047
drhf2424c52010-04-26 00:04:55 +00006048
6049/*
drh734c9862008-11-28 15:37:20 +00006050************************ End of sqlite3_vfs methods ***************************
6051******************************************************************************/
6052
drh715ff302008-12-03 22:32:44 +00006053/******************************************************************************
6054************************** Begin Proxy Locking ********************************
6055**
6056** Proxy locking is a "uber-locking-method" in this sense: It uses the
6057** other locking methods on secondary lock files. Proxy locking is a
6058** meta-layer over top of the primitive locking implemented above. For
6059** this reason, the division that implements of proxy locking is deferred
6060** until late in the file (here) after all of the other I/O methods have
6061** been defined - so that the primitive locking methods are available
6062** as services to help with the implementation of proxy locking.
6063**
6064****
6065**
6066** The default locking schemes in SQLite use byte-range locks on the
6067** database file to coordinate safe, concurrent access by multiple readers
6068** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6069** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6070** as POSIX read & write locks over fixed set of locations (via fsctl),
6071** on AFP and SMB only exclusive byte-range locks are available via fsctl
6072** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6073** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6074** address in the shared range is taken for a SHARED lock, the entire
6075** shared range is taken for an EXCLUSIVE lock):
6076**
drhf2f105d2012-08-20 15:53:54 +00006077** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006078** RESERVED_BYTE 0x40000001
6079** SHARED_RANGE 0x40000002 -> 0x40000200
6080**
6081** This works well on the local file system, but shows a nearly 100x
6082** slowdown in read performance on AFP because the AFP client disables
6083** the read cache when byte-range locks are present. Enabling the read
6084** cache exposes a cache coherency problem that is present on all OS X
6085** supported network file systems. NFS and AFP both observe the
6086** close-to-open semantics for ensuring cache coherency
6087** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6088** address the requirements for concurrent database access by multiple
6089** readers and writers
6090** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6091**
6092** To address the performance and cache coherency issues, proxy file locking
6093** changes the way database access is controlled by limiting access to a
6094** single host at a time and moving file locks off of the database file
6095** and onto a proxy file on the local file system.
6096**
6097**
6098** Using proxy locks
6099** -----------------
6100**
6101** C APIs
6102**
6103** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6104** <proxy_path> | ":auto:");
6105** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6106**
6107**
6108** SQL pragmas
6109**
6110** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6111** PRAGMA [database.]lock_proxy_file
6112**
6113** Specifying ":auto:" means that if there is a conch file with a matching
6114** host ID in it, the proxy path in the conch file will be used, otherwise
6115** a proxy path based on the user's temp dir
6116** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6117** actual proxy file name is generated from the name and path of the
6118** database file. For example:
6119**
6120** For database path "/Users/me/foo.db"
6121** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6122**
6123** Once a lock proxy is configured for a database connection, it can not
6124** be removed, however it may be switched to a different proxy path via
6125** the above APIs (assuming the conch file is not being held by another
6126** connection or process).
6127**
6128**
6129** How proxy locking works
6130** -----------------------
6131**
6132** Proxy file locking relies primarily on two new supporting files:
6133**
6134** * conch file to limit access to the database file to a single host
6135** at a time
6136**
6137** * proxy file to act as a proxy for the advisory locks normally
6138** taken on the database
6139**
6140** The conch file - to use a proxy file, sqlite must first "hold the conch"
6141** by taking an sqlite-style shared lock on the conch file, reading the
6142** contents and comparing the host's unique host ID (see below) and lock
6143** proxy path against the values stored in the conch. The conch file is
6144** stored in the same directory as the database file and the file name
6145** is patterned after the database file name as ".<databasename>-conch".
6146** If the conch file does not exist, or it's contents do not match the
6147** host ID and/or proxy path, then the lock is escalated to an exclusive
6148** lock and the conch file contents is updated with the host ID and proxy
6149** path and the lock is downgraded to a shared lock again. If the conch
6150** is held by another process (with a shared lock), the exclusive lock
6151** will fail and SQLITE_BUSY is returned.
6152**
6153** The proxy file - a single-byte file used for all advisory file locks
6154** normally taken on the database file. This allows for safe sharing
6155** of the database file for multiple readers and writers on the same
6156** host (the conch ensures that they all use the same local lock file).
6157**
drh715ff302008-12-03 22:32:44 +00006158** Requesting the lock proxy does not immediately take the conch, it is
6159** only taken when the first request to lock database file is made.
6160** This matches the semantics of the traditional locking behavior, where
6161** opening a connection to a database file does not take a lock on it.
6162** The shared lock and an open file descriptor are maintained until
6163** the connection to the database is closed.
6164**
6165** The proxy file and the lock file are never deleted so they only need
6166** to be created the first time they are used.
6167**
6168** Configuration options
6169** ---------------------
6170**
6171** SQLITE_PREFER_PROXY_LOCKING
6172**
6173** Database files accessed on non-local file systems are
6174** automatically configured for proxy locking, lock files are
6175** named automatically using the same logic as
6176** PRAGMA lock_proxy_file=":auto:"
6177**
6178** SQLITE_PROXY_DEBUG
6179**
6180** Enables the logging of error messages during host id file
6181** retrieval and creation
6182**
drh715ff302008-12-03 22:32:44 +00006183** LOCKPROXYDIR
6184**
6185** Overrides the default directory used for lock proxy files that
6186** are named automatically via the ":auto:" setting
6187**
6188** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6189**
6190** Permissions to use when creating a directory for storing the
6191** lock proxy files, only used when LOCKPROXYDIR is not set.
6192**
6193**
6194** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6195** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6196** force proxy locking to be used for every database file opened, and 0
6197** will force automatic proxy locking to be disabled for all database
6198** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6199** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6200*/
6201
6202/*
6203** Proxy locking is only available on MacOSX
6204*/
drhd2cb50b2009-01-09 21:41:17 +00006205#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006206
drh715ff302008-12-03 22:32:44 +00006207/*
6208** The proxyLockingContext has the path and file structures for the remote
6209** and local proxy files in it
6210*/
6211typedef struct proxyLockingContext proxyLockingContext;
6212struct proxyLockingContext {
6213 unixFile *conchFile; /* Open conch file */
6214 char *conchFilePath; /* Name of the conch file */
6215 unixFile *lockProxy; /* Open proxy lock file */
6216 char *lockProxyPath; /* Name of the proxy lock file */
6217 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006218 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006219 void *oldLockingContext; /* Original lockingcontext to restore on close */
6220 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6221};
6222
drh7ed97b92010-01-20 13:07:21 +00006223/*
6224** The proxy lock file path for the database at dbPath is written into lPath,
6225** which must point to valid, writable memory large enough for a maxLen length
6226** file path.
drh715ff302008-12-03 22:32:44 +00006227*/
drh715ff302008-12-03 22:32:44 +00006228static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6229 int len;
6230 int dbLen;
6231 int i;
6232
6233#ifdef LOCKPROXYDIR
6234 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6235#else
6236# ifdef _CS_DARWIN_USER_TEMP_DIR
6237 {
drh7ed97b92010-01-20 13:07:21 +00006238 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006239 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6240 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006241 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006242 }
drh7ed97b92010-01-20 13:07:21 +00006243 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006244 }
6245# else
6246 len = strlcpy(lPath, "/tmp/", maxLen);
6247# endif
6248#endif
6249
6250 if( lPath[len-1]!='/' ){
6251 len = strlcat(lPath, "/", maxLen);
6252 }
6253
6254 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006255 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006256 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006257 char c = dbPath[i];
6258 lPath[i+len] = (c=='/')?'_':c;
6259 }
6260 lPath[i+len]='\0';
6261 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006262 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006263 return SQLITE_OK;
6264}
6265
drh7ed97b92010-01-20 13:07:21 +00006266/*
6267 ** Creates the lock file and any missing directories in lockPath
6268 */
6269static int proxyCreateLockPath(const char *lockPath){
6270 int i, len;
6271 char buf[MAXPATHLEN];
6272 int start = 0;
6273
6274 assert(lockPath!=NULL);
6275 /* try to create all the intermediate directories */
6276 len = (int)strlen(lockPath);
6277 buf[0] = lockPath[0];
6278 for( i=1; i<len; i++ ){
6279 if( lockPath[i] == '/' && (i - start > 0) ){
6280 /* only mkdir if leaf dir != "." or "/" or ".." */
6281 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6282 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6283 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006284 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006285 int err=errno;
6286 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006287 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006288 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006289 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006290 return err;
6291 }
6292 }
6293 }
6294 start=i+1;
6295 }
6296 buf[i] = lockPath[i];
6297 }
drh308c2a52010-05-14 11:30:18 +00006298 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006299 return 0;
6300}
6301
drh715ff302008-12-03 22:32:44 +00006302/*
6303** Create a new VFS file descriptor (stored in memory obtained from
6304** sqlite3_malloc) and open the file named "path" in the file descriptor.
6305**
6306** The caller is responsible not only for closing the file descriptor
6307** but also for freeing the memory associated with the file descriptor.
6308*/
drh7ed97b92010-01-20 13:07:21 +00006309static int proxyCreateUnixFile(
6310 const char *path, /* path for the new unixFile */
6311 unixFile **ppFile, /* unixFile created and returned by ref */
6312 int islockfile /* if non zero missing dirs will be created */
6313) {
6314 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006315 unixFile *pNew;
6316 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006317 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006318 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006319 int terrno = 0;
6320 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006321
drh7ed97b92010-01-20 13:07:21 +00006322 /* 1. first try to open/create the file
6323 ** 2. if that fails, and this is a lock file (not-conch), try creating
6324 ** the parent directories and then try again.
6325 ** 3. if that fails, try to open the file read-only
6326 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6327 */
6328 pUnused = findReusableFd(path, openFlags);
6329 if( pUnused ){
6330 fd = pUnused->fd;
6331 }else{
6332 pUnused = sqlite3_malloc(sizeof(*pUnused));
6333 if( !pUnused ){
6334 return SQLITE_NOMEM;
6335 }
6336 }
6337 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006338 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006339 terrno = errno;
6340 if( fd<0 && errno==ENOENT && islockfile ){
6341 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006342 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006343 }
6344 }
6345 }
6346 if( fd<0 ){
6347 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006348 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006349 terrno = errno;
6350 }
6351 if( fd<0 ){
6352 if( islockfile ){
6353 return SQLITE_BUSY;
6354 }
6355 switch (terrno) {
6356 case EACCES:
6357 return SQLITE_PERM;
6358 case EIO:
6359 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6360 default:
drh9978c972010-02-23 17:36:32 +00006361 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006362 }
6363 }
6364
6365 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6366 if( pNew==NULL ){
6367 rc = SQLITE_NOMEM;
6368 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006369 }
6370 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006371 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006372 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006373 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006374 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006375 pUnused->fd = fd;
6376 pUnused->flags = openFlags;
6377 pNew->pUnused = pUnused;
6378
drhc02a43a2012-01-10 23:18:38 +00006379 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006380 if( rc==SQLITE_OK ){
6381 *ppFile = pNew;
6382 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006383 }
drh7ed97b92010-01-20 13:07:21 +00006384end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006385 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006386 sqlite3_free(pNew);
6387 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006388 return rc;
6389}
6390
drh7ed97b92010-01-20 13:07:21 +00006391#ifdef SQLITE_TEST
6392/* simulate multiple hosts by creating unique hostid file paths */
6393int sqlite3_hostid_num = 0;
6394#endif
6395
6396#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6397
drh0ab216a2010-07-02 17:10:40 +00006398/* Not always defined in the headers as it ought to be */
6399extern int gethostuuid(uuid_t id, const struct timespec *wait);
6400
drh7ed97b92010-01-20 13:07:21 +00006401/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6402** bytes of writable memory.
6403*/
6404static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006405 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6406 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006407#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6408 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006409 {
6410 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6411 if( gethostuuid(pHostID, &timeout) ){
6412 int err = errno;
6413 if( pError ){
6414 *pError = err;
6415 }
6416 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006417 }
drh7ed97b92010-01-20 13:07:21 +00006418 }
drh3d4435b2011-08-26 20:55:50 +00006419#else
6420 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006421#endif
drh7ed97b92010-01-20 13:07:21 +00006422#ifdef SQLITE_TEST
6423 /* simulate multiple hosts by creating unique hostid file paths */
6424 if( sqlite3_hostid_num != 0){
6425 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6426 }
6427#endif
6428
6429 return SQLITE_OK;
6430}
6431
6432/* The conch file contains the header, host id and lock file path
6433 */
6434#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6435#define PROXY_HEADERLEN 1 /* conch file header length */
6436#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6437#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6438
6439/*
6440** Takes an open conch file, copies the contents to a new path and then moves
6441** it back. The newly created file's file descriptor is assigned to the
6442** conch file structure and finally the original conch file descriptor is
6443** closed. Returns zero if successful.
6444*/
6445static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6446 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6447 unixFile *conchFile = pCtx->conchFile;
6448 char tPath[MAXPATHLEN];
6449 char buf[PROXY_MAXCONCHLEN];
6450 char *cPath = pCtx->conchFilePath;
6451 size_t readLen = 0;
6452 size_t pathLen = 0;
6453 char errmsg[64] = "";
6454 int fd = -1;
6455 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006456 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006457
6458 /* create a new path by replace the trailing '-conch' with '-break' */
6459 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6460 if( pathLen>MAXPATHLEN || pathLen<6 ||
6461 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006462 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006463 goto end_breaklock;
6464 }
6465 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006466 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006467 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006468 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006469 goto end_breaklock;
6470 }
6471 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006472 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006473 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006474 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006475 goto end_breaklock;
6476 }
drhe562be52011-03-02 18:01:10 +00006477 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006478 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006479 goto end_breaklock;
6480 }
6481 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006482 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006483 goto end_breaklock;
6484 }
6485 rc = 0;
6486 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006487 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006488 conchFile->h = fd;
6489 conchFile->openFlags = O_RDWR | O_CREAT;
6490
6491end_breaklock:
6492 if( rc ){
6493 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006494 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006495 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006496 }
6497 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6498 }
6499 return rc;
6500}
6501
6502/* Take the requested lock on the conch file and break a stale lock if the
6503** host id matches.
6504*/
6505static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6506 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6507 unixFile *conchFile = pCtx->conchFile;
6508 int rc = SQLITE_OK;
6509 int nTries = 0;
6510 struct timespec conchModTime;
6511
drh3d4435b2011-08-26 20:55:50 +00006512 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006513 do {
6514 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6515 nTries ++;
6516 if( rc==SQLITE_BUSY ){
6517 /* If the lock failed (busy):
6518 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6519 * 2nd try: fail if the mod time changed or host id is different, wait
6520 * 10 sec and try again
6521 * 3rd try: break the lock unless the mod time has changed.
6522 */
6523 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006524 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006525 pFile->lastErrno = errno;
6526 return SQLITE_IOERR_LOCK;
6527 }
6528
6529 if( nTries==1 ){
6530 conchModTime = buf.st_mtimespec;
6531 usleep(500000); /* wait 0.5 sec and try the lock again*/
6532 continue;
6533 }
6534
6535 assert( nTries>1 );
6536 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6537 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6538 return SQLITE_BUSY;
6539 }
6540
6541 if( nTries==2 ){
6542 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006543 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006544 if( len<0 ){
6545 pFile->lastErrno = errno;
6546 return SQLITE_IOERR_LOCK;
6547 }
6548 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6549 /* don't break the lock if the host id doesn't match */
6550 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6551 return SQLITE_BUSY;
6552 }
6553 }else{
6554 /* don't break the lock on short read or a version mismatch */
6555 return SQLITE_BUSY;
6556 }
6557 usleep(10000000); /* wait 10 sec and try the lock again */
6558 continue;
6559 }
6560
6561 assert( nTries==3 );
6562 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6563 rc = SQLITE_OK;
6564 if( lockType==EXCLUSIVE_LOCK ){
6565 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6566 }
6567 if( !rc ){
6568 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6569 }
6570 }
6571 }
6572 } while( rc==SQLITE_BUSY && nTries<3 );
6573
6574 return rc;
6575}
6576
6577/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006578** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6579** lockPath means that the lockPath in the conch file will be used if the
6580** host IDs match, or a new lock path will be generated automatically
6581** and written to the conch file.
6582*/
6583static int proxyTakeConch(unixFile *pFile){
6584 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6585
drh7ed97b92010-01-20 13:07:21 +00006586 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006587 return SQLITE_OK;
6588 }else{
6589 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006590 uuid_t myHostID;
6591 int pError = 0;
6592 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006593 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006594 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006595 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006596 int createConch = 0;
6597 int hostIdMatch = 0;
6598 int readLen = 0;
6599 int tryOldLockPath = 0;
6600 int forceNewLockPath = 0;
6601
drh308c2a52010-05-14 11:30:18 +00006602 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6603 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006604
drh7ed97b92010-01-20 13:07:21 +00006605 rc = proxyGetHostID(myHostID, &pError);
6606 if( (rc&0xff)==SQLITE_IOERR ){
6607 pFile->lastErrno = pError;
6608 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006609 }
drh7ed97b92010-01-20 13:07:21 +00006610 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006611 if( rc!=SQLITE_OK ){
6612 goto end_takeconch;
6613 }
drh7ed97b92010-01-20 13:07:21 +00006614 /* read the existing conch file */
6615 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6616 if( readLen<0 ){
6617 /* I/O error: lastErrno set by seekAndRead */
6618 pFile->lastErrno = conchFile->lastErrno;
6619 rc = SQLITE_IOERR_READ;
6620 goto end_takeconch;
6621 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6622 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6623 /* a short read or version format mismatch means we need to create a new
6624 ** conch file.
6625 */
6626 createConch = 1;
6627 }
6628 /* if the host id matches and the lock path already exists in the conch
6629 ** we'll try to use the path there, if we can't open that path, we'll
6630 ** retry with a new auto-generated path
6631 */
6632 do { /* in case we need to try again for an :auto: named lock file */
6633
6634 if( !createConch && !forceNewLockPath ){
6635 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6636 PROXY_HOSTIDLEN);
6637 /* if the conch has data compare the contents */
6638 if( !pCtx->lockProxyPath ){
6639 /* for auto-named local lock file, just check the host ID and we'll
6640 ** use the local lock file path that's already in there
6641 */
6642 if( hostIdMatch ){
6643 size_t pathLen = (readLen - PROXY_PATHINDEX);
6644
6645 if( pathLen>=MAXPATHLEN ){
6646 pathLen=MAXPATHLEN-1;
6647 }
6648 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6649 lockPath[pathLen] = 0;
6650 tempLockPath = lockPath;
6651 tryOldLockPath = 1;
6652 /* create a copy of the lock path if the conch is taken */
6653 goto end_takeconch;
6654 }
6655 }else if( hostIdMatch
6656 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6657 readLen-PROXY_PATHINDEX)
6658 ){
6659 /* conch host and lock path match */
6660 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006661 }
drh7ed97b92010-01-20 13:07:21 +00006662 }
6663
6664 /* if the conch isn't writable and doesn't match, we can't take it */
6665 if( (conchFile->openFlags&O_RDWR) == 0 ){
6666 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006667 goto end_takeconch;
6668 }
drh7ed97b92010-01-20 13:07:21 +00006669
6670 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006671 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006672 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6673 tempLockPath = lockPath;
6674 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006675 }
drh7ed97b92010-01-20 13:07:21 +00006676
6677 /* update conch with host and path (this will fail if other process
6678 ** has a shared lock already), if the host id matches, use the big
6679 ** stick.
drh715ff302008-12-03 22:32:44 +00006680 */
drh7ed97b92010-01-20 13:07:21 +00006681 futimes(conchFile->h, NULL);
6682 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006683 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006684 /* We are trying for an exclusive lock but another thread in this
6685 ** same process is still holding a shared lock. */
6686 rc = SQLITE_BUSY;
6687 } else {
6688 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006689 }
drh715ff302008-12-03 22:32:44 +00006690 }else{
drh7ed97b92010-01-20 13:07:21 +00006691 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006692 }
drh7ed97b92010-01-20 13:07:21 +00006693 if( rc==SQLITE_OK ){
6694 char writeBuffer[PROXY_MAXCONCHLEN];
6695 int writeSize = 0;
6696
6697 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6698 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6699 if( pCtx->lockProxyPath!=NULL ){
6700 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6701 }else{
6702 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6703 }
6704 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006705 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006706 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6707 fsync(conchFile->h);
6708 /* If we created a new conch file (not just updated the contents of a
6709 ** valid conch file), try to match the permissions of the database
6710 */
6711 if( rc==SQLITE_OK && createConch ){
6712 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006713 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006714 if( err==0 ){
6715 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6716 S_IROTH|S_IWOTH);
6717 /* try to match the database file R/W permissions, ignore failure */
6718#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006719 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006720#else
drhff812312011-02-23 13:33:46 +00006721 do{
drhe562be52011-03-02 18:01:10 +00006722 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006723 }while( rc==(-1) && errno==EINTR );
6724 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006725 int code = errno;
6726 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6727 cmode, code, strerror(code));
6728 } else {
6729 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6730 }
6731 }else{
6732 int code = errno;
6733 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6734 err, code, strerror(code));
6735#endif
6736 }
drh715ff302008-12-03 22:32:44 +00006737 }
6738 }
drh7ed97b92010-01-20 13:07:21 +00006739 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6740
6741 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006742 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006743 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006744 int fd;
drh7ed97b92010-01-20 13:07:21 +00006745 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006746 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006747 }
6748 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006749 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006750 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006751 if( fd>=0 ){
6752 pFile->h = fd;
6753 }else{
drh9978c972010-02-23 17:36:32 +00006754 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006755 during locking */
6756 }
6757 }
6758 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6759 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6760 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6761 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6762 /* we couldn't create the proxy lock file with the old lock file path
6763 ** so try again via auto-naming
6764 */
6765 forceNewLockPath = 1;
6766 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006767 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006768 }
6769 }
6770 if( rc==SQLITE_OK ){
6771 /* Need to make a copy of path if we extracted the value
6772 ** from the conch file or the path was allocated on the stack
6773 */
6774 if( tempLockPath ){
6775 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6776 if( !pCtx->lockProxyPath ){
6777 rc = SQLITE_NOMEM;
6778 }
6779 }
6780 }
6781 if( rc==SQLITE_OK ){
6782 pCtx->conchHeld = 1;
6783
6784 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6785 afpLockingContext *afpCtx;
6786 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6787 afpCtx->dbPath = pCtx->lockProxyPath;
6788 }
6789 } else {
6790 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6791 }
drh308c2a52010-05-14 11:30:18 +00006792 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6793 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006794 return rc;
drh308c2a52010-05-14 11:30:18 +00006795 } while (1); /* in case we need to retry the :auto: lock file -
6796 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006797 }
6798}
6799
6800/*
6801** If pFile holds a lock on a conch file, then release that lock.
6802*/
6803static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006804 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006805 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6806 unixFile *conchFile; /* Name of the conch file */
6807
6808 pCtx = (proxyLockingContext *)pFile->lockingContext;
6809 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006810 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006811 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006812 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006813 if( pCtx->conchHeld>0 ){
6814 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6815 }
drh715ff302008-12-03 22:32:44 +00006816 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006817 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6818 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006819 return rc;
6820}
6821
6822/*
6823** Given the name of a database file, compute the name of its conch file.
6824** Store the conch filename in memory obtained from sqlite3_malloc().
6825** Make *pConchPath point to the new name. Return SQLITE_OK on success
6826** or SQLITE_NOMEM if unable to obtain memory.
6827**
6828** The caller is responsible for ensuring that the allocated memory
6829** space is eventually freed.
6830**
6831** *pConchPath is set to NULL if a memory allocation error occurs.
6832*/
6833static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6834 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006835 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006836 char *conchPath; /* buffer in which to construct conch name */
6837
6838 /* Allocate space for the conch filename and initialize the name to
6839 ** the name of the original database file. */
6840 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6841 if( conchPath==0 ){
6842 return SQLITE_NOMEM;
6843 }
6844 memcpy(conchPath, dbPath, len+1);
6845
6846 /* now insert a "." before the last / character */
6847 for( i=(len-1); i>=0; i-- ){
6848 if( conchPath[i]=='/' ){
6849 i++;
6850 break;
6851 }
6852 }
6853 conchPath[i]='.';
6854 while ( i<len ){
6855 conchPath[i+1]=dbPath[i];
6856 i++;
6857 }
6858
6859 /* append the "-conch" suffix to the file */
6860 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006861 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006862
6863 return SQLITE_OK;
6864}
6865
6866
6867/* Takes a fully configured proxy locking-style unix file and switches
6868** the local lock file path
6869*/
6870static int switchLockProxyPath(unixFile *pFile, const char *path) {
6871 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6872 char *oldPath = pCtx->lockProxyPath;
6873 int rc = SQLITE_OK;
6874
drh308c2a52010-05-14 11:30:18 +00006875 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006876 return SQLITE_BUSY;
6877 }
6878
6879 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6880 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6881 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6882 return SQLITE_OK;
6883 }else{
6884 unixFile *lockProxy = pCtx->lockProxy;
6885 pCtx->lockProxy=NULL;
6886 pCtx->conchHeld = 0;
6887 if( lockProxy!=NULL ){
6888 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6889 if( rc ) return rc;
6890 sqlite3_free(lockProxy);
6891 }
6892 sqlite3_free(oldPath);
6893 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6894 }
6895
6896 return rc;
6897}
6898
6899/*
6900** pFile is a file that has been opened by a prior xOpen call. dbPath
6901** is a string buffer at least MAXPATHLEN+1 characters in size.
6902**
6903** This routine find the filename associated with pFile and writes it
6904** int dbPath.
6905*/
6906static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006907#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006908 if( pFile->pMethod == &afpIoMethods ){
6909 /* afp style keeps a reference to the db path in the filePath field
6910 ** of the struct */
drhea678832008-12-10 19:26:22 +00006911 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006912 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6913 } else
drh715ff302008-12-03 22:32:44 +00006914#endif
6915 if( pFile->pMethod == &dotlockIoMethods ){
6916 /* dot lock style uses the locking context to store the dot lock
6917 ** file path */
6918 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6919 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6920 }else{
6921 /* all other styles use the locking context to store the db file path */
6922 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006923 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006924 }
6925 return SQLITE_OK;
6926}
6927
6928/*
6929** Takes an already filled in unix file and alters it so all file locking
6930** will be performed on the local proxy lock file. The following fields
6931** are preserved in the locking context so that they can be restored and
6932** the unix structure properly cleaned up at close time:
6933** ->lockingContext
6934** ->pMethod
6935*/
6936static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6937 proxyLockingContext *pCtx;
6938 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6939 char *lockPath=NULL;
6940 int rc = SQLITE_OK;
6941
drh308c2a52010-05-14 11:30:18 +00006942 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006943 return SQLITE_BUSY;
6944 }
6945 proxyGetDbPathForUnixFile(pFile, dbPath);
6946 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6947 lockPath=NULL;
6948 }else{
6949 lockPath=(char *)path;
6950 }
6951
drh308c2a52010-05-14 11:30:18 +00006952 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6953 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006954
6955 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6956 if( pCtx==0 ){
6957 return SQLITE_NOMEM;
6958 }
6959 memset(pCtx, 0, sizeof(*pCtx));
6960
6961 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6962 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006963 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6964 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6965 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6966 ** (c) the file system is read-only, then enable no-locking access.
6967 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6968 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6969 */
6970 struct statfs fsInfo;
6971 struct stat conchInfo;
6972 int goLockless = 0;
6973
drh99ab3b12011-03-02 15:09:07 +00006974 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006975 int err = errno;
6976 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6977 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6978 }
6979 }
6980 if( goLockless ){
6981 pCtx->conchHeld = -1; /* read only FS/ lockless */
6982 rc = SQLITE_OK;
6983 }
6984 }
drh715ff302008-12-03 22:32:44 +00006985 }
6986 if( rc==SQLITE_OK && lockPath ){
6987 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6988 }
6989
6990 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006991 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6992 if( pCtx->dbPath==NULL ){
6993 rc = SQLITE_NOMEM;
6994 }
6995 }
6996 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006997 /* all memory is allocated, proxys are created and assigned,
6998 ** switch the locking context and pMethod then return.
6999 */
drh715ff302008-12-03 22:32:44 +00007000 pCtx->oldLockingContext = pFile->lockingContext;
7001 pFile->lockingContext = pCtx;
7002 pCtx->pOldMethod = pFile->pMethod;
7003 pFile->pMethod = &proxyIoMethods;
7004 }else{
7005 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007006 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007007 sqlite3_free(pCtx->conchFile);
7008 }
drhd56b1212010-08-11 06:14:15 +00007009 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007010 sqlite3_free(pCtx->conchFilePath);
7011 sqlite3_free(pCtx);
7012 }
drh308c2a52010-05-14 11:30:18 +00007013 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7014 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007015 return rc;
7016}
7017
7018
7019/*
7020** This routine handles sqlite3_file_control() calls that are specific
7021** to proxy locking.
7022*/
7023static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7024 switch( op ){
7025 case SQLITE_GET_LOCKPROXYFILE: {
7026 unixFile *pFile = (unixFile*)id;
7027 if( pFile->pMethod == &proxyIoMethods ){
7028 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7029 proxyTakeConch(pFile);
7030 if( pCtx->lockProxyPath ){
7031 *(const char **)pArg = pCtx->lockProxyPath;
7032 }else{
7033 *(const char **)pArg = ":auto: (not held)";
7034 }
7035 } else {
7036 *(const char **)pArg = NULL;
7037 }
7038 return SQLITE_OK;
7039 }
7040 case SQLITE_SET_LOCKPROXYFILE: {
7041 unixFile *pFile = (unixFile*)id;
7042 int rc = SQLITE_OK;
7043 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7044 if( pArg==NULL || (const char *)pArg==0 ){
7045 if( isProxyStyle ){
7046 /* turn off proxy locking - not supported */
7047 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7048 }else{
7049 /* turn off proxy locking - already off - NOOP */
7050 rc = SQLITE_OK;
7051 }
7052 }else{
7053 const char *proxyPath = (const char *)pArg;
7054 if( isProxyStyle ){
7055 proxyLockingContext *pCtx =
7056 (proxyLockingContext*)pFile->lockingContext;
7057 if( !strcmp(pArg, ":auto:")
7058 || (pCtx->lockProxyPath &&
7059 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7060 ){
7061 rc = SQLITE_OK;
7062 }else{
7063 rc = switchLockProxyPath(pFile, proxyPath);
7064 }
7065 }else{
7066 /* turn on proxy file locking */
7067 rc = proxyTransformUnixFile(pFile, proxyPath);
7068 }
7069 }
7070 return rc;
7071 }
7072 default: {
7073 assert( 0 ); /* The call assures that only valid opcodes are sent */
7074 }
7075 }
7076 /*NOTREACHED*/
7077 return SQLITE_ERROR;
7078}
7079
7080/*
7081** Within this division (the proxying locking implementation) the procedures
7082** above this point are all utilities. The lock-related methods of the
7083** proxy-locking sqlite3_io_method object follow.
7084*/
7085
7086
7087/*
7088** This routine checks if there is a RESERVED lock held on the specified
7089** file by this or any other process. If such a lock is held, set *pResOut
7090** to a non-zero value otherwise *pResOut is set to zero. The return value
7091** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7092*/
7093static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7094 unixFile *pFile = (unixFile*)id;
7095 int rc = proxyTakeConch(pFile);
7096 if( rc==SQLITE_OK ){
7097 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007098 if( pCtx->conchHeld>0 ){
7099 unixFile *proxy = pCtx->lockProxy;
7100 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7101 }else{ /* conchHeld < 0 is lockless */
7102 pResOut=0;
7103 }
drh715ff302008-12-03 22:32:44 +00007104 }
7105 return rc;
7106}
7107
7108/*
drh308c2a52010-05-14 11:30:18 +00007109** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007110** of the following:
7111**
7112** (1) SHARED_LOCK
7113** (2) RESERVED_LOCK
7114** (3) PENDING_LOCK
7115** (4) EXCLUSIVE_LOCK
7116**
7117** Sometimes when requesting one lock state, additional lock states
7118** are inserted in between. The locking might fail on one of the later
7119** transitions leaving the lock state different from what it started but
7120** still short of its goal. The following chart shows the allowed
7121** transitions and the inserted intermediate states:
7122**
7123** UNLOCKED -> SHARED
7124** SHARED -> RESERVED
7125** SHARED -> (PENDING) -> EXCLUSIVE
7126** RESERVED -> (PENDING) -> EXCLUSIVE
7127** PENDING -> EXCLUSIVE
7128**
7129** This routine will only increase a lock. Use the sqlite3OsUnlock()
7130** routine to lower a locking level.
7131*/
drh308c2a52010-05-14 11:30:18 +00007132static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007133 unixFile *pFile = (unixFile*)id;
7134 int rc = proxyTakeConch(pFile);
7135 if( rc==SQLITE_OK ){
7136 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007137 if( pCtx->conchHeld>0 ){
7138 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007139 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7140 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007141 }else{
7142 /* conchHeld < 0 is lockless */
7143 }
drh715ff302008-12-03 22:32:44 +00007144 }
7145 return rc;
7146}
7147
7148
7149/*
drh308c2a52010-05-14 11:30:18 +00007150** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007151** must be either NO_LOCK or SHARED_LOCK.
7152**
7153** If the locking level of the file descriptor is already at or below
7154** the requested locking level, this routine is a no-op.
7155*/
drh308c2a52010-05-14 11:30:18 +00007156static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007157 unixFile *pFile = (unixFile*)id;
7158 int rc = proxyTakeConch(pFile);
7159 if( rc==SQLITE_OK ){
7160 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007161 if( pCtx->conchHeld>0 ){
7162 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007163 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7164 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007165 }else{
7166 /* conchHeld < 0 is lockless */
7167 }
drh715ff302008-12-03 22:32:44 +00007168 }
7169 return rc;
7170}
7171
7172/*
7173** Close a file that uses proxy locks.
7174*/
7175static int proxyClose(sqlite3_file *id) {
7176 if( id ){
7177 unixFile *pFile = (unixFile*)id;
7178 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7179 unixFile *lockProxy = pCtx->lockProxy;
7180 unixFile *conchFile = pCtx->conchFile;
7181 int rc = SQLITE_OK;
7182
7183 if( lockProxy ){
7184 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7185 if( rc ) return rc;
7186 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7187 if( rc ) return rc;
7188 sqlite3_free(lockProxy);
7189 pCtx->lockProxy = 0;
7190 }
7191 if( conchFile ){
7192 if( pCtx->conchHeld ){
7193 rc = proxyReleaseConch(pFile);
7194 if( rc ) return rc;
7195 }
7196 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7197 if( rc ) return rc;
7198 sqlite3_free(conchFile);
7199 }
drhd56b1212010-08-11 06:14:15 +00007200 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007201 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007202 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007203 /* restore the original locking context and pMethod then close it */
7204 pFile->lockingContext = pCtx->oldLockingContext;
7205 pFile->pMethod = pCtx->pOldMethod;
7206 sqlite3_free(pCtx);
7207 return pFile->pMethod->xClose(id);
7208 }
7209 return SQLITE_OK;
7210}
7211
7212
7213
drhd2cb50b2009-01-09 21:41:17 +00007214#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007215/*
7216** The proxy locking style is intended for use with AFP filesystems.
7217** And since AFP is only supported on MacOSX, the proxy locking is also
7218** restricted to MacOSX.
7219**
7220**
7221******************* End of the proxy lock implementation **********************
7222******************************************************************************/
7223
drh734c9862008-11-28 15:37:20 +00007224/*
danielk1977e339d652008-06-28 11:23:00 +00007225** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007226**
7227** This routine registers all VFS implementations for unix-like operating
7228** systems. This routine, and the sqlite3_os_end() routine that follows,
7229** should be the only routines in this file that are visible from other
7230** files.
drh6b9d6dd2008-12-03 19:34:47 +00007231**
7232** This routine is called once during SQLite initialization and by a
7233** single thread. The memory allocation and mutex subsystems have not
7234** necessarily been initialized when this routine is called, and so they
7235** should not be used.
drh153c62c2007-08-24 03:51:33 +00007236*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007237int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007238 /*
7239 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007240 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7241 ** to the "finder" function. (pAppData is a pointer to a pointer because
7242 ** silly C90 rules prohibit a void* from being cast to a function pointer
7243 ** and so we have to go through the intermediate pointer to avoid problems
7244 ** when compiling with -pedantic-errors on GCC.)
7245 **
7246 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007247 ** finder-function. The finder-function returns a pointer to the
7248 ** sqlite_io_methods object that implements the desired locking
7249 ** behaviors. See the division above that contains the IOMETHODS
7250 ** macro for addition information on finder-functions.
7251 **
7252 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7253 ** object. But the "autolockIoFinder" available on MacOSX does a little
7254 ** more than that; it looks at the filesystem type that hosts the
7255 ** database file and tries to choose an locking method appropriate for
7256 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007257 */
drh7708e972008-11-29 00:56:52 +00007258 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007259 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007260 sizeof(unixFile), /* szOsFile */ \
7261 MAX_PATHNAME, /* mxPathname */ \
7262 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007263 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007264 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007265 unixOpen, /* xOpen */ \
7266 unixDelete, /* xDelete */ \
7267 unixAccess, /* xAccess */ \
7268 unixFullPathname, /* xFullPathname */ \
7269 unixDlOpen, /* xDlOpen */ \
7270 unixDlError, /* xDlError */ \
7271 unixDlSym, /* xDlSym */ \
7272 unixDlClose, /* xDlClose */ \
7273 unixRandomness, /* xRandomness */ \
7274 unixSleep, /* xSleep */ \
7275 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007276 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007277 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007278 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007279 unixGetSystemCall, /* xGetSystemCall */ \
7280 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007281 }
7282
drh6b9d6dd2008-12-03 19:34:47 +00007283 /*
7284 ** All default VFSes for unix are contained in the following array.
7285 **
7286 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7287 ** by the SQLite core when the VFS is registered. So the following
7288 ** array cannot be const.
7289 */
danielk1977e339d652008-06-28 11:23:00 +00007290 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007291#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007292 UNIXVFS("unix", autolockIoFinder ),
7293#else
7294 UNIXVFS("unix", posixIoFinder ),
7295#endif
7296 UNIXVFS("unix-none", nolockIoFinder ),
7297 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007298 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007299#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007300 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007301#endif
7302#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007303 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007304#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007305 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007306#endif
chw78a13182009-04-07 05:35:03 +00007307#endif
drhd2cb50b2009-01-09 21:41:17 +00007308#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007309 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007310 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007311 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007312#endif
drh153c62c2007-08-24 03:51:33 +00007313 };
drh6b9d6dd2008-12-03 19:34:47 +00007314 unsigned int i; /* Loop counter */
7315
drh2aa5a002011-04-13 13:42:25 +00007316 /* Double-check that the aSyscall[] array has been constructed
7317 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007318 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007319
drh6b9d6dd2008-12-03 19:34:47 +00007320 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007321 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007322 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007323 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007324 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007325}
danielk1977e339d652008-06-28 11:23:00 +00007326
7327/*
drh6b9d6dd2008-12-03 19:34:47 +00007328** Shutdown the operating system interface.
7329**
7330** Some operating systems might need to do some cleanup in this routine,
7331** to release dynamically allocated objects. But not on unix.
7332** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007333*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007334int sqlite3_os_end(void){
7335 return SQLITE_OK;
7336}
drhdce8bdb2007-08-16 13:01:44 +00007337
danielk197729bafea2008-06-26 10:41:19 +00007338#endif /* SQLITE_OS_UNIX */