blob: c85e9b53af4b0024244e191ff385a59548cc451a [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000221#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000222 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000223#endif
drh7ed97b92010-01-20 13:07:21 +0000224#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000225 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000226#endif
227#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000228 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
drhf0b190d2011-07-26 16:03:07 +0000253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
255#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000256#ifndef SQLITE_DISABLE_DIRSYNC
257# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
258#else
259# define UNIXFILE_DIRSYNC 0x00
260#endif
drhcb15f352011-12-23 01:04:17 +0000261#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000262#define UNIXFILE_DELETE 0x20 /* Delete on close */
263#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
264#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drh3ee34842012-02-11 21:21:17 +0000265#define UNIXFILE_CHOWN 0x100 /* File ownership was changed */
drha7e61d82011-03-12 17:02:57 +0000266
267/*
drh198bf392006-01-06 21:52:49 +0000268** Include code that is common to all os_*.c files
269*/
270#include "os_common.h"
271
272/*
drh0ccebe72005-06-07 22:22:50 +0000273** Define various macros that are missing from some systems.
274*/
drhbbd42a62004-05-22 17:41:58 +0000275#ifndef O_LARGEFILE
276# define O_LARGEFILE 0
277#endif
278#ifdef SQLITE_DISABLE_LFS
279# undef O_LARGEFILE
280# define O_LARGEFILE 0
281#endif
282#ifndef O_NOFOLLOW
283# define O_NOFOLLOW 0
284#endif
285#ifndef O_BINARY
286# define O_BINARY 0
287#endif
288
289/*
drh2b4b5962005-06-15 17:47:55 +0000290** The threadid macro resolves to the thread-id or to 0. Used for
291** testing and debugging only.
292*/
drhd677b3d2007-08-20 22:48:41 +0000293#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000294#define threadid pthread_self()
295#else
296#define threadid 0
297#endif
298
drh99ab3b12011-03-02 15:09:07 +0000299/*
drh9a3baf12011-04-25 18:01:27 +0000300** Different Unix systems declare open() in different ways. Same use
301** open(const char*,int,mode_t). Others use open(const char*,int,...).
302** The difference is important when using a pointer to the function.
303**
304** The safest way to deal with the problem is to always use this wrapper
305** which always has the same well-defined interface.
306*/
307static int posixOpen(const char *zFile, int flags, int mode){
308 return open(zFile, flags, mode);
309}
310
drh90315a22011-08-10 01:52:12 +0000311/* Forward reference */
312static int openDirectory(const char*, int*);
313
drh9a3baf12011-04-25 18:01:27 +0000314/*
drh99ab3b12011-03-02 15:09:07 +0000315** Many system calls are accessed through pointer-to-functions so that
316** they may be overridden at runtime to facilitate fault injection during
317** testing and sandboxing. The following array holds the names and pointers
318** to all overrideable system calls.
319*/
320static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000321 const char *zName; /* Name of the sytem call */
322 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
323 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000324} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000325 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
326#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000327
drh58ad5802011-03-23 22:02:23 +0000328 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000329#define osClose ((int(*)(int))aSyscall[1].pCurrent)
330
drh58ad5802011-03-23 22:02:23 +0000331 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000332#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
333
drh58ad5802011-03-23 22:02:23 +0000334 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000335#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
336
drh58ad5802011-03-23 22:02:23 +0000337 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000338#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
339
340/*
341** The DJGPP compiler environment looks mostly like Unix, but it
342** lacks the fcntl() system call. So redefine fcntl() to be something
343** that always succeeds. This means that locking does not occur under
344** DJGPP. But it is DOS - what did you expect?
345*/
346#ifdef __DJGPP__
347 { "fstat", 0, 0 },
348#define osFstat(a,b,c) 0
349#else
drh58ad5802011-03-23 22:02:23 +0000350 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
352#endif
353
drh58ad5802011-03-23 22:02:23 +0000354 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
356
drh58ad5802011-03-23 22:02:23 +0000357 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000358#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000359
drh58ad5802011-03-23 22:02:23 +0000360 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000361#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
362
drhd4a80312011-04-15 14:33:20 +0000363#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000364 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000365#else
drh58ad5802011-03-23 22:02:23 +0000366 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000367#endif
368#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
369
370#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000371 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000372#else
drh58ad5802011-03-23 22:02:23 +0000373 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000374#endif
375#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
376
drh58ad5802011-03-23 22:02:23 +0000377 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000378#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
379
drhd4a80312011-04-15 14:33:20 +0000380#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000381 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000384#endif
385#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
386 aSyscall[12].pCurrent)
387
388#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000389 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000390#else
drh58ad5802011-03-23 22:02:23 +0000391 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000392#endif
393#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
394 aSyscall[13].pCurrent)
395
drha6c47492011-04-11 18:35:09 +0000396#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000398#else
399 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000400#endif
drh2aa5a002011-04-13 13:42:25 +0000401#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000402
403#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000404 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
dan0fd7d862011-03-29 10:04:23 +0000408#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000409
drh036ac7f2011-08-08 23:18:05 +0000410 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
411#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
412
drh90315a22011-08-10 01:52:12 +0000413 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
414#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
415
drh9ef6bc42011-11-04 02:24:02 +0000416 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
417#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
418
419 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
420#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
421
drh23c4b972012-02-11 23:55:15 +0000422 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000423#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000424
drh8c815d12012-02-13 20:16:37 +0000425 { "umask", (sqlite3_syscall_ptr)umask, 0 },
426#define osUmask ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
427
drhe562be52011-03-02 18:01:10 +0000428}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000429
430/*
431** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000432** "unix" VFSes. Return SQLITE_OK opon successfully updating the
433** system call pointer, or SQLITE_NOTFOUND if there is no configurable
434** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000435*/
436static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000437 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
438 const char *zName, /* Name of system call to override */
439 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000440){
drh58ad5802011-03-23 22:02:23 +0000441 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000442 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000443
444 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000445 if( zName==0 ){
446 /* If no zName is given, restore all system calls to their default
447 ** settings and return NULL
448 */
dan51438a72011-04-02 17:00:47 +0000449 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000450 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
451 if( aSyscall[i].pDefault ){
452 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000453 }
454 }
455 }else{
456 /* If zName is specified, operate on only the one system call
457 ** specified.
458 */
459 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
460 if( strcmp(zName, aSyscall[i].zName)==0 ){
461 if( aSyscall[i].pDefault==0 ){
462 aSyscall[i].pDefault = aSyscall[i].pCurrent;
463 }
drh1df30962011-03-02 19:06:42 +0000464 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000465 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
466 aSyscall[i].pCurrent = pNewFunc;
467 break;
468 }
469 }
470 }
471 return rc;
472}
473
drh1df30962011-03-02 19:06:42 +0000474/*
475** Return the value of a system call. Return NULL if zName is not a
476** recognized system call name. NULL is also returned if the system call
477** is currently undefined.
478*/
drh58ad5802011-03-23 22:02:23 +0000479static sqlite3_syscall_ptr unixGetSystemCall(
480 sqlite3_vfs *pNotUsed,
481 const char *zName
482){
483 unsigned int i;
484
485 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000486 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
487 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
488 }
489 return 0;
490}
491
492/*
493** Return the name of the first system call after zName. If zName==NULL
494** then return the name of the first system call. Return NULL if zName
495** is the last system call or if zName is not the name of a valid
496** system call.
497*/
498static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000499 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000500
501 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000502 if( zName ){
503 for(i=0; i<ArraySize(aSyscall)-1; i++){
504 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000505 }
506 }
dan0fd7d862011-03-29 10:04:23 +0000507 for(i++; i<ArraySize(aSyscall); i++){
508 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000509 }
510 return 0;
511}
512
drhad4f1e52011-03-04 15:43:57 +0000513/*
drh8c815d12012-02-13 20:16:37 +0000514** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000515** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000516**
517** If the file creation mode "m" is 0 then set it to the default for
518** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
519** 0644) as modified by the system umask. If m is not 0, then
520** make the file creation mode be exactly m ignoring the umask.
521**
522** The m parameter will be non-zero only when creating -wal, -journal,
523** and -shm files. We want those files to have *exactly* the same
524** permissions as their original database, unadulterated by the umask.
525** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
526** transaction crashes and leaves behind hot journals, then any
527** process that is able to write to the database will also be able to
528** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000529*/
drh8c815d12012-02-13 20:16:37 +0000530static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000531 int fd;
drh8c815d12012-02-13 20:16:37 +0000532 mode_t m2;
drhef595982012-02-13 20:28:15 +0000533 mode_t origM = 0;
drh8c815d12012-02-13 20:16:37 +0000534 if( m==0 ){
535 m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
536 }else{
537 m2 = m;
538 origM = osUmask(0);
539 }
drh5adc60b2012-04-14 13:25:11 +0000540 do{
541#if defined(O_CLOEXEC)
542 fd = osOpen(z,f|O_CLOEXEC,m2);
543#else
544 fd = osOpen(z,f,m2);
545#endif
546 }while( fd<0 && errno==EINTR );
drh8c815d12012-02-13 20:16:37 +0000547 if( m ){
548 osUmask(origM);
549 }
drh5adc60b2012-04-14 13:25:11 +0000550#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
551 if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
552#endif
553 return fd;
drhad4f1e52011-03-04 15:43:57 +0000554}
danielk197713adf8a2004-06-03 16:08:41 +0000555
drh107886a2008-11-21 22:21:50 +0000556/*
dan9359c7b2009-08-21 08:29:10 +0000557** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000558** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000559** vxworksFileId objects used by this file, all of which may be
560** shared by multiple threads.
561**
562** Function unixMutexHeld() is used to assert() that the global mutex
563** is held when required. This function is only used as part of assert()
564** statements. e.g.
565**
566** unixEnterMutex()
567** assert( unixMutexHeld() );
568** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000569*/
570static void unixEnterMutex(void){
571 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
572}
573static void unixLeaveMutex(void){
574 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
575}
dan9359c7b2009-08-21 08:29:10 +0000576#ifdef SQLITE_DEBUG
577static int unixMutexHeld(void) {
578 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
579}
580#endif
drh107886a2008-11-21 22:21:50 +0000581
drh734c9862008-11-28 15:37:20 +0000582
drh30ddce62011-10-15 00:16:30 +0000583#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000584/*
585** Helper function for printing out trace information from debugging
586** binaries. This returns the string represetation of the supplied
587** integer lock-type.
588*/
drh308c2a52010-05-14 11:30:18 +0000589static const char *azFileLock(int eFileLock){
590 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000591 case NO_LOCK: return "NONE";
592 case SHARED_LOCK: return "SHARED";
593 case RESERVED_LOCK: return "RESERVED";
594 case PENDING_LOCK: return "PENDING";
595 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000596 }
597 return "ERROR";
598}
599#endif
600
601#ifdef SQLITE_LOCK_TRACE
602/*
603** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000604**
drh734c9862008-11-28 15:37:20 +0000605** This routine is used for troubleshooting locks on multithreaded
606** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
607** command-line option on the compiler. This code is normally
608** turned off.
609*/
610static int lockTrace(int fd, int op, struct flock *p){
611 char *zOpName, *zType;
612 int s;
613 int savedErrno;
614 if( op==F_GETLK ){
615 zOpName = "GETLK";
616 }else if( op==F_SETLK ){
617 zOpName = "SETLK";
618 }else{
drh99ab3b12011-03-02 15:09:07 +0000619 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000620 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
621 return s;
622 }
623 if( p->l_type==F_RDLCK ){
624 zType = "RDLCK";
625 }else if( p->l_type==F_WRLCK ){
626 zType = "WRLCK";
627 }else if( p->l_type==F_UNLCK ){
628 zType = "UNLCK";
629 }else{
630 assert( 0 );
631 }
632 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000633 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000634 savedErrno = errno;
635 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
636 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
637 (int)p->l_pid, s);
638 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
639 struct flock l2;
640 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000641 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000642 if( l2.l_type==F_RDLCK ){
643 zType = "RDLCK";
644 }else if( l2.l_type==F_WRLCK ){
645 zType = "WRLCK";
646 }else if( l2.l_type==F_UNLCK ){
647 zType = "UNLCK";
648 }else{
649 assert( 0 );
650 }
651 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
652 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
653 }
654 errno = savedErrno;
655 return s;
656}
drh99ab3b12011-03-02 15:09:07 +0000657#undef osFcntl
658#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000659#endif /* SQLITE_LOCK_TRACE */
660
drhff812312011-02-23 13:33:46 +0000661/*
662** Retry ftruncate() calls that fail due to EINTR
663*/
drhff812312011-02-23 13:33:46 +0000664static int robust_ftruncate(int h, sqlite3_int64 sz){
665 int rc;
drh99ab3b12011-03-02 15:09:07 +0000666 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000667 return rc;
668}
drh734c9862008-11-28 15:37:20 +0000669
670/*
671** This routine translates a standard POSIX errno code into something
672** useful to the clients of the sqlite3 functions. Specifically, it is
673** intended to translate a variety of "try again" errors into SQLITE_BUSY
674** and a variety of "please close the file descriptor NOW" errors into
675** SQLITE_IOERR
676**
677** Errors during initialization of locks, or file system support for locks,
678** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
679*/
680static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
681 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000682#if 0
683 /* At one point this code was not commented out. In theory, this branch
684 ** should never be hit, as this function should only be called after
685 ** a locking-related function (i.e. fcntl()) has returned non-zero with
686 ** the value of errno as the first argument. Since a system call has failed,
687 ** errno should be non-zero.
688 **
689 ** Despite this, if errno really is zero, we still don't want to return
690 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
691 ** propagated back to the caller. Commenting this branch out means errno==0
692 ** will be handled by the "default:" case below.
693 */
drh734c9862008-11-28 15:37:20 +0000694 case 0:
695 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000696#endif
697
drh734c9862008-11-28 15:37:20 +0000698 case EAGAIN:
699 case ETIMEDOUT:
700 case EBUSY:
701 case EINTR:
702 case ENOLCK:
703 /* random NFS retry error, unless during file system support
704 * introspection, in which it actually means what it says */
705 return SQLITE_BUSY;
706
707 case EACCES:
708 /* EACCES is like EAGAIN during locking operations, but not any other time*/
709 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
710 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
711 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
712 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
713 return SQLITE_BUSY;
714 }
715 /* else fall through */
716 case EPERM:
717 return SQLITE_PERM;
718
danea83bc62011-04-01 11:56:32 +0000719 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
720 ** this module never makes such a call. And the code in SQLite itself
721 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
722 ** this case is also commented out. If the system does set errno to EDEADLK,
723 ** the default SQLITE_IOERR_XXX code will be returned. */
724#if 0
drh734c9862008-11-28 15:37:20 +0000725 case EDEADLK:
726 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000727#endif
drh734c9862008-11-28 15:37:20 +0000728
729#if EOPNOTSUPP!=ENOTSUP
730 case EOPNOTSUPP:
731 /* something went terribly awry, unless during file system support
732 * introspection, in which it actually means what it says */
733#endif
734#ifdef ENOTSUP
735 case ENOTSUP:
736 /* invalid fd, unless during file system support introspection, in which
737 * it actually means what it says */
738#endif
739 case EIO:
740 case EBADF:
741 case EINVAL:
742 case ENOTCONN:
743 case ENODEV:
744 case ENXIO:
745 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000746#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000747 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000748#endif
drh734c9862008-11-28 15:37:20 +0000749 case ENOSYS:
750 /* these should force the client to close the file and reconnect */
751
752 default:
753 return sqliteIOErr;
754 }
755}
756
757
758
759/******************************************************************************
760****************** Begin Unique File ID Utility Used By VxWorks ***************
761**
762** On most versions of unix, we can get a unique ID for a file by concatenating
763** the device number and the inode number. But this does not work on VxWorks.
764** On VxWorks, a unique file id must be based on the canonical filename.
765**
766** A pointer to an instance of the following structure can be used as a
767** unique file ID in VxWorks. Each instance of this structure contains
768** a copy of the canonical filename. There is also a reference count.
769** The structure is reclaimed when the number of pointers to it drops to
770** zero.
771**
772** There are never very many files open at one time and lookups are not
773** a performance-critical path, so it is sufficient to put these
774** structures on a linked list.
775*/
776struct vxworksFileId {
777 struct vxworksFileId *pNext; /* Next in a list of them all */
778 int nRef; /* Number of references to this one */
779 int nName; /* Length of the zCanonicalName[] string */
780 char *zCanonicalName; /* Canonical filename */
781};
782
783#if OS_VXWORKS
784/*
drh9b35ea62008-11-29 02:20:26 +0000785** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000786** variable:
787*/
788static struct vxworksFileId *vxworksFileList = 0;
789
790/*
791** Simplify a filename into its canonical form
792** by making the following changes:
793**
794** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000795** * convert /./ into just /
796** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000797**
798** Changes are made in-place. Return the new name length.
799**
800** The original filename is in z[0..n-1]. Return the number of
801** characters in the simplified name.
802*/
803static int vxworksSimplifyName(char *z, int n){
804 int i, j;
805 while( n>1 && z[n-1]=='/' ){ n--; }
806 for(i=j=0; i<n; i++){
807 if( z[i]=='/' ){
808 if( z[i+1]=='/' ) continue;
809 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
810 i += 1;
811 continue;
812 }
813 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
814 while( j>0 && z[j-1]!='/' ){ j--; }
815 if( j>0 ){ j--; }
816 i += 2;
817 continue;
818 }
819 }
820 z[j++] = z[i];
821 }
822 z[j] = 0;
823 return j;
824}
825
826/*
827** Find a unique file ID for the given absolute pathname. Return
828** a pointer to the vxworksFileId object. This pointer is the unique
829** file ID.
830**
831** The nRef field of the vxworksFileId object is incremented before
832** the object is returned. A new vxworksFileId object is created
833** and added to the global list if necessary.
834**
835** If a memory allocation error occurs, return NULL.
836*/
837static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
838 struct vxworksFileId *pNew; /* search key and new file ID */
839 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
840 int n; /* Length of zAbsoluteName string */
841
842 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000843 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000844 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
845 if( pNew==0 ) return 0;
846 pNew->zCanonicalName = (char*)&pNew[1];
847 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
848 n = vxworksSimplifyName(pNew->zCanonicalName, n);
849
850 /* Search for an existing entry that matching the canonical name.
851 ** If found, increment the reference count and return a pointer to
852 ** the existing file ID.
853 */
854 unixEnterMutex();
855 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
856 if( pCandidate->nName==n
857 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
858 ){
859 sqlite3_free(pNew);
860 pCandidate->nRef++;
861 unixLeaveMutex();
862 return pCandidate;
863 }
864 }
865
866 /* No match was found. We will make a new file ID */
867 pNew->nRef = 1;
868 pNew->nName = n;
869 pNew->pNext = vxworksFileList;
870 vxworksFileList = pNew;
871 unixLeaveMutex();
872 return pNew;
873}
874
875/*
876** Decrement the reference count on a vxworksFileId object. Free
877** the object when the reference count reaches zero.
878*/
879static void vxworksReleaseFileId(struct vxworksFileId *pId){
880 unixEnterMutex();
881 assert( pId->nRef>0 );
882 pId->nRef--;
883 if( pId->nRef==0 ){
884 struct vxworksFileId **pp;
885 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
886 assert( *pp==pId );
887 *pp = pId->pNext;
888 sqlite3_free(pId);
889 }
890 unixLeaveMutex();
891}
892#endif /* OS_VXWORKS */
893/*************** End of Unique File ID Utility Used By VxWorks ****************
894******************************************************************************/
895
896
897/******************************************************************************
898*************************** Posix Advisory Locking ****************************
899**
drh9b35ea62008-11-29 02:20:26 +0000900** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000901** section 6.5.2.2 lines 483 through 490 specify that when a process
902** sets or clears a lock, that operation overrides any prior locks set
903** by the same process. It does not explicitly say so, but this implies
904** that it overrides locks set by the same process using a different
905** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000906**
907** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000908** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
909**
910** Suppose ./file1 and ./file2 are really the same file (because
911** one is a hard or symbolic link to the other) then if you set
912** an exclusive lock on fd1, then try to get an exclusive lock
913** on fd2, it works. I would have expected the second lock to
914** fail since there was already a lock on the file due to fd1.
915** But not so. Since both locks came from the same process, the
916** second overrides the first, even though they were on different
917** file descriptors opened on different file names.
918**
drh734c9862008-11-28 15:37:20 +0000919** This means that we cannot use POSIX locks to synchronize file access
920** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000921** to synchronize access for threads in separate processes, but not
922** threads within the same process.
923**
924** To work around the problem, SQLite has to manage file locks internally
925** on its own. Whenever a new database is opened, we have to find the
926** specific inode of the database file (the inode is determined by the
927** st_dev and st_ino fields of the stat structure that fstat() fills in)
928** and check for locks already existing on that inode. When locks are
929** created or removed, we have to look at our own internal record of the
930** locks to see if another thread has previously set a lock on that same
931** inode.
932**
drh9b35ea62008-11-29 02:20:26 +0000933** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
934** For VxWorks, we have to use the alternative unique ID system based on
935** canonical filename and implemented in the previous division.)
936**
danielk1977ad94b582007-08-20 06:44:22 +0000937** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000938** descriptor. It is now a structure that holds the integer file
939** descriptor and a pointer to a structure that describes the internal
940** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000941** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000942** point to the same locking structure. The locking structure keeps
943** a reference count (so we will know when to delete it) and a "cnt"
944** field that tells us its internal lock status. cnt==0 means the
945** file is unlocked. cnt==-1 means the file has an exclusive lock.
946** cnt>0 means there are cnt shared locks on the file.
947**
948** Any attempt to lock or unlock a file first checks the locking
949** structure. The fcntl() system call is only invoked to set a
950** POSIX lock if the internal lock structure transitions between
951** a locked and an unlocked state.
952**
drh734c9862008-11-28 15:37:20 +0000953** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000954**
955** If you close a file descriptor that points to a file that has locks,
956** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000957** released. To work around this problem, each unixInodeInfo object
958** maintains a count of the number of pending locks on tha inode.
959** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000960** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000961** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000962** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000963** be closed and that list is walked (and cleared) when the last lock
964** clears.
965**
drh9b35ea62008-11-29 02:20:26 +0000966** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000967**
drh9b35ea62008-11-29 02:20:26 +0000968** Many older versions of linux use the LinuxThreads library which is
969** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000970** A cannot be modified or overridden by a different thread B.
971** Only thread A can modify the lock. Locking behavior is correct
972** if the appliation uses the newer Native Posix Thread Library (NPTL)
973** on linux - with NPTL a lock created by thread A can override locks
974** in thread B. But there is no way to know at compile-time which
975** threading library is being used. So there is no way to know at
976** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000977** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000978** current process.
drh5fdae772004-06-29 03:29:00 +0000979**
drh8af6c222010-05-14 12:43:01 +0000980** SQLite used to support LinuxThreads. But support for LinuxThreads
981** was dropped beginning with version 3.7.0. SQLite will still work with
982** LinuxThreads provided that (1) there is no more than one connection
983** per database file in the same process and (2) database connections
984** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000985*/
986
987/*
988** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000989** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000990*/
991struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000992 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000993#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000994 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000995#else
drh107886a2008-11-21 22:21:50 +0000996 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000997#endif
998};
999
1000/*
drhbbd42a62004-05-22 17:41:58 +00001001** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001002** inode. Or, on LinuxThreads, there is one of these structures for
1003** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001004**
danielk1977ad94b582007-08-20 06:44:22 +00001005** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001006** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001007** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001008*/
drh8af6c222010-05-14 12:43:01 +00001009struct unixInodeInfo {
1010 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001011 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001012 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1013 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001014 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001015 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1016 int nLock; /* Number of outstanding file locks */
1017 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1018 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1019 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001020#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001021 unsigned long long sharedByte; /* for AFP simulated shared lock */
1022#endif
drh6c7d5c52008-11-21 20:32:33 +00001023#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001024 sem_t *pSem; /* Named POSIX semaphore */
1025 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001026#endif
drhbbd42a62004-05-22 17:41:58 +00001027};
1028
drhda0e7682008-07-30 15:27:54 +00001029/*
drh8af6c222010-05-14 12:43:01 +00001030** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001031*/
drhd91c68f2010-05-14 14:52:25 +00001032static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001033
drh5fdae772004-06-29 03:29:00 +00001034/*
dane18d4952011-02-21 11:46:24 +00001035**
1036** This function - unixLogError_x(), is only ever called via the macro
1037** unixLogError().
1038**
1039** It is invoked after an error occurs in an OS function and errno has been
1040** set. It logs a message using sqlite3_log() containing the current value of
1041** errno and, if possible, the human-readable equivalent from strerror() or
1042** strerror_r().
1043**
1044** The first argument passed to the macro should be the error code that
1045** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1046** The two subsequent arguments should be the name of the OS function that
1047** failed (e.g. "unlink", "open") and the the associated file-system path,
1048** if any.
1049*/
drh0e9365c2011-03-02 02:08:13 +00001050#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1051static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001052 int errcode, /* SQLite error code */
1053 const char *zFunc, /* Name of OS function that failed */
1054 const char *zPath, /* File path associated with error */
1055 int iLine /* Source line number where error occurred */
1056){
1057 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001058 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001059
1060 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1061 ** the strerror() function to obtain the human-readable error message
1062 ** equivalent to errno. Otherwise, use strerror_r().
1063 */
1064#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1065 char aErr[80];
1066 memset(aErr, 0, sizeof(aErr));
1067 zErr = aErr;
1068
1069 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1070 ** assume that the system provides the the GNU version of strerror_r() that
1071 ** returns a pointer to a buffer containing the error message. That pointer
1072 ** may point to aErr[], or it may point to some static storage somewhere.
1073 ** Otherwise, assume that the system provides the POSIX version of
1074 ** strerror_r(), which always writes an error message into aErr[].
1075 **
1076 ** If the code incorrectly assumes that it is the POSIX version that is
1077 ** available, the error message will often be an empty string. Not a
1078 ** huge problem. Incorrectly concluding that the GNU version is available
1079 ** could lead to a segfault though.
1080 */
1081#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1082 zErr =
1083# endif
drh0e9365c2011-03-02 02:08:13 +00001084 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001085
1086#elif SQLITE_THREADSAFE
1087 /* This is a threadsafe build, but strerror_r() is not available. */
1088 zErr = "";
1089#else
1090 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001091 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001092#endif
1093
1094 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001095 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001096 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001097 "os_unix.c:%d: (%d) %s(%s) - %s",
1098 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001099 );
1100
1101 return errcode;
1102}
1103
drh0e9365c2011-03-02 02:08:13 +00001104/*
1105** Close a file descriptor.
1106**
1107** We assume that close() almost always works, since it is only in a
1108** very sick application or on a very sick platform that it might fail.
1109** If it does fail, simply leak the file descriptor, but do log the
1110** error.
1111**
1112** Note that it is not safe to retry close() after EINTR since the
1113** file descriptor might have already been reused by another thread.
1114** So we don't even try to recover from an EINTR. Just log the error
1115** and move on.
1116*/
1117static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001118 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001119 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1120 pFile ? pFile->zPath : 0, lineno);
1121 }
1122}
dane18d4952011-02-21 11:46:24 +00001123
1124/*
danb0ac3e32010-06-16 10:55:42 +00001125** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001126*/
drh0e9365c2011-03-02 02:08:13 +00001127static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001128 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001129 UnixUnusedFd *p;
1130 UnixUnusedFd *pNext;
1131 for(p=pInode->pUnused; p; p=pNext){
1132 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001133 robust_close(pFile, p->fd, __LINE__);
1134 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001135 }
drh0e9365c2011-03-02 02:08:13 +00001136 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001137}
1138
1139/*
drh8af6c222010-05-14 12:43:01 +00001140** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001141**
1142** The mutex entered using the unixEnterMutex() function must be held
1143** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001144*/
danb0ac3e32010-06-16 10:55:42 +00001145static void releaseInodeInfo(unixFile *pFile){
1146 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001147 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001148 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001149 pInode->nRef--;
1150 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001151 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001152 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001153 if( pInode->pPrev ){
1154 assert( pInode->pPrev->pNext==pInode );
1155 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001156 }else{
drh8af6c222010-05-14 12:43:01 +00001157 assert( inodeList==pInode );
1158 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001159 }
drh8af6c222010-05-14 12:43:01 +00001160 if( pInode->pNext ){
1161 assert( pInode->pNext->pPrev==pInode );
1162 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001163 }
drh8af6c222010-05-14 12:43:01 +00001164 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001165 }
drhbbd42a62004-05-22 17:41:58 +00001166 }
1167}
1168
1169/*
drh8af6c222010-05-14 12:43:01 +00001170** Given a file descriptor, locate the unixInodeInfo object that
1171** describes that file descriptor. Create a new one if necessary. The
1172** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001173**
dan9359c7b2009-08-21 08:29:10 +00001174** The mutex entered using the unixEnterMutex() function must be held
1175** when this function is called.
1176**
drh6c7d5c52008-11-21 20:32:33 +00001177** Return an appropriate error code.
1178*/
drh8af6c222010-05-14 12:43:01 +00001179static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001180 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001181 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001182){
1183 int rc; /* System call return code */
1184 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001185 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1186 struct stat statbuf; /* Low-level file information */
1187 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001188
dan9359c7b2009-08-21 08:29:10 +00001189 assert( unixMutexHeld() );
1190
drh6c7d5c52008-11-21 20:32:33 +00001191 /* Get low-level information about the file that we can used to
1192 ** create a unique name for the file.
1193 */
1194 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001195 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001196 if( rc!=0 ){
1197 pFile->lastErrno = errno;
1198#ifdef EOVERFLOW
1199 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1200#endif
1201 return SQLITE_IOERR;
1202 }
1203
drheb0d74f2009-02-03 15:27:02 +00001204#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001205 /* On OS X on an msdos filesystem, the inode number is reported
1206 ** incorrectly for zero-size files. See ticket #3260. To work
1207 ** around this problem (we consider it a bug in OS X, not SQLite)
1208 ** we always increase the file size to 1 by writing a single byte
1209 ** prior to accessing the inode number. The one byte written is
1210 ** an ASCII 'S' character which also happens to be the first byte
1211 ** in the header of every SQLite database. In this way, if there
1212 ** is a race condition such that another thread has already populated
1213 ** the first page of the database, no damage is done.
1214 */
drh7ed97b92010-01-20 13:07:21 +00001215 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001216 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001217 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001218 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001219 return SQLITE_IOERR;
1220 }
drh99ab3b12011-03-02 15:09:07 +00001221 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001222 if( rc!=0 ){
1223 pFile->lastErrno = errno;
1224 return SQLITE_IOERR;
1225 }
1226 }
drheb0d74f2009-02-03 15:27:02 +00001227#endif
drh6c7d5c52008-11-21 20:32:33 +00001228
drh8af6c222010-05-14 12:43:01 +00001229 memset(&fileId, 0, sizeof(fileId));
1230 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001231#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001232 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001233#else
drh8af6c222010-05-14 12:43:01 +00001234 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001235#endif
drh8af6c222010-05-14 12:43:01 +00001236 pInode = inodeList;
1237 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1238 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001239 }
drh8af6c222010-05-14 12:43:01 +00001240 if( pInode==0 ){
1241 pInode = sqlite3_malloc( sizeof(*pInode) );
1242 if( pInode==0 ){
1243 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001244 }
drh8af6c222010-05-14 12:43:01 +00001245 memset(pInode, 0, sizeof(*pInode));
1246 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1247 pInode->nRef = 1;
1248 pInode->pNext = inodeList;
1249 pInode->pPrev = 0;
1250 if( inodeList ) inodeList->pPrev = pInode;
1251 inodeList = pInode;
1252 }else{
1253 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001254 }
drh8af6c222010-05-14 12:43:01 +00001255 *ppInode = pInode;
1256 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001257}
drh6c7d5c52008-11-21 20:32:33 +00001258
aswift5b1a2562008-08-22 00:22:35 +00001259
1260/*
danielk197713adf8a2004-06-03 16:08:41 +00001261** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001262** file by this or any other process. If such a lock is held, set *pResOut
1263** to a non-zero value otherwise *pResOut is set to zero. The return value
1264** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001265*/
danielk1977861f7452008-06-05 11:39:11 +00001266static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001267 int rc = SQLITE_OK;
1268 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001269 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001270
danielk1977861f7452008-06-05 11:39:11 +00001271 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1272
drh054889e2005-11-30 03:20:31 +00001273 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001274 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001275
1276 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001277 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001278 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001279 }
1280
drh2ac3ee92004-06-07 16:27:46 +00001281 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001282 */
danielk197709480a92009-02-09 05:32:32 +00001283#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001284 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001285 struct flock lock;
1286 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001287 lock.l_start = RESERVED_BYTE;
1288 lock.l_len = 1;
1289 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001290 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1291 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1292 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001293 } else if( lock.l_type!=F_UNLCK ){
1294 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001295 }
1296 }
danielk197709480a92009-02-09 05:32:32 +00001297#endif
danielk197713adf8a2004-06-03 16:08:41 +00001298
drh6c7d5c52008-11-21 20:32:33 +00001299 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001300 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001301
aswift5b1a2562008-08-22 00:22:35 +00001302 *pResOut = reserved;
1303 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001304}
1305
1306/*
drha7e61d82011-03-12 17:02:57 +00001307** Attempt to set a system-lock on the file pFile. The lock is
1308** described by pLock.
1309**
drh77197112011-03-15 19:08:48 +00001310** If the pFile was opened read/write from unix-excl, then the only lock
1311** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001312** the first time any lock is attempted. All subsequent system locking
1313** operations become no-ops. Locking operations still happen internally,
1314** in order to coordinate access between separate database connections
1315** within this process, but all of that is handled in memory and the
1316** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001317**
1318** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1319** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1320** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001321**
1322** Zero is returned if the call completes successfully, or -1 if a call
1323** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001324*/
1325static int unixFileLock(unixFile *pFile, struct flock *pLock){
1326 int rc;
drh3cb93392011-03-12 18:10:44 +00001327 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001328 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001329 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001330 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1331 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1332 ){
drh3cb93392011-03-12 18:10:44 +00001333 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001334 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001335 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001336 lock.l_whence = SEEK_SET;
1337 lock.l_start = SHARED_FIRST;
1338 lock.l_len = SHARED_SIZE;
1339 lock.l_type = F_WRLCK;
1340 rc = osFcntl(pFile->h, F_SETLK, &lock);
1341 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001342 pInode->bProcessLock = 1;
1343 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001344 }else{
1345 rc = 0;
1346 }
1347 }else{
1348 rc = osFcntl(pFile->h, F_SETLK, pLock);
1349 }
1350 return rc;
1351}
1352
1353/*
drh308c2a52010-05-14 11:30:18 +00001354** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001355** of the following:
1356**
drh2ac3ee92004-06-07 16:27:46 +00001357** (1) SHARED_LOCK
1358** (2) RESERVED_LOCK
1359** (3) PENDING_LOCK
1360** (4) EXCLUSIVE_LOCK
1361**
drhb3e04342004-06-08 00:47:47 +00001362** Sometimes when requesting one lock state, additional lock states
1363** are inserted in between. The locking might fail on one of the later
1364** transitions leaving the lock state different from what it started but
1365** still short of its goal. The following chart shows the allowed
1366** transitions and the inserted intermediate states:
1367**
1368** UNLOCKED -> SHARED
1369** SHARED -> RESERVED
1370** SHARED -> (PENDING) -> EXCLUSIVE
1371** RESERVED -> (PENDING) -> EXCLUSIVE
1372** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001373**
drha6abd042004-06-09 17:37:22 +00001374** This routine will only increase a lock. Use the sqlite3OsUnlock()
1375** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001376*/
drh308c2a52010-05-14 11:30:18 +00001377static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001378 /* The following describes the implementation of the various locks and
1379 ** lock transitions in terms of the POSIX advisory shared and exclusive
1380 ** lock primitives (called read-locks and write-locks below, to avoid
1381 ** confusion with SQLite lock names). The algorithms are complicated
1382 ** slightly in order to be compatible with windows systems simultaneously
1383 ** accessing the same database file, in case that is ever required.
1384 **
1385 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1386 ** byte', each single bytes at well known offsets, and the 'shared byte
1387 ** range', a range of 510 bytes at a well known offset.
1388 **
1389 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1390 ** byte'. If this is successful, a random byte from the 'shared byte
1391 ** range' is read-locked and the lock on the 'pending byte' released.
1392 **
danielk197790ba3bd2004-06-25 08:32:25 +00001393 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1394 ** A RESERVED lock is implemented by grabbing a write-lock on the
1395 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001396 **
1397 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001398 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1399 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1400 ** obtained, but existing SHARED locks are allowed to persist. A process
1401 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1402 ** This property is used by the algorithm for rolling back a journal file
1403 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001404 **
danielk197790ba3bd2004-06-25 08:32:25 +00001405 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1406 ** implemented by obtaining a write-lock on the entire 'shared byte
1407 ** range'. Since all other locks require a read-lock on one of the bytes
1408 ** within this range, this ensures that no other locks are held on the
1409 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001410 **
1411 ** The reason a single byte cannot be used instead of the 'shared byte
1412 ** range' is that some versions of windows do not support read-locks. By
1413 ** locking a random byte from a range, concurrent SHARED locks may exist
1414 ** even if the locking primitive used is always a write-lock.
1415 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001416 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001417 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001418 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001419 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001420 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001421
drh054889e2005-11-30 03:20:31 +00001422 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001423 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1424 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001425 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001426
1427 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001428 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001429 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001430 */
drh308c2a52010-05-14 11:30:18 +00001431 if( pFile->eFileLock>=eFileLock ){
1432 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1433 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001434 return SQLITE_OK;
1435 }
1436
drh0c2694b2009-09-03 16:23:44 +00001437 /* Make sure the locking sequence is correct.
1438 ** (1) We never move from unlocked to anything higher than shared lock.
1439 ** (2) SQLite never explicitly requests a pendig lock.
1440 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001441 */
drh308c2a52010-05-14 11:30:18 +00001442 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1443 assert( eFileLock!=PENDING_LOCK );
1444 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001445
drh8af6c222010-05-14 12:43:01 +00001446 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001447 */
drh6c7d5c52008-11-21 20:32:33 +00001448 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001449 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001450
danielk1977ad94b582007-08-20 06:44:22 +00001451 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001452 ** handle that precludes the requested lock, return BUSY.
1453 */
drh8af6c222010-05-14 12:43:01 +00001454 if( (pFile->eFileLock!=pInode->eFileLock &&
1455 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001456 ){
1457 rc = SQLITE_BUSY;
1458 goto end_lock;
1459 }
1460
1461 /* If a SHARED lock is requested, and some thread using this PID already
1462 ** has a SHARED or RESERVED lock, then increment reference counts and
1463 ** return SQLITE_OK.
1464 */
drh308c2a52010-05-14 11:30:18 +00001465 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001466 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001467 assert( eFileLock==SHARED_LOCK );
1468 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001469 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001470 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001471 pInode->nShared++;
1472 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001473 goto end_lock;
1474 }
1475
danielk19779a1d0ab2004-06-01 14:09:28 +00001476
drh3cde3bb2004-06-12 02:17:14 +00001477 /* A PENDING lock is needed before acquiring a SHARED lock and before
1478 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1479 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001480 */
drh0c2694b2009-09-03 16:23:44 +00001481 lock.l_len = 1L;
1482 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001483 if( eFileLock==SHARED_LOCK
1484 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001485 ){
drh308c2a52010-05-14 11:30:18 +00001486 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001487 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001488 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001489 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001490 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001491 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001492 pFile->lastErrno = tErrno;
1493 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001494 goto end_lock;
1495 }
drh3cde3bb2004-06-12 02:17:14 +00001496 }
1497
1498
1499 /* If control gets to this point, then actually go ahead and make
1500 ** operating system calls for the specified lock.
1501 */
drh308c2a52010-05-14 11:30:18 +00001502 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001503 assert( pInode->nShared==0 );
1504 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001505 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001506
drh2ac3ee92004-06-07 16:27:46 +00001507 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001508 lock.l_start = SHARED_FIRST;
1509 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001510 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001511 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001512 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001513 }
dan661d71a2011-03-30 19:08:03 +00001514
drh2ac3ee92004-06-07 16:27:46 +00001515 /* Drop the temporary PENDING lock */
1516 lock.l_start = PENDING_BYTE;
1517 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001518 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001519 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1520 /* This could happen with a network mount */
1521 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001522 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001523 }
dan661d71a2011-03-30 19:08:03 +00001524
1525 if( rc ){
1526 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001527 pFile->lastErrno = tErrno;
1528 }
dan661d71a2011-03-30 19:08:03 +00001529 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001530 }else{
drh308c2a52010-05-14 11:30:18 +00001531 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001532 pInode->nLock++;
1533 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001534 }
drh8af6c222010-05-14 12:43:01 +00001535 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001536 /* We are trying for an exclusive lock but another thread in this
1537 ** same process is still holding a shared lock. */
1538 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001539 }else{
drh3cde3bb2004-06-12 02:17:14 +00001540 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 ** assumed that there is a SHARED or greater lock on the file
1542 ** already.
1543 */
drh308c2a52010-05-14 11:30:18 +00001544 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001546
1547 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1548 if( eFileLock==RESERVED_LOCK ){
1549 lock.l_start = RESERVED_BYTE;
1550 lock.l_len = 1L;
1551 }else{
1552 lock.l_start = SHARED_FIRST;
1553 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001554 }
dan661d71a2011-03-30 19:08:03 +00001555
1556 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001557 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001558 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001559 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001560 pFile->lastErrno = tErrno;
1561 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001562 }
drhbbd42a62004-05-22 17:41:58 +00001563 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001564
drh8f941bc2009-01-14 23:03:40 +00001565
1566#ifndef NDEBUG
1567 /* Set up the transaction-counter change checking flags when
1568 ** transitioning from a SHARED to a RESERVED lock. The change
1569 ** from SHARED to RESERVED marks the beginning of a normal
1570 ** write operation (not a hot journal rollback).
1571 */
1572 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001573 && pFile->eFileLock<=SHARED_LOCK
1574 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001575 ){
1576 pFile->transCntrChng = 0;
1577 pFile->dbUpdate = 0;
1578 pFile->inNormalWrite = 1;
1579 }
1580#endif
1581
1582
danielk1977ecb2a962004-06-02 06:30:16 +00001583 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001584 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001585 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001586 }else if( eFileLock==EXCLUSIVE_LOCK ){
1587 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001588 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001589 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001590
1591end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001592 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001593 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1594 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001595 return rc;
1596}
1597
1598/*
dan08da86a2009-08-21 17:18:03 +00001599** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001600** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001601*/
1602static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001603 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001604 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001605 p->pNext = pInode->pUnused;
1606 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001607 pFile->h = -1;
1608 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001609}
1610
1611/*
drh308c2a52010-05-14 11:30:18 +00001612** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001613** must be either NO_LOCK or SHARED_LOCK.
1614**
1615** If the locking level of the file descriptor is already at or below
1616** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001617**
1618** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1619** the byte range is divided into 2 parts and the first part is unlocked then
1620** set to a read lock, then the other part is simply unlocked. This works
1621** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1622** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001623*/
drha7e61d82011-03-12 17:02:57 +00001624static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001625 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001626 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001627 struct flock lock;
1628 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001629
drh054889e2005-11-30 03:20:31 +00001630 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001631 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001632 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001633 getpid()));
drha6abd042004-06-09 17:37:22 +00001634
drh308c2a52010-05-14 11:30:18 +00001635 assert( eFileLock<=SHARED_LOCK );
1636 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001637 return SQLITE_OK;
1638 }
drh6c7d5c52008-11-21 20:32:33 +00001639 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001640 pInode = pFile->pInode;
1641 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001642 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001643 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001644
1645#ifndef NDEBUG
1646 /* When reducing a lock such that other processes can start
1647 ** reading the database file again, make sure that the
1648 ** transaction counter was updated if any part of the database
1649 ** file changed. If the transaction counter is not updated,
1650 ** other connections to the same file might not realize that
1651 ** the file has changed and hence might not know to flush their
1652 ** cache. The use of a stale cache can lead to database corruption.
1653 */
drh8f941bc2009-01-14 23:03:40 +00001654 pFile->inNormalWrite = 0;
1655#endif
1656
drh7ed97b92010-01-20 13:07:21 +00001657 /* downgrading to a shared lock on NFS involves clearing the write lock
1658 ** before establishing the readlock - to avoid a race condition we downgrade
1659 ** the lock in 2 blocks, so that part of the range will be covered by a
1660 ** write lock until the rest is covered by a read lock:
1661 ** 1: [WWWWW]
1662 ** 2: [....W]
1663 ** 3: [RRRRW]
1664 ** 4: [RRRR.]
1665 */
drh308c2a52010-05-14 11:30:18 +00001666 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001667
1668#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001669 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001670 assert( handleNFSUnlock==0 );
1671#endif
1672#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001673 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001674 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001675 off_t divSize = SHARED_SIZE - 1;
1676
1677 lock.l_type = F_UNLCK;
1678 lock.l_whence = SEEK_SET;
1679 lock.l_start = SHARED_FIRST;
1680 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001681 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001682 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001683 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001684 if( IS_LOCK_ERROR(rc) ){
1685 pFile->lastErrno = tErrno;
1686 }
1687 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001688 }
drh7ed97b92010-01-20 13:07:21 +00001689 lock.l_type = F_RDLCK;
1690 lock.l_whence = SEEK_SET;
1691 lock.l_start = SHARED_FIRST;
1692 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001693 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001694 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001695 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1696 if( IS_LOCK_ERROR(rc) ){
1697 pFile->lastErrno = tErrno;
1698 }
1699 goto end_unlock;
1700 }
1701 lock.l_type = F_UNLCK;
1702 lock.l_whence = SEEK_SET;
1703 lock.l_start = SHARED_FIRST+divSize;
1704 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001705 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001706 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001707 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001708 if( IS_LOCK_ERROR(rc) ){
1709 pFile->lastErrno = tErrno;
1710 }
1711 goto end_unlock;
1712 }
drh30f776f2011-02-25 03:25:07 +00001713 }else
1714#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1715 {
drh7ed97b92010-01-20 13:07:21 +00001716 lock.l_type = F_RDLCK;
1717 lock.l_whence = SEEK_SET;
1718 lock.l_start = SHARED_FIRST;
1719 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001720 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001721 /* In theory, the call to unixFileLock() cannot fail because another
1722 ** process is holding an incompatible lock. If it does, this
1723 ** indicates that the other process is not following the locking
1724 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1725 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1726 ** an assert to fail). */
1727 rc = SQLITE_IOERR_RDLOCK;
1728 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001729 goto end_unlock;
1730 }
drh9c105bb2004-10-02 20:38:28 +00001731 }
1732 }
drhbbd42a62004-05-22 17:41:58 +00001733 lock.l_type = F_UNLCK;
1734 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001735 lock.l_start = PENDING_BYTE;
1736 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001737 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001738 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001739 }else{
danea83bc62011-04-01 11:56:32 +00001740 rc = SQLITE_IOERR_UNLOCK;
1741 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001742 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001743 }
drhbbd42a62004-05-22 17:41:58 +00001744 }
drh308c2a52010-05-14 11:30:18 +00001745 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001746 /* Decrement the shared lock counter. Release the lock using an
1747 ** OS call only when all threads in this same process have released
1748 ** the lock.
1749 */
drh8af6c222010-05-14 12:43:01 +00001750 pInode->nShared--;
1751 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001752 lock.l_type = F_UNLCK;
1753 lock.l_whence = SEEK_SET;
1754 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001755 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001756 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001757 }else{
danea83bc62011-04-01 11:56:32 +00001758 rc = SQLITE_IOERR_UNLOCK;
1759 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001760 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001761 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001762 }
drha6abd042004-06-09 17:37:22 +00001763 }
1764
drhbbd42a62004-05-22 17:41:58 +00001765 /* Decrement the count of locks against this same file. When the
1766 ** count reaches zero, close any other file descriptors whose close
1767 ** was deferred because of outstanding locks.
1768 */
drh8af6c222010-05-14 12:43:01 +00001769 pInode->nLock--;
1770 assert( pInode->nLock>=0 );
1771 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001772 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001773 }
1774 }
aswift5b1a2562008-08-22 00:22:35 +00001775
1776end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001777 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001778 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001779 return rc;
drhbbd42a62004-05-22 17:41:58 +00001780}
1781
1782/*
drh308c2a52010-05-14 11:30:18 +00001783** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001784** must be either NO_LOCK or SHARED_LOCK.
1785**
1786** If the locking level of the file descriptor is already at or below
1787** the requested locking level, this routine is a no-op.
1788*/
drh308c2a52010-05-14 11:30:18 +00001789static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001790 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001791}
1792
1793/*
danielk1977e339d652008-06-28 11:23:00 +00001794** This function performs the parts of the "close file" operation
1795** common to all locking schemes. It closes the directory and file
1796** handles, if they are valid, and sets all fields of the unixFile
1797** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001798**
1799** It is *not* necessary to hold the mutex when this routine is called,
1800** even on VxWorks. A mutex will be acquired on VxWorks by the
1801** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001802*/
1803static int closeUnixFile(sqlite3_file *id){
1804 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001805 if( pFile->h>=0 ){
1806 robust_close(pFile, pFile->h, __LINE__);
1807 pFile->h = -1;
1808 }
1809#if OS_VXWORKS
1810 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001811 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001812 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001813 }
1814 vxworksReleaseFileId(pFile->pId);
1815 pFile->pId = 0;
1816 }
1817#endif
1818 OSTRACE(("CLOSE %-3d\n", pFile->h));
1819 OpenCounter(-1);
1820 sqlite3_free(pFile->pUnused);
1821 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001822 return SQLITE_OK;
1823}
1824
1825/*
danielk1977e3026632004-06-22 11:29:02 +00001826** Close a file.
1827*/
danielk197762079062007-08-15 17:08:46 +00001828static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001829 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001830 unixFile *pFile = (unixFile *)id;
1831 unixUnlock(id, NO_LOCK);
1832 unixEnterMutex();
1833
1834 /* unixFile.pInode is always valid here. Otherwise, a different close
1835 ** routine (e.g. nolockClose()) would be called instead.
1836 */
1837 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1838 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1839 /* If there are outstanding locks, do not actually close the file just
1840 ** yet because that would clear those locks. Instead, add the file
1841 ** descriptor to pInode->pUnused list. It will be automatically closed
1842 ** when the last lock is cleared.
1843 */
1844 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001845 }
dan661d71a2011-03-30 19:08:03 +00001846 releaseInodeInfo(pFile);
1847 rc = closeUnixFile(id);
1848 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001849 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001850}
1851
drh734c9862008-11-28 15:37:20 +00001852/************** End of the posix advisory lock implementation *****************
1853******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001854
drh734c9862008-11-28 15:37:20 +00001855/******************************************************************************
1856****************************** No-op Locking **********************************
1857**
1858** Of the various locking implementations available, this is by far the
1859** simplest: locking is ignored. No attempt is made to lock the database
1860** file for reading or writing.
1861**
1862** This locking mode is appropriate for use on read-only databases
1863** (ex: databases that are burned into CD-ROM, for example.) It can
1864** also be used if the application employs some external mechanism to
1865** prevent simultaneous access of the same database by two or more
1866** database connections. But there is a serious risk of database
1867** corruption if this locking mode is used in situations where multiple
1868** database connections are accessing the same database file at the same
1869** time and one or more of those connections are writing.
1870*/
drhbfe66312006-10-03 17:40:40 +00001871
drh734c9862008-11-28 15:37:20 +00001872static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1873 UNUSED_PARAMETER(NotUsed);
1874 *pResOut = 0;
1875 return SQLITE_OK;
1876}
drh734c9862008-11-28 15:37:20 +00001877static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1878 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1879 return SQLITE_OK;
1880}
drh734c9862008-11-28 15:37:20 +00001881static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1882 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1883 return SQLITE_OK;
1884}
1885
1886/*
drh9b35ea62008-11-29 02:20:26 +00001887** Close the file.
drh734c9862008-11-28 15:37:20 +00001888*/
1889static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001890 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001891}
1892
1893/******************* End of the no-op lock implementation *********************
1894******************************************************************************/
1895
1896/******************************************************************************
1897************************* Begin dot-file Locking ******************************
1898**
drh0c2694b2009-09-03 16:23:44 +00001899** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001900** files (really a directory) to control access to the database. This works
1901** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001902**
1903** (1) There is zero concurrency. A single reader blocks all other
1904** connections from reading or writing the database.
1905**
1906** (2) An application crash or power loss can leave stale lock files
1907** sitting around that need to be cleared manually.
1908**
1909** Nevertheless, a dotlock is an appropriate locking mode for use if no
1910** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001911**
drh9ef6bc42011-11-04 02:24:02 +00001912** Dotfile locking works by creating a subdirectory in the same directory as
1913** the database and with the same name but with a ".lock" extension added.
1914** The existance of a lock directory implies an EXCLUSIVE lock. All other
1915** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001916*/
1917
1918/*
1919** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001920** lock directory.
drh734c9862008-11-28 15:37:20 +00001921*/
1922#define DOTLOCK_SUFFIX ".lock"
1923
drh7708e972008-11-29 00:56:52 +00001924/*
1925** This routine checks if there is a RESERVED lock held on the specified
1926** file by this or any other process. If such a lock is held, set *pResOut
1927** to a non-zero value otherwise *pResOut is set to zero. The return value
1928** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1929**
1930** In dotfile locking, either a lock exists or it does not. So in this
1931** variation of CheckReservedLock(), *pResOut is set to true if any lock
1932** is held on the file and false if the file is unlocked.
1933*/
drh734c9862008-11-28 15:37:20 +00001934static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1935 int rc = SQLITE_OK;
1936 int reserved = 0;
1937 unixFile *pFile = (unixFile*)id;
1938
1939 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1940
1941 assert( pFile );
1942
1943 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001944 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001945 /* Either this connection or some other connection in the same process
1946 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001947 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001948 }else{
1949 /* The lock is held if and only if the lockfile exists */
1950 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001951 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001952 }
drh308c2a52010-05-14 11:30:18 +00001953 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001954 *pResOut = reserved;
1955 return rc;
1956}
1957
drh7708e972008-11-29 00:56:52 +00001958/*
drh308c2a52010-05-14 11:30:18 +00001959** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001960** of the following:
1961**
1962** (1) SHARED_LOCK
1963** (2) RESERVED_LOCK
1964** (3) PENDING_LOCK
1965** (4) EXCLUSIVE_LOCK
1966**
1967** Sometimes when requesting one lock state, additional lock states
1968** are inserted in between. The locking might fail on one of the later
1969** transitions leaving the lock state different from what it started but
1970** still short of its goal. The following chart shows the allowed
1971** transitions and the inserted intermediate states:
1972**
1973** UNLOCKED -> SHARED
1974** SHARED -> RESERVED
1975** SHARED -> (PENDING) -> EXCLUSIVE
1976** RESERVED -> (PENDING) -> EXCLUSIVE
1977** PENDING -> EXCLUSIVE
1978**
1979** This routine will only increase a lock. Use the sqlite3OsUnlock()
1980** routine to lower a locking level.
1981**
1982** With dotfile locking, we really only support state (4): EXCLUSIVE.
1983** But we track the other locking levels internally.
1984*/
drh308c2a52010-05-14 11:30:18 +00001985static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001986 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001987 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001988 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001989
drh7708e972008-11-29 00:56:52 +00001990
1991 /* If we have any lock, then the lock file already exists. All we have
1992 ** to do is adjust our internal record of the lock level.
1993 */
drh308c2a52010-05-14 11:30:18 +00001994 if( pFile->eFileLock > NO_LOCK ){
1995 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001996 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001997#ifdef HAVE_UTIME
1998 utime(zLockFile, NULL);
1999#else
drh734c9862008-11-28 15:37:20 +00002000 utimes(zLockFile, NULL);
2001#endif
drh7708e972008-11-29 00:56:52 +00002002 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002003 }
2004
2005 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002006 rc = osMkdir(zLockFile, 0777);
2007 if( rc<0 ){
2008 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002009 int tErrno = errno;
2010 if( EEXIST == tErrno ){
2011 rc = SQLITE_BUSY;
2012 } else {
2013 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2014 if( IS_LOCK_ERROR(rc) ){
2015 pFile->lastErrno = tErrno;
2016 }
2017 }
drh7708e972008-11-29 00:56:52 +00002018 return rc;
drh734c9862008-11-28 15:37:20 +00002019 }
drh734c9862008-11-28 15:37:20 +00002020
2021 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002022 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002023 return rc;
2024}
2025
drh7708e972008-11-29 00:56:52 +00002026/*
drh308c2a52010-05-14 11:30:18 +00002027** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002028** must be either NO_LOCK or SHARED_LOCK.
2029**
2030** If the locking level of the file descriptor is already at or below
2031** the requested locking level, this routine is a no-op.
2032**
2033** When the locking level reaches NO_LOCK, delete the lock file.
2034*/
drh308c2a52010-05-14 11:30:18 +00002035static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002036 unixFile *pFile = (unixFile*)id;
2037 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002038 int rc;
drh734c9862008-11-28 15:37:20 +00002039
2040 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002041 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2042 pFile->eFileLock, getpid()));
2043 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002044
2045 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002046 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002047 return SQLITE_OK;
2048 }
drh7708e972008-11-29 00:56:52 +00002049
2050 /* To downgrade to shared, simply update our internal notion of the
2051 ** lock state. No need to mess with the file on disk.
2052 */
drh308c2a52010-05-14 11:30:18 +00002053 if( eFileLock==SHARED_LOCK ){
2054 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002055 return SQLITE_OK;
2056 }
2057
drh7708e972008-11-29 00:56:52 +00002058 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002059 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002060 rc = osRmdir(zLockFile);
2061 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2062 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002063 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002064 rc = 0;
drh734c9862008-11-28 15:37:20 +00002065 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002066 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002067 }
2068 if( IS_LOCK_ERROR(rc) ){
2069 pFile->lastErrno = tErrno;
2070 }
2071 return rc;
2072 }
drh308c2a52010-05-14 11:30:18 +00002073 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002074 return SQLITE_OK;
2075}
2076
2077/*
drh9b35ea62008-11-29 02:20:26 +00002078** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002079*/
2080static int dotlockClose(sqlite3_file *id) {
2081 int rc;
2082 if( id ){
2083 unixFile *pFile = (unixFile*)id;
2084 dotlockUnlock(id, NO_LOCK);
2085 sqlite3_free(pFile->lockingContext);
2086 }
drh734c9862008-11-28 15:37:20 +00002087 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002088 return rc;
2089}
2090/****************** End of the dot-file lock implementation *******************
2091******************************************************************************/
2092
2093/******************************************************************************
2094************************** Begin flock Locking ********************************
2095**
2096** Use the flock() system call to do file locking.
2097**
drh6b9d6dd2008-12-03 19:34:47 +00002098** flock() locking is like dot-file locking in that the various
2099** fine-grain locking levels supported by SQLite are collapsed into
2100** a single exclusive lock. In other words, SHARED, RESERVED, and
2101** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2102** still works when you do this, but concurrency is reduced since
2103** only a single process can be reading the database at a time.
2104**
drh734c9862008-11-28 15:37:20 +00002105** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2106** compiling for VXWORKS.
2107*/
2108#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002109
drh6b9d6dd2008-12-03 19:34:47 +00002110/*
drhff812312011-02-23 13:33:46 +00002111** Retry flock() calls that fail with EINTR
2112*/
2113#ifdef EINTR
2114static int robust_flock(int fd, int op){
2115 int rc;
2116 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2117 return rc;
2118}
2119#else
drh5c819272011-02-23 14:00:12 +00002120# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002121#endif
2122
2123
2124/*
drh6b9d6dd2008-12-03 19:34:47 +00002125** This routine checks if there is a RESERVED lock held on the specified
2126** file by this or any other process. If such a lock is held, set *pResOut
2127** to a non-zero value otherwise *pResOut is set to zero. The return value
2128** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2129*/
drh734c9862008-11-28 15:37:20 +00002130static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2131 int rc = SQLITE_OK;
2132 int reserved = 0;
2133 unixFile *pFile = (unixFile*)id;
2134
2135 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2136
2137 assert( pFile );
2138
2139 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002140 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002141 reserved = 1;
2142 }
2143
2144 /* Otherwise see if some other process holds it. */
2145 if( !reserved ){
2146 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002147 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002148 if( !lrc ){
2149 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002150 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002151 if ( lrc ) {
2152 int tErrno = errno;
2153 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002154 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002155 if( IS_LOCK_ERROR(lrc) ){
2156 pFile->lastErrno = tErrno;
2157 rc = lrc;
2158 }
2159 }
2160 } else {
2161 int tErrno = errno;
2162 reserved = 1;
2163 /* someone else might have it reserved */
2164 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2165 if( IS_LOCK_ERROR(lrc) ){
2166 pFile->lastErrno = tErrno;
2167 rc = lrc;
2168 }
2169 }
2170 }
drh308c2a52010-05-14 11:30:18 +00002171 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002172
2173#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2174 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2175 rc = SQLITE_OK;
2176 reserved=1;
2177 }
2178#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2179 *pResOut = reserved;
2180 return rc;
2181}
2182
drh6b9d6dd2008-12-03 19:34:47 +00002183/*
drh308c2a52010-05-14 11:30:18 +00002184** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002185** of the following:
2186**
2187** (1) SHARED_LOCK
2188** (2) RESERVED_LOCK
2189** (3) PENDING_LOCK
2190** (4) EXCLUSIVE_LOCK
2191**
2192** Sometimes when requesting one lock state, additional lock states
2193** are inserted in between. The locking might fail on one of the later
2194** transitions leaving the lock state different from what it started but
2195** still short of its goal. The following chart shows the allowed
2196** transitions and the inserted intermediate states:
2197**
2198** UNLOCKED -> SHARED
2199** SHARED -> RESERVED
2200** SHARED -> (PENDING) -> EXCLUSIVE
2201** RESERVED -> (PENDING) -> EXCLUSIVE
2202** PENDING -> EXCLUSIVE
2203**
2204** flock() only really support EXCLUSIVE locks. We track intermediate
2205** lock states in the sqlite3_file structure, but all locks SHARED or
2206** above are really EXCLUSIVE locks and exclude all other processes from
2207** access the file.
2208**
2209** This routine will only increase a lock. Use the sqlite3OsUnlock()
2210** routine to lower a locking level.
2211*/
drh308c2a52010-05-14 11:30:18 +00002212static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002213 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002214 unixFile *pFile = (unixFile*)id;
2215
2216 assert( pFile );
2217
2218 /* if we already have a lock, it is exclusive.
2219 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002220 if (pFile->eFileLock > NO_LOCK) {
2221 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
2225 /* grab an exclusive lock */
2226
drhff812312011-02-23 13:33:46 +00002227 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002228 int tErrno = errno;
2229 /* didn't get, must be busy */
2230 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2231 if( IS_LOCK_ERROR(rc) ){
2232 pFile->lastErrno = tErrno;
2233 }
2234 } else {
2235 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002236 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002237 }
drh308c2a52010-05-14 11:30:18 +00002238 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2239 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002240#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2241 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2242 rc = SQLITE_BUSY;
2243 }
2244#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2245 return rc;
2246}
2247
drh6b9d6dd2008-12-03 19:34:47 +00002248
2249/*
drh308c2a52010-05-14 11:30:18 +00002250** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002251** must be either NO_LOCK or SHARED_LOCK.
2252**
2253** If the locking level of the file descriptor is already at or below
2254** the requested locking level, this routine is a no-op.
2255*/
drh308c2a52010-05-14 11:30:18 +00002256static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002257 unixFile *pFile = (unixFile*)id;
2258
2259 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002260 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2261 pFile->eFileLock, getpid()));
2262 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002263
2264 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002265 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002266 return SQLITE_OK;
2267 }
2268
2269 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002270 if (eFileLock==SHARED_LOCK) {
2271 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002272 return SQLITE_OK;
2273 }
2274
2275 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002276 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002277#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002278 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002279#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002280 return SQLITE_IOERR_UNLOCK;
2281 }else{
drh308c2a52010-05-14 11:30:18 +00002282 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002283 return SQLITE_OK;
2284 }
2285}
2286
2287/*
2288** Close a file.
2289*/
2290static int flockClose(sqlite3_file *id) {
2291 if( id ){
2292 flockUnlock(id, NO_LOCK);
2293 }
2294 return closeUnixFile(id);
2295}
2296
2297#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2298
2299/******************* End of the flock lock implementation *********************
2300******************************************************************************/
2301
2302/******************************************************************************
2303************************ Begin Named Semaphore Locking ************************
2304**
2305** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002306**
2307** Semaphore locking is like dot-lock and flock in that it really only
2308** supports EXCLUSIVE locking. Only a single process can read or write
2309** the database file at a time. This reduces potential concurrency, but
2310** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002311*/
2312#if OS_VXWORKS
2313
drh6b9d6dd2008-12-03 19:34:47 +00002314/*
2315** This routine checks if there is a RESERVED lock held on the specified
2316** file by this or any other process. If such a lock is held, set *pResOut
2317** to a non-zero value otherwise *pResOut is set to zero. The return value
2318** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2319*/
drh734c9862008-11-28 15:37:20 +00002320static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2321 int rc = SQLITE_OK;
2322 int reserved = 0;
2323 unixFile *pFile = (unixFile*)id;
2324
2325 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2326
2327 assert( pFile );
2328
2329 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002330 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002331 reserved = 1;
2332 }
2333
2334 /* Otherwise see if some other process holds it. */
2335 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002336 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002337 struct stat statBuf;
2338
2339 if( sem_trywait(pSem)==-1 ){
2340 int tErrno = errno;
2341 if( EAGAIN != tErrno ){
2342 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2343 pFile->lastErrno = tErrno;
2344 } else {
2345 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002346 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002347 }
2348 }else{
2349 /* we could have it if we want it */
2350 sem_post(pSem);
2351 }
2352 }
drh308c2a52010-05-14 11:30:18 +00002353 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002354
2355 *pResOut = reserved;
2356 return rc;
2357}
2358
drh6b9d6dd2008-12-03 19:34:47 +00002359/*
drh308c2a52010-05-14 11:30:18 +00002360** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002361** of the following:
2362**
2363** (1) SHARED_LOCK
2364** (2) RESERVED_LOCK
2365** (3) PENDING_LOCK
2366** (4) EXCLUSIVE_LOCK
2367**
2368** Sometimes when requesting one lock state, additional lock states
2369** are inserted in between. The locking might fail on one of the later
2370** transitions leaving the lock state different from what it started but
2371** still short of its goal. The following chart shows the allowed
2372** transitions and the inserted intermediate states:
2373**
2374** UNLOCKED -> SHARED
2375** SHARED -> RESERVED
2376** SHARED -> (PENDING) -> EXCLUSIVE
2377** RESERVED -> (PENDING) -> EXCLUSIVE
2378** PENDING -> EXCLUSIVE
2379**
2380** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2381** lock states in the sqlite3_file structure, but all locks SHARED or
2382** above are really EXCLUSIVE locks and exclude all other processes from
2383** access the file.
2384**
2385** This routine will only increase a lock. Use the sqlite3OsUnlock()
2386** routine to lower a locking level.
2387*/
drh308c2a52010-05-14 11:30:18 +00002388static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002389 unixFile *pFile = (unixFile*)id;
2390 int fd;
drh8af6c222010-05-14 12:43:01 +00002391 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002392 int rc = SQLITE_OK;
2393
2394 /* if we already have a lock, it is exclusive.
2395 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002396 if (pFile->eFileLock > NO_LOCK) {
2397 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002398 rc = SQLITE_OK;
2399 goto sem_end_lock;
2400 }
2401
2402 /* lock semaphore now but bail out when already locked. */
2403 if( sem_trywait(pSem)==-1 ){
2404 rc = SQLITE_BUSY;
2405 goto sem_end_lock;
2406 }
2407
2408 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002409 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002410
2411 sem_end_lock:
2412 return rc;
2413}
2414
drh6b9d6dd2008-12-03 19:34:47 +00002415/*
drh308c2a52010-05-14 11:30:18 +00002416** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002417** must be either NO_LOCK or SHARED_LOCK.
2418**
2419** If the locking level of the file descriptor is already at or below
2420** the requested locking level, this routine is a no-op.
2421*/
drh308c2a52010-05-14 11:30:18 +00002422static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002423 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002424 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002425
2426 assert( pFile );
2427 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002428 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2429 pFile->eFileLock, getpid()));
2430 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002431
2432 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002433 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002434 return SQLITE_OK;
2435 }
2436
2437 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002438 if (eFileLock==SHARED_LOCK) {
2439 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002440 return SQLITE_OK;
2441 }
2442
2443 /* no, really unlock. */
2444 if ( sem_post(pSem)==-1 ) {
2445 int rc, tErrno = errno;
2446 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2447 if( IS_LOCK_ERROR(rc) ){
2448 pFile->lastErrno = tErrno;
2449 }
2450 return rc;
2451 }
drh308c2a52010-05-14 11:30:18 +00002452 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002453 return SQLITE_OK;
2454}
2455
2456/*
2457 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002458 */
drh734c9862008-11-28 15:37:20 +00002459static int semClose(sqlite3_file *id) {
2460 if( id ){
2461 unixFile *pFile = (unixFile*)id;
2462 semUnlock(id, NO_LOCK);
2463 assert( pFile );
2464 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002465 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002466 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002467 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002468 }
2469 return SQLITE_OK;
2470}
2471
2472#endif /* OS_VXWORKS */
2473/*
2474** Named semaphore locking is only available on VxWorks.
2475**
2476*************** End of the named semaphore lock implementation ****************
2477******************************************************************************/
2478
2479
2480/******************************************************************************
2481*************************** Begin AFP Locking *********************************
2482**
2483** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2484** on Apple Macintosh computers - both OS9 and OSX.
2485**
2486** Third-party implementations of AFP are available. But this code here
2487** only works on OSX.
2488*/
2489
drhd2cb50b2009-01-09 21:41:17 +00002490#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002491/*
2492** The afpLockingContext structure contains all afp lock specific state
2493*/
drhbfe66312006-10-03 17:40:40 +00002494typedef struct afpLockingContext afpLockingContext;
2495struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002496 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002497 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002498};
2499
2500struct ByteRangeLockPB2
2501{
2502 unsigned long long offset; /* offset to first byte to lock */
2503 unsigned long long length; /* nbr of bytes to lock */
2504 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2505 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2506 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2507 int fd; /* file desc to assoc this lock with */
2508};
2509
drhfd131da2007-08-07 17:13:03 +00002510#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002511
drh6b9d6dd2008-12-03 19:34:47 +00002512/*
2513** This is a utility for setting or clearing a bit-range lock on an
2514** AFP filesystem.
2515**
2516** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2517*/
2518static int afpSetLock(
2519 const char *path, /* Name of the file to be locked or unlocked */
2520 unixFile *pFile, /* Open file descriptor on path */
2521 unsigned long long offset, /* First byte to be locked */
2522 unsigned long long length, /* Number of bytes to lock */
2523 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002524){
drh6b9d6dd2008-12-03 19:34:47 +00002525 struct ByteRangeLockPB2 pb;
2526 int err;
drhbfe66312006-10-03 17:40:40 +00002527
2528 pb.unLockFlag = setLockFlag ? 0 : 1;
2529 pb.startEndFlag = 0;
2530 pb.offset = offset;
2531 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002532 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002533
drh308c2a52010-05-14 11:30:18 +00002534 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002535 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002536 offset, length));
drhbfe66312006-10-03 17:40:40 +00002537 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2538 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002539 int rc;
2540 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002541 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2542 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002543#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2544 rc = SQLITE_BUSY;
2545#else
drh734c9862008-11-28 15:37:20 +00002546 rc = sqliteErrorFromPosixError(tErrno,
2547 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002548#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002549 if( IS_LOCK_ERROR(rc) ){
2550 pFile->lastErrno = tErrno;
2551 }
2552 return rc;
drhbfe66312006-10-03 17:40:40 +00002553 } else {
aswift5b1a2562008-08-22 00:22:35 +00002554 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002555 }
2556}
2557
drh6b9d6dd2008-12-03 19:34:47 +00002558/*
2559** This routine checks if there is a RESERVED lock held on the specified
2560** file by this or any other process. If such a lock is held, set *pResOut
2561** to a non-zero value otherwise *pResOut is set to zero. The return value
2562** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2563*/
danielk1977e339d652008-06-28 11:23:00 +00002564static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002565 int rc = SQLITE_OK;
2566 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002567 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002568 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002569
aswift5b1a2562008-08-22 00:22:35 +00002570 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2571
2572 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002573 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002574 if( context->reserved ){
2575 *pResOut = 1;
2576 return SQLITE_OK;
2577 }
drh8af6c222010-05-14 12:43:01 +00002578 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002579
2580 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002581 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002582 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002583 }
2584
2585 /* Otherwise see if some other process holds it.
2586 */
aswift5b1a2562008-08-22 00:22:35 +00002587 if( !reserved ){
2588 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002589 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002590 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002591 /* if we succeeded in taking the reserved lock, unlock it to restore
2592 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002593 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002594 } else {
2595 /* if we failed to get the lock then someone else must have it */
2596 reserved = 1;
2597 }
2598 if( IS_LOCK_ERROR(lrc) ){
2599 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002600 }
2601 }
drhbfe66312006-10-03 17:40:40 +00002602
drh7ed97b92010-01-20 13:07:21 +00002603 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002604 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002605
2606 *pResOut = reserved;
2607 return rc;
drhbfe66312006-10-03 17:40:40 +00002608}
2609
drh6b9d6dd2008-12-03 19:34:47 +00002610/*
drh308c2a52010-05-14 11:30:18 +00002611** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002612** of the following:
2613**
2614** (1) SHARED_LOCK
2615** (2) RESERVED_LOCK
2616** (3) PENDING_LOCK
2617** (4) EXCLUSIVE_LOCK
2618**
2619** Sometimes when requesting one lock state, additional lock states
2620** are inserted in between. The locking might fail on one of the later
2621** transitions leaving the lock state different from what it started but
2622** still short of its goal. The following chart shows the allowed
2623** transitions and the inserted intermediate states:
2624**
2625** UNLOCKED -> SHARED
2626** SHARED -> RESERVED
2627** SHARED -> (PENDING) -> EXCLUSIVE
2628** RESERVED -> (PENDING) -> EXCLUSIVE
2629** PENDING -> EXCLUSIVE
2630**
2631** This routine will only increase a lock. Use the sqlite3OsUnlock()
2632** routine to lower a locking level.
2633*/
drh308c2a52010-05-14 11:30:18 +00002634static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002635 int rc = SQLITE_OK;
2636 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002637 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002638 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002639
2640 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002641 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2642 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002643 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002644
drhbfe66312006-10-03 17:40:40 +00002645 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002646 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002647 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002648 */
drh308c2a52010-05-14 11:30:18 +00002649 if( pFile->eFileLock>=eFileLock ){
2650 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2651 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002652 return SQLITE_OK;
2653 }
2654
2655 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002656 ** (1) We never move from unlocked to anything higher than shared lock.
2657 ** (2) SQLite never explicitly requests a pendig lock.
2658 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002659 */
drh308c2a52010-05-14 11:30:18 +00002660 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2661 assert( eFileLock!=PENDING_LOCK );
2662 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002663
drh8af6c222010-05-14 12:43:01 +00002664 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002665 */
drh6c7d5c52008-11-21 20:32:33 +00002666 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002667 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002668
2669 /* If some thread using this PID has a lock via a different unixFile*
2670 ** handle that precludes the requested lock, return BUSY.
2671 */
drh8af6c222010-05-14 12:43:01 +00002672 if( (pFile->eFileLock!=pInode->eFileLock &&
2673 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002674 ){
2675 rc = SQLITE_BUSY;
2676 goto afp_end_lock;
2677 }
2678
2679 /* If a SHARED lock is requested, and some thread using this PID already
2680 ** has a SHARED or RESERVED lock, then increment reference counts and
2681 ** return SQLITE_OK.
2682 */
drh308c2a52010-05-14 11:30:18 +00002683 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002684 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002685 assert( eFileLock==SHARED_LOCK );
2686 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002687 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002688 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002689 pInode->nShared++;
2690 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002691 goto afp_end_lock;
2692 }
drhbfe66312006-10-03 17:40:40 +00002693
2694 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002695 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2696 ** be released.
2697 */
drh308c2a52010-05-14 11:30:18 +00002698 if( eFileLock==SHARED_LOCK
2699 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002700 ){
2701 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002702 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002703 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002704 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002705 goto afp_end_lock;
2706 }
2707 }
2708
2709 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002710 ** operating system calls for the specified lock.
2711 */
drh308c2a52010-05-14 11:30:18 +00002712 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002713 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002714 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002715
drh8af6c222010-05-14 12:43:01 +00002716 assert( pInode->nShared==0 );
2717 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002718
2719 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002720 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002721 /* note that the quality of the randomness doesn't matter that much */
2722 lk = random();
drh8af6c222010-05-14 12:43:01 +00002723 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002724 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002725 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002726 if( IS_LOCK_ERROR(lrc1) ){
2727 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002728 }
aswift5b1a2562008-08-22 00:22:35 +00002729 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002730 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002731
aswift5b1a2562008-08-22 00:22:35 +00002732 if( IS_LOCK_ERROR(lrc1) ) {
2733 pFile->lastErrno = lrc1Errno;
2734 rc = lrc1;
2735 goto afp_end_lock;
2736 } else if( IS_LOCK_ERROR(lrc2) ){
2737 rc = lrc2;
2738 goto afp_end_lock;
2739 } else if( lrc1 != SQLITE_OK ) {
2740 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002741 } else {
drh308c2a52010-05-14 11:30:18 +00002742 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002743 pInode->nLock++;
2744 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002745 }
drh8af6c222010-05-14 12:43:01 +00002746 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002747 /* We are trying for an exclusive lock but another thread in this
2748 ** same process is still holding a shared lock. */
2749 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002750 }else{
2751 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2752 ** assumed that there is a SHARED or greater lock on the file
2753 ** already.
2754 */
2755 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002756 assert( 0!=pFile->eFileLock );
2757 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002758 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002759 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002760 if( !failed ){
2761 context->reserved = 1;
2762 }
drhbfe66312006-10-03 17:40:40 +00002763 }
drh308c2a52010-05-14 11:30:18 +00002764 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002765 /* Acquire an EXCLUSIVE lock */
2766
2767 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002768 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002769 */
drh6b9d6dd2008-12-03 19:34:47 +00002770 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002771 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002772 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002773 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002774 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002775 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002776 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002777 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002778 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2779 ** a critical I/O error
2780 */
2781 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2782 SQLITE_IOERR_LOCK;
2783 goto afp_end_lock;
2784 }
2785 }else{
aswift5b1a2562008-08-22 00:22:35 +00002786 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002787 }
2788 }
aswift5b1a2562008-08-22 00:22:35 +00002789 if( failed ){
2790 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002791 }
2792 }
2793
2794 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002795 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002796 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002797 }else if( eFileLock==EXCLUSIVE_LOCK ){
2798 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002799 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002800 }
2801
2802afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002803 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002804 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2805 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002806 return rc;
2807}
2808
2809/*
drh308c2a52010-05-14 11:30:18 +00002810** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002811** must be either NO_LOCK or SHARED_LOCK.
2812**
2813** If the locking level of the file descriptor is already at or below
2814** the requested locking level, this routine is a no-op.
2815*/
drh308c2a52010-05-14 11:30:18 +00002816static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002817 int rc = SQLITE_OK;
2818 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002819 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002820 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2821 int skipShared = 0;
2822#ifdef SQLITE_TEST
2823 int h = pFile->h;
2824#endif
drhbfe66312006-10-03 17:40:40 +00002825
2826 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002827 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002828 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002829 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002830
drh308c2a52010-05-14 11:30:18 +00002831 assert( eFileLock<=SHARED_LOCK );
2832 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002833 return SQLITE_OK;
2834 }
drh6c7d5c52008-11-21 20:32:33 +00002835 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002836 pInode = pFile->pInode;
2837 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002838 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002839 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002840 SimulateIOErrorBenign(1);
2841 SimulateIOError( h=(-1) )
2842 SimulateIOErrorBenign(0);
2843
2844#ifndef NDEBUG
2845 /* When reducing a lock such that other processes can start
2846 ** reading the database file again, make sure that the
2847 ** transaction counter was updated if any part of the database
2848 ** file changed. If the transaction counter is not updated,
2849 ** other connections to the same file might not realize that
2850 ** the file has changed and hence might not know to flush their
2851 ** cache. The use of a stale cache can lead to database corruption.
2852 */
2853 assert( pFile->inNormalWrite==0
2854 || pFile->dbUpdate==0
2855 || pFile->transCntrChng==1 );
2856 pFile->inNormalWrite = 0;
2857#endif
aswiftaebf4132008-11-21 00:10:35 +00002858
drh308c2a52010-05-14 11:30:18 +00002859 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002860 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002861 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002862 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002863 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002864 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2865 } else {
2866 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002867 }
2868 }
drh308c2a52010-05-14 11:30:18 +00002869 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002870 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002871 }
drh308c2a52010-05-14 11:30:18 +00002872 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002873 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2874 if( !rc ){
2875 context->reserved = 0;
2876 }
aswiftaebf4132008-11-21 00:10:35 +00002877 }
drh8af6c222010-05-14 12:43:01 +00002878 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2879 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002880 }
aswiftaebf4132008-11-21 00:10:35 +00002881 }
drh308c2a52010-05-14 11:30:18 +00002882 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002883
drh7ed97b92010-01-20 13:07:21 +00002884 /* Decrement the shared lock counter. Release the lock using an
2885 ** OS call only when all threads in this same process have released
2886 ** the lock.
2887 */
drh8af6c222010-05-14 12:43:01 +00002888 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2889 pInode->nShared--;
2890 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002891 SimulateIOErrorBenign(1);
2892 SimulateIOError( h=(-1) )
2893 SimulateIOErrorBenign(0);
2894 if( !skipShared ){
2895 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2896 }
2897 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002898 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002899 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002900 }
2901 }
2902 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002903 pInode->nLock--;
2904 assert( pInode->nLock>=0 );
2905 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002906 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002907 }
2908 }
drhbfe66312006-10-03 17:40:40 +00002909 }
drh7ed97b92010-01-20 13:07:21 +00002910
drh6c7d5c52008-11-21 20:32:33 +00002911 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002912 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002913 return rc;
2914}
2915
2916/*
drh339eb0b2008-03-07 15:34:11 +00002917** Close a file & cleanup AFP specific locking context
2918*/
danielk1977e339d652008-06-28 11:23:00 +00002919static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002920 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002921 if( id ){
2922 unixFile *pFile = (unixFile*)id;
2923 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002924 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002925 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002926 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002927 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002928 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002929 ** the last lock is cleared.
2930 */
dan08da86a2009-08-21 17:18:03 +00002931 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002932 }
danb0ac3e32010-06-16 10:55:42 +00002933 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002934 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002935 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002936 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002937 }
drh7ed97b92010-01-20 13:07:21 +00002938 return rc;
drhbfe66312006-10-03 17:40:40 +00002939}
2940
drhd2cb50b2009-01-09 21:41:17 +00002941#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002942/*
2943** The code above is the AFP lock implementation. The code is specific
2944** to MacOSX and does not work on other unix platforms. No alternative
2945** is available. If you don't compile for a mac, then the "unix-afp"
2946** VFS is not available.
2947**
2948********************* End of the AFP lock implementation **********************
2949******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002950
drh7ed97b92010-01-20 13:07:21 +00002951/******************************************************************************
2952*************************** Begin NFS Locking ********************************/
2953
2954#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2955/*
drh308c2a52010-05-14 11:30:18 +00002956 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002957 ** must be either NO_LOCK or SHARED_LOCK.
2958 **
2959 ** If the locking level of the file descriptor is already at or below
2960 ** the requested locking level, this routine is a no-op.
2961 */
drh308c2a52010-05-14 11:30:18 +00002962static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002963 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002964}
2965
2966#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2967/*
2968** The code above is the NFS lock implementation. The code is specific
2969** to MacOSX and does not work on other unix platforms. No alternative
2970** is available.
2971**
2972********************* End of the NFS lock implementation **********************
2973******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002974
2975/******************************************************************************
2976**************** Non-locking sqlite3_file methods *****************************
2977**
2978** The next division contains implementations for all methods of the
2979** sqlite3_file object other than the locking methods. The locking
2980** methods were defined in divisions above (one locking method per
2981** division). Those methods that are common to all locking modes
2982** are gather together into this division.
2983*/
drhbfe66312006-10-03 17:40:40 +00002984
2985/*
drh734c9862008-11-28 15:37:20 +00002986** Seek to the offset passed as the second argument, then read cnt
2987** bytes into pBuf. Return the number of bytes actually read.
2988**
2989** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2990** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2991** one system to another. Since SQLite does not define USE_PREAD
2992** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2993** See tickets #2741 and #2681.
2994**
2995** To avoid stomping the errno value on a failed read the lastErrno value
2996** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002997*/
drh734c9862008-11-28 15:37:20 +00002998static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2999 int got;
drh58024642011-11-07 18:16:00 +00003000 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003001#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003002 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003003#endif
drh734c9862008-11-28 15:37:20 +00003004 TIMER_START;
drh58024642011-11-07 18:16:00 +00003005 do{
drh734c9862008-11-28 15:37:20 +00003006#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003007 got = osPread(id->h, pBuf, cnt, offset);
3008 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003009#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003010 got = osPread64(id->h, pBuf, cnt, offset);
3011 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003012#else
drh58024642011-11-07 18:16:00 +00003013 newOffset = lseek(id->h, offset, SEEK_SET);
3014 SimulateIOError( newOffset-- );
3015 if( newOffset!=offset ){
3016 if( newOffset == -1 ){
3017 ((unixFile*)id)->lastErrno = errno;
3018 }else{
3019 ((unixFile*)id)->lastErrno = 0;
3020 }
3021 return -1;
drh734c9862008-11-28 15:37:20 +00003022 }
drh58024642011-11-07 18:16:00 +00003023 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003024#endif
drh58024642011-11-07 18:16:00 +00003025 if( got==cnt ) break;
3026 if( got<0 ){
3027 if( errno==EINTR ){ got = 1; continue; }
3028 prior = 0;
3029 ((unixFile*)id)->lastErrno = errno;
3030 break;
3031 }else if( got>0 ){
3032 cnt -= got;
3033 offset += got;
3034 prior += got;
3035 pBuf = (void*)(got + (char*)pBuf);
3036 }
3037 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003038 TIMER_END;
drh58024642011-11-07 18:16:00 +00003039 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3040 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3041 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003042}
3043
3044/*
drh734c9862008-11-28 15:37:20 +00003045** Read data from a file into a buffer. Return SQLITE_OK if all
3046** bytes were read successfully and SQLITE_IOERR if anything goes
3047** wrong.
drh339eb0b2008-03-07 15:34:11 +00003048*/
drh734c9862008-11-28 15:37:20 +00003049static int unixRead(
3050 sqlite3_file *id,
3051 void *pBuf,
3052 int amt,
3053 sqlite3_int64 offset
3054){
dan08da86a2009-08-21 17:18:03 +00003055 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003056 int got;
3057 assert( id );
drh08c6d442009-02-09 17:34:07 +00003058
dan08da86a2009-08-21 17:18:03 +00003059 /* If this is a database file (not a journal, master-journal or temp
3060 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003061#if 0
dane946c392009-08-22 11:39:46 +00003062 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003063 || offset>=PENDING_BYTE+512
3064 || offset+amt<=PENDING_BYTE
3065 );
dan7c246102010-04-12 19:00:29 +00003066#endif
drh08c6d442009-02-09 17:34:07 +00003067
dan08da86a2009-08-21 17:18:03 +00003068 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003069 if( got==amt ){
3070 return SQLITE_OK;
3071 }else if( got<0 ){
3072 /* lastErrno set by seekAndRead */
3073 return SQLITE_IOERR_READ;
3074 }else{
dan08da86a2009-08-21 17:18:03 +00003075 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003076 /* Unread parts of the buffer must be zero-filled */
3077 memset(&((char*)pBuf)[got], 0, amt-got);
3078 return SQLITE_IOERR_SHORT_READ;
3079 }
3080}
3081
3082/*
3083** Seek to the offset in id->offset then read cnt bytes into pBuf.
3084** Return the number of bytes actually read. Update the offset.
3085**
3086** To avoid stomping the errno value on a failed write the lastErrno value
3087** is set before returning.
3088*/
3089static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3090 int got;
drh7ed97b92010-01-20 13:07:21 +00003091#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003092 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003093#endif
drh734c9862008-11-28 15:37:20 +00003094 TIMER_START;
3095#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003096 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003097#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003098 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003099#else
drhbd1e50c2011-08-19 14:54:12 +00003100 do{
3101 newOffset = lseek(id->h, offset, SEEK_SET);
3102 SimulateIOError( newOffset-- );
3103 if( newOffset!=offset ){
3104 if( newOffset == -1 ){
3105 ((unixFile*)id)->lastErrno = errno;
3106 }else{
3107 ((unixFile*)id)->lastErrno = 0;
3108 }
3109 return -1;
drh734c9862008-11-28 15:37:20 +00003110 }
drhbd1e50c2011-08-19 14:54:12 +00003111 got = osWrite(id->h, pBuf, cnt);
3112 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003113#endif
3114 TIMER_END;
3115 if( got<0 ){
3116 ((unixFile*)id)->lastErrno = errno;
3117 }
3118
drh308c2a52010-05-14 11:30:18 +00003119 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003120 return got;
3121}
3122
3123
3124/*
3125** Write data from a buffer into a file. Return SQLITE_OK on success
3126** or some other error code on failure.
3127*/
3128static int unixWrite(
3129 sqlite3_file *id,
3130 const void *pBuf,
3131 int amt,
3132 sqlite3_int64 offset
3133){
dan08da86a2009-08-21 17:18:03 +00003134 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003135 int wrote = 0;
3136 assert( id );
3137 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003138
dan08da86a2009-08-21 17:18:03 +00003139 /* If this is a database file (not a journal, master-journal or temp
3140 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003141#if 0
dane946c392009-08-22 11:39:46 +00003142 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003143 || offset>=PENDING_BYTE+512
3144 || offset+amt<=PENDING_BYTE
3145 );
dan7c246102010-04-12 19:00:29 +00003146#endif
drh08c6d442009-02-09 17:34:07 +00003147
drh8f941bc2009-01-14 23:03:40 +00003148#ifndef NDEBUG
3149 /* If we are doing a normal write to a database file (as opposed to
3150 ** doing a hot-journal rollback or a write to some file other than a
3151 ** normal database file) then record the fact that the database
3152 ** has changed. If the transaction counter is modified, record that
3153 ** fact too.
3154 */
dan08da86a2009-08-21 17:18:03 +00003155 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003156 pFile->dbUpdate = 1; /* The database has been modified */
3157 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003158 int rc;
drh8f941bc2009-01-14 23:03:40 +00003159 char oldCntr[4];
3160 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003161 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003162 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003163 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003164 pFile->transCntrChng = 1; /* The transaction counter has changed */
3165 }
3166 }
3167 }
3168#endif
3169
dan08da86a2009-08-21 17:18:03 +00003170 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003171 amt -= wrote;
3172 offset += wrote;
3173 pBuf = &((char*)pBuf)[wrote];
3174 }
3175 SimulateIOError(( wrote=(-1), amt=1 ));
3176 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003177
drh734c9862008-11-28 15:37:20 +00003178 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003179 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003180 /* lastErrno set by seekAndWrite */
3181 return SQLITE_IOERR_WRITE;
3182 }else{
dan08da86a2009-08-21 17:18:03 +00003183 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003184 return SQLITE_FULL;
3185 }
3186 }
dan6e09d692010-07-27 18:34:15 +00003187
drh734c9862008-11-28 15:37:20 +00003188 return SQLITE_OK;
3189}
3190
3191#ifdef SQLITE_TEST
3192/*
3193** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003194** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003195*/
3196int sqlite3_sync_count = 0;
3197int sqlite3_fullsync_count = 0;
3198#endif
3199
3200/*
drh89240432009-03-25 01:06:01 +00003201** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003202** Others do no. To be safe, we will stick with the (slightly slower)
3203** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003204** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003205*/
drh20f8e132011-08-31 21:01:55 +00003206#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003207# define fdatasync fsync
3208#endif
3209
3210/*
3211** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3212** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3213** only available on Mac OS X. But that could change.
3214*/
3215#ifdef F_FULLFSYNC
3216# define HAVE_FULLFSYNC 1
3217#else
3218# define HAVE_FULLFSYNC 0
3219#endif
3220
3221
3222/*
3223** The fsync() system call does not work as advertised on many
3224** unix systems. The following procedure is an attempt to make
3225** it work better.
3226**
3227** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3228** for testing when we want to run through the test suite quickly.
3229** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3230** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3231** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003232**
3233** SQLite sets the dataOnly flag if the size of the file is unchanged.
3234** The idea behind dataOnly is that it should only write the file content
3235** to disk, not the inode. We only set dataOnly if the file size is
3236** unchanged since the file size is part of the inode. However,
3237** Ted Ts'o tells us that fdatasync() will also write the inode if the
3238** file size has changed. The only real difference between fdatasync()
3239** and fsync(), Ted tells us, is that fdatasync() will not flush the
3240** inode if the mtime or owner or other inode attributes have changed.
3241** We only care about the file size, not the other file attributes, so
3242** as far as SQLite is concerned, an fdatasync() is always adequate.
3243** So, we always use fdatasync() if it is available, regardless of
3244** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003245*/
3246static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003247 int rc;
drh734c9862008-11-28 15:37:20 +00003248
3249 /* The following "ifdef/elif/else/" block has the same structure as
3250 ** the one below. It is replicated here solely to avoid cluttering
3251 ** up the real code with the UNUSED_PARAMETER() macros.
3252 */
3253#ifdef SQLITE_NO_SYNC
3254 UNUSED_PARAMETER(fd);
3255 UNUSED_PARAMETER(fullSync);
3256 UNUSED_PARAMETER(dataOnly);
3257#elif HAVE_FULLFSYNC
3258 UNUSED_PARAMETER(dataOnly);
3259#else
3260 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003261 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003262#endif
3263
3264 /* Record the number of times that we do a normal fsync() and
3265 ** FULLSYNC. This is used during testing to verify that this procedure
3266 ** gets called with the correct arguments.
3267 */
3268#ifdef SQLITE_TEST
3269 if( fullSync ) sqlite3_fullsync_count++;
3270 sqlite3_sync_count++;
3271#endif
3272
3273 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3274 ** no-op
3275 */
3276#ifdef SQLITE_NO_SYNC
3277 rc = SQLITE_OK;
3278#elif HAVE_FULLFSYNC
3279 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003280 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003281 }else{
3282 rc = 1;
3283 }
3284 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003285 ** It shouldn't be possible for fullfsync to fail on the local
3286 ** file system (on OSX), so failure indicates that FULLFSYNC
3287 ** isn't supported for this file system. So, attempt an fsync
3288 ** and (for now) ignore the overhead of a superfluous fcntl call.
3289 ** It'd be better to detect fullfsync support once and avoid
3290 ** the fcntl call every time sync is called.
3291 */
drh734c9862008-11-28 15:37:20 +00003292 if( rc ) rc = fsync(fd);
3293
drh7ed97b92010-01-20 13:07:21 +00003294#elif defined(__APPLE__)
3295 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3296 ** so currently we default to the macro that redefines fdatasync to fsync
3297 */
3298 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003299#else
drh0b647ff2009-03-21 14:41:04 +00003300 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003301#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003302 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003303 rc = fsync(fd);
3304 }
drh0b647ff2009-03-21 14:41:04 +00003305#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003306#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3307
3308 if( OS_VXWORKS && rc!= -1 ){
3309 rc = 0;
3310 }
chw97185482008-11-17 08:05:31 +00003311 return rc;
drhbfe66312006-10-03 17:40:40 +00003312}
3313
drh734c9862008-11-28 15:37:20 +00003314/*
drh0059eae2011-08-08 23:48:40 +00003315** Open a file descriptor to the directory containing file zFilename.
3316** If successful, *pFd is set to the opened file descriptor and
3317** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3318** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3319** value.
3320**
drh90315a22011-08-10 01:52:12 +00003321** The directory file descriptor is used for only one thing - to
3322** fsync() a directory to make sure file creation and deletion events
3323** are flushed to disk. Such fsyncs are not needed on newer
3324** journaling filesystems, but are required on older filesystems.
3325**
3326** This routine can be overridden using the xSetSysCall interface.
3327** The ability to override this routine was added in support of the
3328** chromium sandbox. Opening a directory is a security risk (we are
3329** told) so making it overrideable allows the chromium sandbox to
3330** replace this routine with a harmless no-op. To make this routine
3331** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3332** *pFd set to a negative number.
3333**
drh0059eae2011-08-08 23:48:40 +00003334** If SQLITE_OK is returned, the caller is responsible for closing
3335** the file descriptor *pFd using close().
3336*/
3337static int openDirectory(const char *zFilename, int *pFd){
3338 int ii;
3339 int fd = -1;
3340 char zDirname[MAX_PATHNAME+1];
3341
3342 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3343 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3344 if( ii>0 ){
3345 zDirname[ii] = '\0';
3346 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3347 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003348 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3349 }
3350 }
3351 *pFd = fd;
3352 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3353}
3354
3355/*
drh734c9862008-11-28 15:37:20 +00003356** Make sure all writes to a particular file are committed to disk.
3357**
3358** If dataOnly==0 then both the file itself and its metadata (file
3359** size, access time, etc) are synced. If dataOnly!=0 then only the
3360** file data is synced.
3361**
3362** Under Unix, also make sure that the directory entry for the file
3363** has been created by fsync-ing the directory that contains the file.
3364** If we do not do this and we encounter a power failure, the directory
3365** entry for the journal might not exist after we reboot. The next
3366** SQLite to access the file will not know that the journal exists (because
3367** the directory entry for the journal was never created) and the transaction
3368** will not roll back - possibly leading to database corruption.
3369*/
3370static int unixSync(sqlite3_file *id, int flags){
3371 int rc;
3372 unixFile *pFile = (unixFile*)id;
3373
3374 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3375 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3376
3377 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3378 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3379 || (flags&0x0F)==SQLITE_SYNC_FULL
3380 );
3381
3382 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3383 ** line is to test that doing so does not cause any problems.
3384 */
3385 SimulateDiskfullError( return SQLITE_FULL );
3386
3387 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003388 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003389 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3390 SimulateIOError( rc=1 );
3391 if( rc ){
3392 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003393 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003394 }
drh0059eae2011-08-08 23:48:40 +00003395
3396 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003397 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3398 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003399 */
3400 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3401 int dirfd;
3402 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003403 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003404 rc = osOpenDirectory(pFile->zPath, &dirfd);
3405 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003406 full_fsync(dirfd, 0, 0);
3407 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003408 }else if( rc==SQLITE_CANTOPEN ){
3409 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003410 }
drh0059eae2011-08-08 23:48:40 +00003411 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003412 }
3413 return rc;
3414}
3415
3416/*
3417** Truncate an open file to a specified size
3418*/
3419static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003420 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003421 int rc;
dan6e09d692010-07-27 18:34:15 +00003422 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003423 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003424
3425 /* If the user has configured a chunk-size for this file, truncate the
3426 ** file so that it consists of an integer number of chunks (i.e. the
3427 ** actual file size after the operation may be larger than the requested
3428 ** size).
3429 */
drhb8af4b72012-04-05 20:04:39 +00003430 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003431 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3432 }
3433
drhff812312011-02-23 13:33:46 +00003434 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003435 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003436 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003437 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003438 }else{
drh3313b142009-11-06 04:13:18 +00003439#ifndef NDEBUG
3440 /* If we are doing a normal write to a database file (as opposed to
3441 ** doing a hot-journal rollback or a write to some file other than a
3442 ** normal database file) and we truncate the file to zero length,
3443 ** that effectively updates the change counter. This might happen
3444 ** when restoring a database using the backup API from a zero-length
3445 ** source.
3446 */
dan6e09d692010-07-27 18:34:15 +00003447 if( pFile->inNormalWrite && nByte==0 ){
3448 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003449 }
3450#endif
3451
drh734c9862008-11-28 15:37:20 +00003452 return SQLITE_OK;
3453 }
3454}
3455
3456/*
3457** Determine the current size of a file in bytes
3458*/
3459static int unixFileSize(sqlite3_file *id, i64 *pSize){
3460 int rc;
3461 struct stat buf;
3462 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003463 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003464 SimulateIOError( rc=1 );
3465 if( rc!=0 ){
3466 ((unixFile*)id)->lastErrno = errno;
3467 return SQLITE_IOERR_FSTAT;
3468 }
3469 *pSize = buf.st_size;
3470
drh8af6c222010-05-14 12:43:01 +00003471 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003472 ** writes a single byte into that file in order to work around a bug
3473 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3474 ** layers, we need to report this file size as zero even though it is
3475 ** really 1. Ticket #3260.
3476 */
3477 if( *pSize==1 ) *pSize = 0;
3478
3479
3480 return SQLITE_OK;
3481}
3482
drhd2cb50b2009-01-09 21:41:17 +00003483#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003484/*
3485** Handler for proxy-locking file-control verbs. Defined below in the
3486** proxying locking division.
3487*/
3488static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003489#endif
drh715ff302008-12-03 22:32:44 +00003490
dan502019c2010-07-28 14:26:17 +00003491/*
3492** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003493** file-control operation. Enlarge the database to nBytes in size
3494** (rounded up to the next chunk-size). If the database is already
3495** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003496*/
3497static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003498 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003499 i64 nSize; /* Required file size */
3500 struct stat buf; /* Used to hold return values of fstat() */
3501
drh99ab3b12011-03-02 15:09:07 +00003502 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003503
3504 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3505 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003506
dan502019c2010-07-28 14:26:17 +00003507#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003508 /* The code below is handling the return value of osFallocate()
3509 ** correctly. posix_fallocate() is defined to "returns zero on success,
3510 ** or an error number on failure". See the manpage for details. */
3511 int err;
drhff812312011-02-23 13:33:46 +00003512 do{
dan661d71a2011-03-30 19:08:03 +00003513 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3514 }while( err==EINTR );
3515 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003516#else
3517 /* If the OS does not have posix_fallocate(), fake it. First use
3518 ** ftruncate() to set the file size, then write a single byte to
3519 ** the last byte in each block within the extended region. This
3520 ** is the same technique used by glibc to implement posix_fallocate()
3521 ** on systems that do not have a real fallocate() system call.
3522 */
3523 int nBlk = buf.st_blksize; /* File-system block size */
3524 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003525
drhff812312011-02-23 13:33:46 +00003526 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003527 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003528 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003529 }
3530 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003531 while( iWrite<nSize ){
3532 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3533 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003534 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003535 }
dan502019c2010-07-28 14:26:17 +00003536#endif
3537 }
3538 }
3539
3540 return SQLITE_OK;
3541}
danielk1977ad94b582007-08-20 06:44:22 +00003542
danielk1977e3026632004-06-22 11:29:02 +00003543/*
drhf12b3f62011-12-21 14:42:29 +00003544** If *pArg is inititially negative then this is a query. Set *pArg to
3545** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3546**
3547** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3548*/
3549static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3550 if( *pArg<0 ){
3551 *pArg = (pFile->ctrlFlags & mask)!=0;
3552 }else if( (*pArg)==0 ){
3553 pFile->ctrlFlags &= ~mask;
3554 }else{
3555 pFile->ctrlFlags |= mask;
3556 }
3557}
3558
3559/*
drh9e33c2c2007-08-31 18:34:59 +00003560** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003561*/
drhcc6bb3e2007-08-31 16:11:35 +00003562static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003563 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003564 switch( op ){
3565 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003566 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003567 return SQLITE_OK;
3568 }
drh7708e972008-11-29 00:56:52 +00003569 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003570 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003571 return SQLITE_OK;
3572 }
dan6e09d692010-07-27 18:34:15 +00003573 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003574 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003575 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003576 }
drh9ff27ec2010-05-19 19:26:05 +00003577 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003578 int rc;
3579 SimulateIOErrorBenign(1);
3580 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3581 SimulateIOErrorBenign(0);
3582 return rc;
drhf0b190d2011-07-26 16:03:07 +00003583 }
3584 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003585 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3586 return SQLITE_OK;
3587 }
drhcb15f352011-12-23 01:04:17 +00003588 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3589 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003590 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003591 }
drhde60fc22011-12-14 17:53:36 +00003592 case SQLITE_FCNTL_VFSNAME: {
3593 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3594 return SQLITE_OK;
3595 }
drh8f941bc2009-01-14 23:03:40 +00003596#ifndef NDEBUG
3597 /* The pager calls this method to signal that it has done
3598 ** a rollback and that the database is therefore unchanged and
3599 ** it hence it is OK for the transaction change counter to be
3600 ** unchanged.
3601 */
3602 case SQLITE_FCNTL_DB_UNCHANGED: {
3603 ((unixFile*)id)->dbUpdate = 0;
3604 return SQLITE_OK;
3605 }
3606#endif
drhd2cb50b2009-01-09 21:41:17 +00003607#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003608 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003609 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003610 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003611 }
drhd2cb50b2009-01-09 21:41:17 +00003612#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003613 }
drh0b52b7d2011-01-26 19:46:22 +00003614 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003615}
3616
3617/*
danielk1977a3d4c882007-03-23 10:08:38 +00003618** Return the sector size in bytes of the underlying block device for
3619** the specified file. This is almost always 512 bytes, but may be
3620** larger for some devices.
3621**
3622** SQLite code assumes this function cannot fail. It also assumes that
3623** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003624** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003625** same for both.
3626*/
drh1da88f02011-12-17 16:09:16 +00003627static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003628 (void)pFile;
3629 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003630}
3631
danielk197790949c22007-08-17 16:50:38 +00003632/*
drhf12b3f62011-12-21 14:42:29 +00003633** Return the device characteristics for the file.
3634**
drhcb15f352011-12-23 01:04:17 +00003635** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3636** However, that choice is contraversial since technically the underlying
3637** file system does not always provide powersafe overwrites. (In other
3638** words, after a power-loss event, parts of the file that were never
3639** written might end up being altered.) However, non-PSOW behavior is very,
3640** very rare. And asserting PSOW makes a large reduction in the amount
3641** of required I/O for journaling, since a lot of padding is eliminated.
3642** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3643** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003644*/
drhf12b3f62011-12-21 14:42:29 +00003645static int unixDeviceCharacteristics(sqlite3_file *id){
3646 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003647 if( p->ctrlFlags & UNIXFILE_PSOW ){
3648 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3649 }else{
3650 return 0;
3651 }
danielk197762079062007-08-15 17:08:46 +00003652}
3653
drhd9e5c4f2010-05-12 18:01:39 +00003654#ifndef SQLITE_OMIT_WAL
3655
3656
3657/*
drhd91c68f2010-05-14 14:52:25 +00003658** Object used to represent an shared memory buffer.
3659**
3660** When multiple threads all reference the same wal-index, each thread
3661** has its own unixShm object, but they all point to a single instance
3662** of this unixShmNode object. In other words, each wal-index is opened
3663** only once per process.
3664**
3665** Each unixShmNode object is connected to a single unixInodeInfo object.
3666** We could coalesce this object into unixInodeInfo, but that would mean
3667** every open file that does not use shared memory (in other words, most
3668** open files) would have to carry around this extra information. So
3669** the unixInodeInfo object contains a pointer to this unixShmNode object
3670** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003671**
3672** unixMutexHeld() must be true when creating or destroying
3673** this object or while reading or writing the following fields:
3674**
3675** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003676**
3677** The following fields are read-only after the object is created:
3678**
3679** fid
3680** zFilename
3681**
drhd91c68f2010-05-14 14:52:25 +00003682** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003683** unixMutexHeld() is true when reading or writing any other field
3684** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003685*/
drhd91c68f2010-05-14 14:52:25 +00003686struct unixShmNode {
3687 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003688 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003689 char *zFilename; /* Name of the mmapped file */
3690 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003691 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003692 u16 nRegion; /* Size of array apRegion */
3693 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003694 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003695 int nRef; /* Number of unixShm objects pointing to this */
3696 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003697#ifdef SQLITE_DEBUG
3698 u8 exclMask; /* Mask of exclusive locks held */
3699 u8 sharedMask; /* Mask of shared locks held */
3700 u8 nextShmId; /* Next available unixShm.id value */
3701#endif
3702};
3703
3704/*
drhd9e5c4f2010-05-12 18:01:39 +00003705** Structure used internally by this VFS to record the state of an
3706** open shared memory connection.
3707**
drhd91c68f2010-05-14 14:52:25 +00003708** The following fields are initialized when this object is created and
3709** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003710**
drhd91c68f2010-05-14 14:52:25 +00003711** unixShm.pFile
3712** unixShm.id
3713**
3714** All other fields are read/write. The unixShm.pFile->mutex must be held
3715** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003716*/
3717struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003718 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3719 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003720 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003721 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003722 u16 sharedMask; /* Mask of shared locks held */
3723 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003724};
3725
3726/*
drhd9e5c4f2010-05-12 18:01:39 +00003727** Constants used for locking
3728*/
drhbd9676c2010-06-23 17:58:38 +00003729#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003730#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003731
drhd9e5c4f2010-05-12 18:01:39 +00003732/*
drh73b64e42010-05-30 19:55:15 +00003733** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003734**
3735** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3736** otherwise.
3737*/
3738static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003739 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3740 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003741 int ofst, /* First byte of the locking range */
3742 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003743){
3744 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003745 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003746
drhd91c68f2010-05-14 14:52:25 +00003747 /* Access to the unixShmNode object is serialized by the caller */
3748 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003749
drh73b64e42010-05-30 19:55:15 +00003750 /* Shared locks never span more than one byte */
3751 assert( n==1 || lockType!=F_RDLCK );
3752
3753 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003754 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003755
drh3cb93392011-03-12 18:10:44 +00003756 if( pShmNode->h>=0 ){
3757 /* Initialize the locking parameters */
3758 memset(&f, 0, sizeof(f));
3759 f.l_type = lockType;
3760 f.l_whence = SEEK_SET;
3761 f.l_start = ofst;
3762 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003763
drh3cb93392011-03-12 18:10:44 +00003764 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3765 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3766 }
drhd9e5c4f2010-05-12 18:01:39 +00003767
3768 /* Update the global lock state and do debug tracing */
3769#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003770 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003771 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003772 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003773 if( rc==SQLITE_OK ){
3774 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003775 OSTRACE(("unlock %d ok", ofst));
3776 pShmNode->exclMask &= ~mask;
3777 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003778 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003779 OSTRACE(("read-lock %d ok", ofst));
3780 pShmNode->exclMask &= ~mask;
3781 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003782 }else{
3783 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003784 OSTRACE(("write-lock %d ok", ofst));
3785 pShmNode->exclMask |= mask;
3786 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003787 }
3788 }else{
3789 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003790 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003791 }else if( lockType==F_RDLCK ){
3792 OSTRACE(("read-lock failed"));
3793 }else{
3794 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003795 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003796 }
3797 }
drh20e1f082010-05-31 16:10:12 +00003798 OSTRACE((" - afterwards %03x,%03x\n",
3799 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003800 }
drhd9e5c4f2010-05-12 18:01:39 +00003801#endif
3802
3803 return rc;
3804}
3805
drhd9e5c4f2010-05-12 18:01:39 +00003806
3807/*
drhd91c68f2010-05-14 14:52:25 +00003808** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003809**
3810** This is not a VFS shared-memory method; it is a utility function called
3811** by VFS shared-memory methods.
3812*/
drhd91c68f2010-05-14 14:52:25 +00003813static void unixShmPurge(unixFile *pFd){
3814 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003815 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003816 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003817 int i;
drhd91c68f2010-05-14 14:52:25 +00003818 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003819 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003820 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003821 if( p->h>=0 ){
3822 munmap(p->apRegion[i], p->szRegion);
3823 }else{
3824 sqlite3_free(p->apRegion[i]);
3825 }
dan13a3cb82010-06-11 19:04:21 +00003826 }
dan18801912010-06-14 14:07:50 +00003827 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003828 if( p->h>=0 ){
3829 robust_close(pFd, p->h, __LINE__);
3830 p->h = -1;
3831 }
drhd91c68f2010-05-14 14:52:25 +00003832 p->pInode->pShmNode = 0;
3833 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003834 }
3835}
3836
3837/*
danda9fe0c2010-07-13 18:44:03 +00003838** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003839** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003840**
drh7234c6d2010-06-19 15:10:09 +00003841** The file used to implement shared-memory is in the same directory
3842** as the open database file and has the same name as the open database
3843** file with the "-shm" suffix added. For example, if the database file
3844** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003845** for shared memory will be called "/home/user1/config.db-shm".
3846**
3847** Another approach to is to use files in /dev/shm or /dev/tmp or an
3848** some other tmpfs mount. But if a file in a different directory
3849** from the database file is used, then differing access permissions
3850** or a chroot() might cause two different processes on the same
3851** database to end up using different files for shared memory -
3852** meaning that their memory would not really be shared - resulting
3853** in database corruption. Nevertheless, this tmpfs file usage
3854** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3855** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3856** option results in an incompatible build of SQLite; builds of SQLite
3857** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3858** same database file at the same time, database corruption will likely
3859** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3860** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003861**
3862** When opening a new shared-memory file, if no other instances of that
3863** file are currently open, in this process or in other processes, then
3864** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003865**
3866** If the original database file (pDbFd) is using the "unix-excl" VFS
3867** that means that an exclusive lock is held on the database file and
3868** that no other processes are able to read or write the database. In
3869** that case, we do not really need shared memory. No shared memory
3870** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003871*/
danda9fe0c2010-07-13 18:44:03 +00003872static int unixOpenSharedMemory(unixFile *pDbFd){
3873 struct unixShm *p = 0; /* The connection to be opened */
3874 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3875 int rc; /* Result code */
3876 unixInodeInfo *pInode; /* The inode of fd */
3877 char *zShmFilename; /* Name of the file used for SHM */
3878 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003879
danda9fe0c2010-07-13 18:44:03 +00003880 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003881 p = sqlite3_malloc( sizeof(*p) );
3882 if( p==0 ) return SQLITE_NOMEM;
3883 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003884 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003885
danda9fe0c2010-07-13 18:44:03 +00003886 /* Check to see if a unixShmNode object already exists. Reuse an existing
3887 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003888 */
3889 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003890 pInode = pDbFd->pInode;
3891 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003892 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003893 struct stat sStat; /* fstat() info for database file */
3894
3895 /* Call fstat() to figure out the permissions on the database file. If
3896 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00003897 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00003898 */
drh3cb93392011-03-12 18:10:44 +00003899 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003900 rc = SQLITE_IOERR_FSTAT;
3901 goto shm_open_err;
3902 }
3903
drha4ced192010-07-15 18:32:40 +00003904#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003905 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003906#else
drh52bcde02012-01-03 14:50:45 +00003907 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003908#endif
drh7234c6d2010-06-19 15:10:09 +00003909 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003910 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003911 rc = SQLITE_NOMEM;
3912 goto shm_open_err;
3913 }
drh9cb5a0d2012-01-05 21:19:54 +00003914 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003915 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003916#ifdef SQLITE_SHM_DIRECTORY
3917 sqlite3_snprintf(nShmFilename, zShmFilename,
3918 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3919 (u32)sStat.st_ino, (u32)sStat.st_dev);
3920#else
drh7234c6d2010-06-19 15:10:09 +00003921 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003922 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003923#endif
drhd91c68f2010-05-14 14:52:25 +00003924 pShmNode->h = -1;
3925 pDbFd->pInode->pShmNode = pShmNode;
3926 pShmNode->pInode = pDbFd->pInode;
3927 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3928 if( pShmNode->mutex==0 ){
3929 rc = SQLITE_NOMEM;
3930 goto shm_open_err;
3931 }
drhd9e5c4f2010-05-12 18:01:39 +00003932
drh3cb93392011-03-12 18:10:44 +00003933 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003934 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003935 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003936 openFlags = O_RDONLY;
3937 pShmNode->isReadonly = 1;
3938 }
3939 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003940 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003941 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3942 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003943 }
drhac7c3ac2012-02-11 19:23:48 +00003944
3945 /* If this process is running as root, make sure that the SHM file
3946 ** is owned by the same user that owns the original database. Otherwise,
3947 ** the original owner will not be able to connect. If this process is
drh3ee34842012-02-11 21:21:17 +00003948 ** not root, the following fchown() will fail, but we don't care. The
3949 ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
3950 ** warnings.
drhac7c3ac2012-02-11 19:23:48 +00003951 */
drh23c4b972012-02-11 23:55:15 +00003952 if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
drh3ee34842012-02-11 21:21:17 +00003953 pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
3954 }
drh3cb93392011-03-12 18:10:44 +00003955
3956 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003957 ** If not, truncate the file to zero length.
3958 */
3959 rc = SQLITE_OK;
3960 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3961 if( robust_ftruncate(pShmNode->h, 0) ){
3962 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003963 }
3964 }
drh66dfec8b2011-06-01 20:01:49 +00003965 if( rc==SQLITE_OK ){
3966 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3967 }
3968 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003969 }
drhd9e5c4f2010-05-12 18:01:39 +00003970 }
3971
drhd91c68f2010-05-14 14:52:25 +00003972 /* Make the new connection a child of the unixShmNode */
3973 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003974#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003975 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003976#endif
drhd91c68f2010-05-14 14:52:25 +00003977 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003978 pDbFd->pShm = p;
3979 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003980
3981 /* The reference count on pShmNode has already been incremented under
3982 ** the cover of the unixEnterMutex() mutex and the pointer from the
3983 ** new (struct unixShm) object to the pShmNode has been set. All that is
3984 ** left to do is to link the new object into the linked list starting
3985 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3986 ** mutex.
3987 */
3988 sqlite3_mutex_enter(pShmNode->mutex);
3989 p->pNext = pShmNode->pFirst;
3990 pShmNode->pFirst = p;
3991 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003992 return SQLITE_OK;
3993
3994 /* Jump here on any error */
3995shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003996 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003997 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003998 unixLeaveMutex();
3999 return rc;
4000}
4001
4002/*
danda9fe0c2010-07-13 18:44:03 +00004003** This function is called to obtain a pointer to region iRegion of the
4004** shared-memory associated with the database file fd. Shared-memory regions
4005** are numbered starting from zero. Each shared-memory region is szRegion
4006** bytes in size.
4007**
4008** If an error occurs, an error code is returned and *pp is set to NULL.
4009**
4010** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4011** region has not been allocated (by any client, including one running in a
4012** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4013** bExtend is non-zero and the requested shared-memory region has not yet
4014** been allocated, it is allocated by this function.
4015**
4016** If the shared-memory region has already been allocated or is allocated by
4017** this call as described above, then it is mapped into this processes
4018** address space (if it is not already), *pp is set to point to the mapped
4019** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004020*/
danda9fe0c2010-07-13 18:44:03 +00004021static int unixShmMap(
4022 sqlite3_file *fd, /* Handle open on database file */
4023 int iRegion, /* Region to retrieve */
4024 int szRegion, /* Size of regions */
4025 int bExtend, /* True to extend file if necessary */
4026 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004027){
danda9fe0c2010-07-13 18:44:03 +00004028 unixFile *pDbFd = (unixFile*)fd;
4029 unixShm *p;
4030 unixShmNode *pShmNode;
4031 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004032
danda9fe0c2010-07-13 18:44:03 +00004033 /* If the shared-memory file has not yet been opened, open it now. */
4034 if( pDbFd->pShm==0 ){
4035 rc = unixOpenSharedMemory(pDbFd);
4036 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004037 }
drhd9e5c4f2010-05-12 18:01:39 +00004038
danda9fe0c2010-07-13 18:44:03 +00004039 p = pDbFd->pShm;
4040 pShmNode = p->pShmNode;
4041 sqlite3_mutex_enter(pShmNode->mutex);
4042 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004043 assert( pShmNode->pInode==pDbFd->pInode );
4044 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4045 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004046
4047 if( pShmNode->nRegion<=iRegion ){
4048 char **apNew; /* New apRegion[] array */
4049 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4050 struct stat sStat; /* Used by fstat() */
4051
4052 pShmNode->szRegion = szRegion;
4053
drh3cb93392011-03-12 18:10:44 +00004054 if( pShmNode->h>=0 ){
4055 /* The requested region is not mapped into this processes address space.
4056 ** Check to see if it has been allocated (i.e. if the wal-index file is
4057 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004058 */
drh3cb93392011-03-12 18:10:44 +00004059 if( osFstat(pShmNode->h, &sStat) ){
4060 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004061 goto shmpage_out;
4062 }
drh3cb93392011-03-12 18:10:44 +00004063
4064 if( sStat.st_size<nByte ){
4065 /* The requested memory region does not exist. If bExtend is set to
4066 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4067 **
4068 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4069 ** the requested memory region.
4070 */
4071 if( !bExtend ) goto shmpage_out;
4072 if( robust_ftruncate(pShmNode->h, nByte) ){
4073 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4074 pShmNode->zFilename);
4075 goto shmpage_out;
4076 }
4077 }
danda9fe0c2010-07-13 18:44:03 +00004078 }
4079
4080 /* Map the requested memory region into this processes address space. */
4081 apNew = (char **)sqlite3_realloc(
4082 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4083 );
4084 if( !apNew ){
4085 rc = SQLITE_IOERR_NOMEM;
4086 goto shmpage_out;
4087 }
4088 pShmNode->apRegion = apNew;
4089 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004090 void *pMem;
4091 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004092 pMem = mmap(0, szRegion,
4093 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004094 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4095 );
4096 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004097 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004098 goto shmpage_out;
4099 }
4100 }else{
4101 pMem = sqlite3_malloc(szRegion);
4102 if( pMem==0 ){
4103 rc = SQLITE_NOMEM;
4104 goto shmpage_out;
4105 }
4106 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004107 }
4108 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4109 pShmNode->nRegion++;
4110 }
4111 }
4112
4113shmpage_out:
4114 if( pShmNode->nRegion>iRegion ){
4115 *pp = pShmNode->apRegion[iRegion];
4116 }else{
4117 *pp = 0;
4118 }
drh66dfec8b2011-06-01 20:01:49 +00004119 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004120 sqlite3_mutex_leave(pShmNode->mutex);
4121 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004122}
4123
4124/*
drhd9e5c4f2010-05-12 18:01:39 +00004125** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004126**
4127** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4128** different here than in posix. In xShmLock(), one can go from unlocked
4129** to shared and back or from unlocked to exclusive and back. But one may
4130** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004131*/
4132static int unixShmLock(
4133 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004134 int ofst, /* First lock to acquire or release */
4135 int n, /* Number of locks to acquire or release */
4136 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004137){
drh73b64e42010-05-30 19:55:15 +00004138 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4139 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4140 unixShm *pX; /* For looping over all siblings */
4141 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4142 int rc = SQLITE_OK; /* Result code */
4143 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004144
drhd91c68f2010-05-14 14:52:25 +00004145 assert( pShmNode==pDbFd->pInode->pShmNode );
4146 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004147 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004148 assert( n>=1 );
4149 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4150 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4151 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4152 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4153 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004154 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4155 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004156
drhc99597c2010-05-31 01:41:15 +00004157 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004158 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004159 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004160 if( flags & SQLITE_SHM_UNLOCK ){
4161 u16 allMask = 0; /* Mask of locks held by siblings */
4162
4163 /* See if any siblings hold this same lock */
4164 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4165 if( pX==p ) continue;
4166 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4167 allMask |= pX->sharedMask;
4168 }
4169
4170 /* Unlock the system-level locks */
4171 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004172 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004173 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004174 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004175 }
drh73b64e42010-05-30 19:55:15 +00004176
4177 /* Undo the local locks */
4178 if( rc==SQLITE_OK ){
4179 p->exclMask &= ~mask;
4180 p->sharedMask &= ~mask;
4181 }
4182 }else if( flags & SQLITE_SHM_SHARED ){
4183 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4184
4185 /* Find out which shared locks are already held by sibling connections.
4186 ** If any sibling already holds an exclusive lock, go ahead and return
4187 ** SQLITE_BUSY.
4188 */
4189 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004190 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004191 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004192 break;
4193 }
4194 allShared |= pX->sharedMask;
4195 }
4196
4197 /* Get shared locks at the system level, if necessary */
4198 if( rc==SQLITE_OK ){
4199 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004200 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004201 }else{
drh73b64e42010-05-30 19:55:15 +00004202 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004203 }
drhd9e5c4f2010-05-12 18:01:39 +00004204 }
drh73b64e42010-05-30 19:55:15 +00004205
4206 /* Get the local shared locks */
4207 if( rc==SQLITE_OK ){
4208 p->sharedMask |= mask;
4209 }
4210 }else{
4211 /* Make sure no sibling connections hold locks that will block this
4212 ** lock. If any do, return SQLITE_BUSY right away.
4213 */
4214 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004215 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4216 rc = SQLITE_BUSY;
4217 break;
4218 }
4219 }
4220
4221 /* Get the exclusive locks at the system level. Then if successful
4222 ** also mark the local connection as being locked.
4223 */
4224 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004225 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004226 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004227 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004228 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004229 }
drhd9e5c4f2010-05-12 18:01:39 +00004230 }
4231 }
drhd91c68f2010-05-14 14:52:25 +00004232 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004233 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4234 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004235 return rc;
4236}
4237
drh286a2882010-05-20 23:51:06 +00004238/*
4239** Implement a memory barrier or memory fence on shared memory.
4240**
4241** All loads and stores begun before the barrier must complete before
4242** any load or store begun after the barrier.
4243*/
4244static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004245 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004246){
drhff828942010-06-26 21:34:06 +00004247 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004248 unixEnterMutex();
4249 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004250}
4251
dan18801912010-06-14 14:07:50 +00004252/*
danda9fe0c2010-07-13 18:44:03 +00004253** Close a connection to shared-memory. Delete the underlying
4254** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004255**
4256** If there is no shared memory associated with the connection then this
4257** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004258*/
danda9fe0c2010-07-13 18:44:03 +00004259static int unixShmUnmap(
4260 sqlite3_file *fd, /* The underlying database file */
4261 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004262){
danda9fe0c2010-07-13 18:44:03 +00004263 unixShm *p; /* The connection to be closed */
4264 unixShmNode *pShmNode; /* The underlying shared-memory file */
4265 unixShm **pp; /* For looping over sibling connections */
4266 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004267
danda9fe0c2010-07-13 18:44:03 +00004268 pDbFd = (unixFile*)fd;
4269 p = pDbFd->pShm;
4270 if( p==0 ) return SQLITE_OK;
4271 pShmNode = p->pShmNode;
4272
4273 assert( pShmNode==pDbFd->pInode->pShmNode );
4274 assert( pShmNode->pInode==pDbFd->pInode );
4275
4276 /* Remove connection p from the set of connections associated
4277 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004278 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004279 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4280 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004281
danda9fe0c2010-07-13 18:44:03 +00004282 /* Free the connection p */
4283 sqlite3_free(p);
4284 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004285 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004286
4287 /* If pShmNode->nRef has reached 0, then close the underlying
4288 ** shared-memory file, too */
4289 unixEnterMutex();
4290 assert( pShmNode->nRef>0 );
4291 pShmNode->nRef--;
4292 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004293 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004294 unixShmPurge(pDbFd);
4295 }
4296 unixLeaveMutex();
4297
4298 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004299}
drh286a2882010-05-20 23:51:06 +00004300
danda9fe0c2010-07-13 18:44:03 +00004301
drhd9e5c4f2010-05-12 18:01:39 +00004302#else
drh6b017cc2010-06-14 18:01:46 +00004303# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004304# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004305# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004306# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004307#endif /* #ifndef SQLITE_OMIT_WAL */
4308
drh734c9862008-11-28 15:37:20 +00004309/*
4310** Here ends the implementation of all sqlite3_file methods.
4311**
4312********************** End sqlite3_file Methods *******************************
4313******************************************************************************/
4314
4315/*
drh6b9d6dd2008-12-03 19:34:47 +00004316** This division contains definitions of sqlite3_io_methods objects that
4317** implement various file locking strategies. It also contains definitions
4318** of "finder" functions. A finder-function is used to locate the appropriate
4319** sqlite3_io_methods object for a particular database file. The pAppData
4320** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4321** the correct finder-function for that VFS.
4322**
4323** Most finder functions return a pointer to a fixed sqlite3_io_methods
4324** object. The only interesting finder-function is autolockIoFinder, which
4325** looks at the filesystem type and tries to guess the best locking
4326** strategy from that.
4327**
drh1875f7a2008-12-08 18:19:17 +00004328** For finder-funtion F, two objects are created:
4329**
4330** (1) The real finder-function named "FImpt()".
4331**
dane946c392009-08-22 11:39:46 +00004332** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004333**
4334**
4335** A pointer to the F pointer is used as the pAppData value for VFS
4336** objects. We have to do this instead of letting pAppData point
4337** directly at the finder-function since C90 rules prevent a void*
4338** from be cast into a function pointer.
4339**
drh6b9d6dd2008-12-03 19:34:47 +00004340**
drh7708e972008-11-29 00:56:52 +00004341** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004342**
drh7708e972008-11-29 00:56:52 +00004343** * A constant sqlite3_io_methods object call METHOD that has locking
4344** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4345**
4346** * An I/O method finder function called FINDER that returns a pointer
4347** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004348*/
drhd9e5c4f2010-05-12 18:01:39 +00004349#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004350static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004351 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004352 CLOSE, /* xClose */ \
4353 unixRead, /* xRead */ \
4354 unixWrite, /* xWrite */ \
4355 unixTruncate, /* xTruncate */ \
4356 unixSync, /* xSync */ \
4357 unixFileSize, /* xFileSize */ \
4358 LOCK, /* xLock */ \
4359 UNLOCK, /* xUnlock */ \
4360 CKLOCK, /* xCheckReservedLock */ \
4361 unixFileControl, /* xFileControl */ \
4362 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004363 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004364 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004365 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004366 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004367 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004368}; \
drh0c2694b2009-09-03 16:23:44 +00004369static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4370 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004371 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004372} \
drh0c2694b2009-09-03 16:23:44 +00004373static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004374 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004375
4376/*
4377** Here are all of the sqlite3_io_methods objects for each of the
4378** locking strategies. Functions that return pointers to these methods
4379** are also created.
4380*/
4381IOMETHODS(
4382 posixIoFinder, /* Finder function name */
4383 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004384 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004385 unixClose, /* xClose method */
4386 unixLock, /* xLock method */
4387 unixUnlock, /* xUnlock method */
4388 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004389)
drh7708e972008-11-29 00:56:52 +00004390IOMETHODS(
4391 nolockIoFinder, /* Finder function name */
4392 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004393 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004394 nolockClose, /* xClose method */
4395 nolockLock, /* xLock method */
4396 nolockUnlock, /* xUnlock method */
4397 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004398)
drh7708e972008-11-29 00:56:52 +00004399IOMETHODS(
4400 dotlockIoFinder, /* Finder function name */
4401 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004402 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004403 dotlockClose, /* xClose method */
4404 dotlockLock, /* xLock method */
4405 dotlockUnlock, /* xUnlock method */
4406 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004407)
drh7708e972008-11-29 00:56:52 +00004408
chw78a13182009-04-07 05:35:03 +00004409#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004410IOMETHODS(
4411 flockIoFinder, /* Finder function name */
4412 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004413 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004414 flockClose, /* xClose method */
4415 flockLock, /* xLock method */
4416 flockUnlock, /* xUnlock method */
4417 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004418)
drh7708e972008-11-29 00:56:52 +00004419#endif
4420
drh6c7d5c52008-11-21 20:32:33 +00004421#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004422IOMETHODS(
4423 semIoFinder, /* Finder function name */
4424 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004425 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004426 semClose, /* xClose method */
4427 semLock, /* xLock method */
4428 semUnlock, /* xUnlock method */
4429 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004430)
aswiftaebf4132008-11-21 00:10:35 +00004431#endif
drh7708e972008-11-29 00:56:52 +00004432
drhd2cb50b2009-01-09 21:41:17 +00004433#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004434IOMETHODS(
4435 afpIoFinder, /* Finder function name */
4436 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004437 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004438 afpClose, /* xClose method */
4439 afpLock, /* xLock method */
4440 afpUnlock, /* xUnlock method */
4441 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004442)
drh715ff302008-12-03 22:32:44 +00004443#endif
4444
4445/*
4446** The proxy locking method is a "super-method" in the sense that it
4447** opens secondary file descriptors for the conch and lock files and
4448** it uses proxy, dot-file, AFP, and flock() locking methods on those
4449** secondary files. For this reason, the division that implements
4450** proxy locking is located much further down in the file. But we need
4451** to go ahead and define the sqlite3_io_methods and finder function
4452** for proxy locking here. So we forward declare the I/O methods.
4453*/
drhd2cb50b2009-01-09 21:41:17 +00004454#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004455static int proxyClose(sqlite3_file*);
4456static int proxyLock(sqlite3_file*, int);
4457static int proxyUnlock(sqlite3_file*, int);
4458static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004459IOMETHODS(
4460 proxyIoFinder, /* Finder function name */
4461 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004462 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004463 proxyClose, /* xClose method */
4464 proxyLock, /* xLock method */
4465 proxyUnlock, /* xUnlock method */
4466 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004467)
aswiftaebf4132008-11-21 00:10:35 +00004468#endif
drh7708e972008-11-29 00:56:52 +00004469
drh7ed97b92010-01-20 13:07:21 +00004470/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4471#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4472IOMETHODS(
4473 nfsIoFinder, /* Finder function name */
4474 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004475 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004476 unixClose, /* xClose method */
4477 unixLock, /* xLock method */
4478 nfsUnlock, /* xUnlock method */
4479 unixCheckReservedLock /* xCheckReservedLock method */
4480)
4481#endif
drh7708e972008-11-29 00:56:52 +00004482
drhd2cb50b2009-01-09 21:41:17 +00004483#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004484/*
drh6b9d6dd2008-12-03 19:34:47 +00004485** This "finder" function attempts to determine the best locking strategy
4486** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004487** object that implements that strategy.
4488**
4489** This is for MacOSX only.
4490*/
drh1875f7a2008-12-08 18:19:17 +00004491static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004492 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004493 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004494){
4495 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004496 const char *zFilesystem; /* Filesystem type name */
4497 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004498 } aMap[] = {
4499 { "hfs", &posixIoMethods },
4500 { "ufs", &posixIoMethods },
4501 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004502 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004503 { "webdav", &nolockIoMethods },
4504 { 0, 0 }
4505 };
4506 int i;
4507 struct statfs fsInfo;
4508 struct flock lockInfo;
4509
4510 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004511 /* If filePath==NULL that means we are dealing with a transient file
4512 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004513 return &nolockIoMethods;
4514 }
4515 if( statfs(filePath, &fsInfo) != -1 ){
4516 if( fsInfo.f_flags & MNT_RDONLY ){
4517 return &nolockIoMethods;
4518 }
4519 for(i=0; aMap[i].zFilesystem; i++){
4520 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4521 return aMap[i].pMethods;
4522 }
4523 }
4524 }
4525
4526 /* Default case. Handles, amongst others, "nfs".
4527 ** Test byte-range lock using fcntl(). If the call succeeds,
4528 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004529 */
drh7708e972008-11-29 00:56:52 +00004530 lockInfo.l_len = 1;
4531 lockInfo.l_start = 0;
4532 lockInfo.l_whence = SEEK_SET;
4533 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004534 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004535 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4536 return &nfsIoMethods;
4537 } else {
4538 return &posixIoMethods;
4539 }
drh7708e972008-11-29 00:56:52 +00004540 }else{
4541 return &dotlockIoMethods;
4542 }
4543}
drh0c2694b2009-09-03 16:23:44 +00004544static const sqlite3_io_methods
4545 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004546
drhd2cb50b2009-01-09 21:41:17 +00004547#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004548
chw78a13182009-04-07 05:35:03 +00004549#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4550/*
4551** This "finder" function attempts to determine the best locking strategy
4552** for the database file "filePath". It then returns the sqlite3_io_methods
4553** object that implements that strategy.
4554**
4555** This is for VXWorks only.
4556*/
4557static const sqlite3_io_methods *autolockIoFinderImpl(
4558 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004559 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004560){
4561 struct flock lockInfo;
4562
4563 if( !filePath ){
4564 /* If filePath==NULL that means we are dealing with a transient file
4565 ** that does not need to be locked. */
4566 return &nolockIoMethods;
4567 }
4568
4569 /* Test if fcntl() is supported and use POSIX style locks.
4570 ** Otherwise fall back to the named semaphore method.
4571 */
4572 lockInfo.l_len = 1;
4573 lockInfo.l_start = 0;
4574 lockInfo.l_whence = SEEK_SET;
4575 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004576 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004577 return &posixIoMethods;
4578 }else{
4579 return &semIoMethods;
4580 }
4581}
drh0c2694b2009-09-03 16:23:44 +00004582static const sqlite3_io_methods
4583 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004584
4585#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4586
drh7708e972008-11-29 00:56:52 +00004587/*
4588** An abstract type for a pointer to a IO method finder function:
4589*/
drh0c2694b2009-09-03 16:23:44 +00004590typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004591
aswiftaebf4132008-11-21 00:10:35 +00004592
drh734c9862008-11-28 15:37:20 +00004593/****************************************************************************
4594**************************** sqlite3_vfs methods ****************************
4595**
4596** This division contains the implementation of methods on the
4597** sqlite3_vfs object.
4598*/
4599
danielk1977a3d4c882007-03-23 10:08:38 +00004600/*
danielk1977e339d652008-06-28 11:23:00 +00004601** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004602*/
4603static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004604 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004605 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004606 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004607 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004608 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004609){
drh7708e972008-11-29 00:56:52 +00004610 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004611 unixFile *pNew = (unixFile *)pId;
4612 int rc = SQLITE_OK;
4613
drh8af6c222010-05-14 12:43:01 +00004614 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004615
dan00157392010-10-05 11:33:15 +00004616 /* Usually the path zFilename should not be a relative pathname. The
4617 ** exception is when opening the proxy "conch" file in builds that
4618 ** include the special Apple locking styles.
4619 */
dan00157392010-10-05 11:33:15 +00004620#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004621 assert( zFilename==0 || zFilename[0]=='/'
4622 || pVfs->pAppData==(void*)&autolockIoFinder );
4623#else
4624 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004625#endif
dan00157392010-10-05 11:33:15 +00004626
drhb07028f2011-10-14 21:49:18 +00004627 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004628 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004629
drh308c2a52010-05-14 11:30:18 +00004630 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004631 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004632 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004633 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004634 pNew->ctrlFlags = (u8)ctrlFlags;
4635 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4636 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004637 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004638 }
drha7e61d82011-03-12 17:02:57 +00004639 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004640 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004641 }
drh339eb0b2008-03-07 15:34:11 +00004642
drh6c7d5c52008-11-21 20:32:33 +00004643#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004644 pNew->pId = vxworksFindFileId(zFilename);
4645 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004646 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004647 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004648 }
4649#endif
4650
drhc02a43a2012-01-10 23:18:38 +00004651 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004652 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004653 }else{
drh0c2694b2009-09-03 16:23:44 +00004654 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004655#if SQLITE_ENABLE_LOCKING_STYLE
4656 /* Cache zFilename in the locking context (AFP and dotlock override) for
4657 ** proxyLock activation is possible (remote proxy is based on db name)
4658 ** zFilename remains valid until file is closed, to support */
4659 pNew->lockingContext = (void*)zFilename;
4660#endif
drhda0e7682008-07-30 15:27:54 +00004661 }
danielk1977e339d652008-06-28 11:23:00 +00004662
drh7ed97b92010-01-20 13:07:21 +00004663 if( pLockingStyle == &posixIoMethods
4664#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4665 || pLockingStyle == &nfsIoMethods
4666#endif
4667 ){
drh7708e972008-11-29 00:56:52 +00004668 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004669 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004670 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004671 /* If an error occured in findInodeInfo(), close the file descriptor
4672 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004673 ** in two scenarios:
4674 **
4675 ** (a) A call to fstat() failed.
4676 ** (b) A malloc failed.
4677 **
4678 ** Scenario (b) may only occur if the process is holding no other
4679 ** file descriptors open on the same file. If there were other file
4680 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004681 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004682 ** handle h - as it is guaranteed that no posix locks will be released
4683 ** by doing so.
4684 **
4685 ** If scenario (a) caused the error then things are not so safe. The
4686 ** implicit assumption here is that if fstat() fails, things are in
4687 ** such bad shape that dropping a lock or two doesn't matter much.
4688 */
drh0e9365c2011-03-02 02:08:13 +00004689 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004690 h = -1;
4691 }
drh7708e972008-11-29 00:56:52 +00004692 unixLeaveMutex();
4693 }
danielk1977e339d652008-06-28 11:23:00 +00004694
drhd2cb50b2009-01-09 21:41:17 +00004695#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004696 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004697 /* AFP locking uses the file path so it needs to be included in
4698 ** the afpLockingContext.
4699 */
4700 afpLockingContext *pCtx;
4701 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4702 if( pCtx==0 ){
4703 rc = SQLITE_NOMEM;
4704 }else{
4705 /* NB: zFilename exists and remains valid until the file is closed
4706 ** according to requirement F11141. So we do not need to make a
4707 ** copy of the filename. */
4708 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004709 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004710 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004711 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004712 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004713 if( rc!=SQLITE_OK ){
4714 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004715 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004716 h = -1;
4717 }
drh7708e972008-11-29 00:56:52 +00004718 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004719 }
drh7708e972008-11-29 00:56:52 +00004720 }
4721#endif
danielk1977e339d652008-06-28 11:23:00 +00004722
drh7708e972008-11-29 00:56:52 +00004723 else if( pLockingStyle == &dotlockIoMethods ){
4724 /* Dotfile locking uses the file path so it needs to be included in
4725 ** the dotlockLockingContext
4726 */
4727 char *zLockFile;
4728 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004729 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004730 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004731 zLockFile = (char *)sqlite3_malloc(nFilename);
4732 if( zLockFile==0 ){
4733 rc = SQLITE_NOMEM;
4734 }else{
4735 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004736 }
drh7708e972008-11-29 00:56:52 +00004737 pNew->lockingContext = zLockFile;
4738 }
danielk1977e339d652008-06-28 11:23:00 +00004739
drh6c7d5c52008-11-21 20:32:33 +00004740#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004741 else if( pLockingStyle == &semIoMethods ){
4742 /* Named semaphore locking uses the file path so it needs to be
4743 ** included in the semLockingContext
4744 */
4745 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004746 rc = findInodeInfo(pNew, &pNew->pInode);
4747 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4748 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004749 int n;
drh2238dcc2009-08-27 17:56:20 +00004750 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004751 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004752 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004753 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004754 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4755 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004756 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004757 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004758 }
chw97185482008-11-17 08:05:31 +00004759 }
drh7708e972008-11-29 00:56:52 +00004760 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004761 }
drh7708e972008-11-29 00:56:52 +00004762#endif
aswift5b1a2562008-08-22 00:22:35 +00004763
4764 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004765#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004766 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004767 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004768 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004769 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004770 isDelete = 0;
4771 }
drhc02a43a2012-01-10 23:18:38 +00004772 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004773#endif
danielk1977e339d652008-06-28 11:23:00 +00004774 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004775 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004776 }else{
drh7708e972008-11-29 00:56:52 +00004777 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004778 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004779 }
danielk1977e339d652008-06-28 11:23:00 +00004780 return rc;
drh054889e2005-11-30 03:20:31 +00004781}
drh9c06c952005-11-26 00:25:00 +00004782
danielk1977ad94b582007-08-20 06:44:22 +00004783/*
drh8b3cf822010-06-01 21:02:51 +00004784** Return the name of a directory in which to put temporary files.
4785** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004786*/
drh7234c6d2010-06-19 15:10:09 +00004787static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004788 static const char *azDirs[] = {
4789 0,
aswiftaebf4132008-11-21 00:10:35 +00004790 0,
danielk197717b90b52008-06-06 11:11:25 +00004791 "/var/tmp",
4792 "/usr/tmp",
4793 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004794 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004795 };
drh8b3cf822010-06-01 21:02:51 +00004796 unsigned int i;
4797 struct stat buf;
4798 const char *zDir = 0;
4799
4800 azDirs[0] = sqlite3_temp_directory;
4801 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004802 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004803 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004804 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004805 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004806 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004807 break;
4808 }
4809 return zDir;
4810}
4811
4812/*
4813** Create a temporary file name in zBuf. zBuf must be allocated
4814** by the calling process and must be big enough to hold at least
4815** pVfs->mxPathname bytes.
4816*/
4817static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004818 static const unsigned char zChars[] =
4819 "abcdefghijklmnopqrstuvwxyz"
4820 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4821 "0123456789";
drh41022642008-11-21 00:24:42 +00004822 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004823 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004824
4825 /* It's odd to simulate an io-error here, but really this is just
4826 ** using the io-error infrastructure to test that SQLite handles this
4827 ** function failing.
4828 */
4829 SimulateIOError( return SQLITE_IOERR );
4830
drh7234c6d2010-06-19 15:10:09 +00004831 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004832 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004833
4834 /* Check that the output buffer is large enough for the temporary file
4835 ** name. If it is not, return SQLITE_ERROR.
4836 */
drhc02a43a2012-01-10 23:18:38 +00004837 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004838 return SQLITE_ERROR;
4839 }
4840
4841 do{
drhc02a43a2012-01-10 23:18:38 +00004842 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004843 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004844 sqlite3_randomness(15, &zBuf[j]);
4845 for(i=0; i<15; i++, j++){
4846 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4847 }
4848 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004849 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004850 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004851 return SQLITE_OK;
4852}
4853
drhd2cb50b2009-01-09 21:41:17 +00004854#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004855/*
4856** Routine to transform a unixFile into a proxy-locking unixFile.
4857** Implementation in the proxy-lock division, but used by unixOpen()
4858** if SQLITE_PREFER_PROXY_LOCKING is defined.
4859*/
4860static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004861#endif
drhc66d5b62008-12-03 22:48:32 +00004862
dan08da86a2009-08-21 17:18:03 +00004863/*
4864** Search for an unused file descriptor that was opened on the database
4865** file (not a journal or master-journal file) identified by pathname
4866** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4867** argument to this function.
4868**
4869** Such a file descriptor may exist if a database connection was closed
4870** but the associated file descriptor could not be closed because some
4871** other file descriptor open on the same file is holding a file-lock.
4872** Refer to comments in the unixClose() function and the lengthy comment
4873** describing "Posix Advisory Locking" at the start of this file for
4874** further details. Also, ticket #4018.
4875**
4876** If a suitable file descriptor is found, then it is returned. If no
4877** such file descriptor is located, -1 is returned.
4878*/
dane946c392009-08-22 11:39:46 +00004879static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4880 UnixUnusedFd *pUnused = 0;
4881
4882 /* Do not search for an unused file descriptor on vxworks. Not because
4883 ** vxworks would not benefit from the change (it might, we're not sure),
4884 ** but because no way to test it is currently available. It is better
4885 ** not to risk breaking vxworks support for the sake of such an obscure
4886 ** feature. */
4887#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004888 struct stat sStat; /* Results of stat() call */
4889
4890 /* A stat() call may fail for various reasons. If this happens, it is
4891 ** almost certain that an open() call on the same path will also fail.
4892 ** For this reason, if an error occurs in the stat() call here, it is
4893 ** ignored and -1 is returned. The caller will try to open a new file
4894 ** descriptor on the same path, fail, and return an error to SQLite.
4895 **
4896 ** Even if a subsequent open() call does succeed, the consequences of
4897 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004898 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004899 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004900
4901 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004902 pInode = inodeList;
4903 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4904 || pInode->fileId.ino!=sStat.st_ino) ){
4905 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004906 }
drh8af6c222010-05-14 12:43:01 +00004907 if( pInode ){
dane946c392009-08-22 11:39:46 +00004908 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004909 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004910 pUnused = *pp;
4911 if( pUnused ){
4912 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004913 }
4914 }
4915 unixLeaveMutex();
4916 }
dane946c392009-08-22 11:39:46 +00004917#endif /* if !OS_VXWORKS */
4918 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004919}
danielk197717b90b52008-06-06 11:11:25 +00004920
4921/*
danddb0ac42010-07-14 14:48:58 +00004922** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004923** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004924** and a value suitable for passing as the third argument to open(2) is
4925** written to *pMode. If an IO error occurs, an SQLite error code is
4926** returned and the value of *pMode is not modified.
4927**
drh8c815d12012-02-13 20:16:37 +00004928** In most cases cases, this routine sets *pMode to 0, which will become
4929** an indication to robust_open() to create the file using
4930** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
4931** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00004932** this function queries the file-system for the permissions on the
4933** corresponding database file and sets *pMode to this value. Whenever
4934** possible, WAL and journal files are created using the same permissions
4935** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004936**
4937** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4938** original filename is unavailable. But 8_3_NAMES is only used for
4939** FAT filesystems and permissions do not matter there, so just use
4940** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004941*/
4942static int findCreateFileMode(
4943 const char *zPath, /* Path of file (possibly) being created */
4944 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00004945 mode_t *pMode, /* OUT: Permissions to open file with */
4946 uid_t *pUid, /* OUT: uid to set on the file */
4947 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00004948){
4949 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00004950 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00004951 *pUid = 0;
4952 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00004953 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004954 char zDb[MAX_PATHNAME+1]; /* Database file path */
4955 int nDb; /* Number of valid bytes in zDb */
4956 struct stat sStat; /* Output of stat() on database file */
4957
dana0c989d2010-11-05 18:07:37 +00004958 /* zPath is a path to a WAL or journal file. The following block derives
4959 ** the path to the associated database file from zPath. This block handles
4960 ** the following naming conventions:
4961 **
4962 ** "<path to db>-journal"
4963 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004964 ** "<path to db>-journalNN"
4965 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004966 **
drhd337c5b2011-10-20 18:23:35 +00004967 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004968 ** used by the test_multiplex.c module.
4969 */
4970 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004971#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004972 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004973 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004974#else
4975 while( zPath[nDb]!='-' ){
4976 assert( nDb>0 );
4977 assert( zPath[nDb]!='\n' );
4978 nDb--;
4979 }
4980#endif
danddb0ac42010-07-14 14:48:58 +00004981 memcpy(zDb, zPath, nDb);
4982 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004983
drh58384f12011-07-28 00:14:45 +00004984 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004985 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00004986 *pUid = sStat.st_uid;
4987 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00004988 }else{
4989 rc = SQLITE_IOERR_FSTAT;
4990 }
4991 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4992 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004993 }
4994 return rc;
4995}
4996
4997/*
danielk1977ad94b582007-08-20 06:44:22 +00004998** Open the file zPath.
4999**
danielk1977b4b47412007-08-17 15:53:36 +00005000** Previously, the SQLite OS layer used three functions in place of this
5001** one:
5002**
5003** sqlite3OsOpenReadWrite();
5004** sqlite3OsOpenReadOnly();
5005** sqlite3OsOpenExclusive();
5006**
5007** These calls correspond to the following combinations of flags:
5008**
5009** ReadWrite() -> (READWRITE | CREATE)
5010** ReadOnly() -> (READONLY)
5011** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5012**
5013** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5014** true, the file was configured to be automatically deleted when the
5015** file handle closed. To achieve the same effect using this new
5016** interface, add the DELETEONCLOSE flag to those specified above for
5017** OpenExclusive().
5018*/
5019static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005020 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5021 const char *zPath, /* Pathname of file to be opened */
5022 sqlite3_file *pFile, /* The file descriptor to be filled in */
5023 int flags, /* Input flags to control the opening */
5024 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005025){
dan08da86a2009-08-21 17:18:03 +00005026 unixFile *p = (unixFile *)pFile;
5027 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005028 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005029 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005030 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005031 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005032 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005033
5034 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5035 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5036 int isCreate = (flags & SQLITE_OPEN_CREATE);
5037 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5038 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005039#if SQLITE_ENABLE_LOCKING_STYLE
5040 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5041#endif
drh3d4435b2011-08-26 20:55:50 +00005042#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5043 struct statfs fsInfo;
5044#endif
danielk1977b4b47412007-08-17 15:53:36 +00005045
danielk1977fee2d252007-08-18 10:59:19 +00005046 /* If creating a master or main-file journal, this function will open
5047 ** a file-descriptor on the directory too. The first time unixSync()
5048 ** is called the directory file descriptor will be fsync()ed and close()d.
5049 */
drh0059eae2011-08-08 23:48:40 +00005050 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005051 eType==SQLITE_OPEN_MASTER_JOURNAL
5052 || eType==SQLITE_OPEN_MAIN_JOURNAL
5053 || eType==SQLITE_OPEN_WAL
5054 ));
danielk1977fee2d252007-08-18 10:59:19 +00005055
danielk197717b90b52008-06-06 11:11:25 +00005056 /* If argument zPath is a NULL pointer, this function is required to open
5057 ** a temporary file. Use this buffer to store the file name in.
5058 */
drhc02a43a2012-01-10 23:18:38 +00005059 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005060 const char *zName = zPath;
5061
danielk1977fee2d252007-08-18 10:59:19 +00005062 /* Check the following statements are true:
5063 **
5064 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5065 ** (b) if CREATE is set, then READWRITE must also be set, and
5066 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005067 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005068 */
danielk1977b4b47412007-08-17 15:53:36 +00005069 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005070 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005071 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005072 assert(isDelete==0 || isCreate);
5073
danddb0ac42010-07-14 14:48:58 +00005074 /* The main DB, main journal, WAL file and master journal are never
5075 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005076 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5077 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5078 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005079 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005080
danielk1977fee2d252007-08-18 10:59:19 +00005081 /* Assert that the upper layer has set one of the "file-type" flags. */
5082 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5083 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5084 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005085 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005086 );
5087
dan08da86a2009-08-21 17:18:03 +00005088 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005089
dan08da86a2009-08-21 17:18:03 +00005090 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005091 UnixUnusedFd *pUnused;
5092 pUnused = findReusableFd(zName, flags);
5093 if( pUnused ){
5094 fd = pUnused->fd;
5095 }else{
dan6aa657f2009-08-24 18:57:58 +00005096 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005097 if( !pUnused ){
5098 return SQLITE_NOMEM;
5099 }
5100 }
5101 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005102
5103 /* Database filenames are double-zero terminated if they are not
5104 ** URIs with parameters. Hence, they can always be passed into
5105 ** sqlite3_uri_parameter(). */
5106 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5107
dan08da86a2009-08-21 17:18:03 +00005108 }else if( !zName ){
5109 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005110 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005111 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005112 if( rc!=SQLITE_OK ){
5113 return rc;
5114 }
5115 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005116
5117 /* Generated temporary filenames are always double-zero terminated
5118 ** for use by sqlite3_uri_parameter(). */
5119 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005120 }
5121
dan08da86a2009-08-21 17:18:03 +00005122 /* Determine the value of the flags parameter passed to POSIX function
5123 ** open(). These must be calculated even if open() is not called, as
5124 ** they may be stored as part of the file handle and used by the
5125 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005126 if( isReadonly ) openFlags |= O_RDONLY;
5127 if( isReadWrite ) openFlags |= O_RDWR;
5128 if( isCreate ) openFlags |= O_CREAT;
5129 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5130 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005131
danielk1977b4b47412007-08-17 15:53:36 +00005132 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005133 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005134 uid_t uid; /* Userid for the file */
5135 gid_t gid; /* Groupid for the file */
5136 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005137 if( rc!=SQLITE_OK ){
5138 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005139 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005140 return rc;
5141 }
drhad4f1e52011-03-04 15:43:57 +00005142 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005143 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005144 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5145 /* Failed to open the file for read/write access. Try read-only. */
5146 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005147 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005148 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005149 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005150 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005151 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005152 }
5153 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005154 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005155 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005156 }
drhac7c3ac2012-02-11 19:23:48 +00005157
5158 /* If this process is running as root and if creating a new rollback
5159 ** journal or WAL file, set the ownership of the journal or WAL to be
5160 ** the same as the original database. If we are not running as root,
drh3ee34842012-02-11 21:21:17 +00005161 ** then the fchown() call will fail, but that's ok. The "if(){}" and
5162 ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
5163 ** warnings from gcc.
drhac7c3ac2012-02-11 19:23:48 +00005164 */
5165 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh23c4b972012-02-11 23:55:15 +00005166 if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
drhac7c3ac2012-02-11 19:23:48 +00005167 }
danielk1977b4b47412007-08-17 15:53:36 +00005168 }
dan08da86a2009-08-21 17:18:03 +00005169 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005170 if( pOutFlags ){
5171 *pOutFlags = flags;
5172 }
5173
dane946c392009-08-22 11:39:46 +00005174 if( p->pUnused ){
5175 p->pUnused->fd = fd;
5176 p->pUnused->flags = flags;
5177 }
5178
danielk1977b4b47412007-08-17 15:53:36 +00005179 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005180#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005181 zPath = zName;
5182#else
drh036ac7f2011-08-08 23:18:05 +00005183 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005184#endif
danielk1977b4b47412007-08-17 15:53:36 +00005185 }
drh41022642008-11-21 00:24:42 +00005186#if SQLITE_ENABLE_LOCKING_STYLE
5187 else{
dan08da86a2009-08-21 17:18:03 +00005188 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005189 }
5190#endif
5191
drhda0e7682008-07-30 15:27:54 +00005192 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005193
drh7ed97b92010-01-20 13:07:21 +00005194
5195#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005196 if( fstatfs(fd, &fsInfo) == -1 ){
5197 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005198 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005199 return SQLITE_IOERR_ACCESS;
5200 }
5201 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5202 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5203 }
5204#endif
drhc02a43a2012-01-10 23:18:38 +00005205
5206 /* Set up appropriate ctrlFlags */
5207 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5208 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5209 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5210 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5211 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5212
drh7ed97b92010-01-20 13:07:21 +00005213#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005214#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005215 isAutoProxy = 1;
5216#endif
5217 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005218 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5219 int useProxy = 0;
5220
dan08da86a2009-08-21 17:18:03 +00005221 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5222 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005223 if( envforce!=NULL ){
5224 useProxy = atoi(envforce)>0;
5225 }else{
aswiftaebf4132008-11-21 00:10:35 +00005226 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005227 /* In theory, the close(fd) call is sub-optimal. If the file opened
5228 ** with fd is a database file, and there are other connections open
5229 ** on that file that are currently holding advisory locks on it,
5230 ** then the call to close() will cancel those locks. In practice,
5231 ** we're assuming that statfs() doesn't fail very often. At least
5232 ** not while other file descriptors opened by the same process on
5233 ** the same file are working. */
5234 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005235 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005236 rc = SQLITE_IOERR_ACCESS;
5237 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005238 }
5239 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5240 }
5241 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005242 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005243 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005244 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005245 if( rc!=SQLITE_OK ){
5246 /* Use unixClose to clean up the resources added in fillInUnixFile
5247 ** and clear all the structure's references. Specifically,
5248 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5249 */
5250 unixClose(pFile);
5251 return rc;
5252 }
aswiftaebf4132008-11-21 00:10:35 +00005253 }
dane946c392009-08-22 11:39:46 +00005254 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005255 }
5256 }
5257#endif
5258
drhc02a43a2012-01-10 23:18:38 +00005259 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5260
dane946c392009-08-22 11:39:46 +00005261open_finished:
5262 if( rc!=SQLITE_OK ){
5263 sqlite3_free(p->pUnused);
5264 }
5265 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005266}
5267
dane946c392009-08-22 11:39:46 +00005268
danielk1977b4b47412007-08-17 15:53:36 +00005269/*
danielk1977fee2d252007-08-18 10:59:19 +00005270** Delete the file at zPath. If the dirSync argument is true, fsync()
5271** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005272*/
drh6b9d6dd2008-12-03 19:34:47 +00005273static int unixDelete(
5274 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5275 const char *zPath, /* Name of file to be deleted */
5276 int dirSync /* If true, fsync() directory after deleting file */
5277){
danielk1977fee2d252007-08-18 10:59:19 +00005278 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005279 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005280 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005281 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005282 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005283 }
danielk1977d39fa702008-10-16 13:27:40 +00005284#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005285 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005286 int fd;
drh90315a22011-08-10 01:52:12 +00005287 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005288 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005289#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005290 if( fsync(fd)==-1 )
5291#else
5292 if( fsync(fd) )
5293#endif
5294 {
dane18d4952011-02-21 11:46:24 +00005295 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005296 }
drh0e9365c2011-03-02 02:08:13 +00005297 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005298 }else if( rc==SQLITE_CANTOPEN ){
5299 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005300 }
5301 }
danielk1977d138dd82008-10-15 16:02:48 +00005302#endif
danielk1977fee2d252007-08-18 10:59:19 +00005303 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005304}
5305
danielk197790949c22007-08-17 16:50:38 +00005306/*
5307** Test the existance of or access permissions of file zPath. The
5308** test performed depends on the value of flags:
5309**
5310** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5311** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5312** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5313**
5314** Otherwise return 0.
5315*/
danielk1977861f7452008-06-05 11:39:11 +00005316static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005317 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5318 const char *zPath, /* Path of the file to examine */
5319 int flags, /* What do we want to learn about the zPath file? */
5320 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005321){
rse25c0d1a2007-09-20 08:38:14 +00005322 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005323 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005324 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005325 switch( flags ){
5326 case SQLITE_ACCESS_EXISTS:
5327 amode = F_OK;
5328 break;
5329 case SQLITE_ACCESS_READWRITE:
5330 amode = W_OK|R_OK;
5331 break;
drh50d3f902007-08-27 21:10:36 +00005332 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005333 amode = R_OK;
5334 break;
5335
5336 default:
5337 assert(!"Invalid flags argument");
5338 }
drh99ab3b12011-03-02 15:09:07 +00005339 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005340 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5341 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005342 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005343 *pResOut = 0;
5344 }
5345 }
danielk1977861f7452008-06-05 11:39:11 +00005346 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005347}
5348
danielk1977b4b47412007-08-17 15:53:36 +00005349
5350/*
5351** Turn a relative pathname into a full pathname. The relative path
5352** is stored as a nul-terminated string in the buffer pointed to by
5353** zPath.
5354**
5355** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5356** (in this case, MAX_PATHNAME bytes). The full-path is written to
5357** this buffer before returning.
5358*/
danielk1977adfb9b02007-09-17 07:02:56 +00005359static int unixFullPathname(
5360 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5361 const char *zPath, /* Possibly relative input path */
5362 int nOut, /* Size of output buffer in bytes */
5363 char *zOut /* Output buffer */
5364){
danielk1977843e65f2007-09-01 16:16:15 +00005365
5366 /* It's odd to simulate an io-error here, but really this is just
5367 ** using the io-error infrastructure to test that SQLite handles this
5368 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005369 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005370 */
5371 SimulateIOError( return SQLITE_ERROR );
5372
drh153c62c2007-08-24 03:51:33 +00005373 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005374 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005375
drh3c7f2dc2007-12-06 13:26:20 +00005376 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005377 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005378 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005379 }else{
5380 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005381 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005382 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005383 }
drhea678832008-12-10 19:26:22 +00005384 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005385 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005386 }
5387 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005388}
5389
drh0ccebe72005-06-07 22:22:50 +00005390
drh761df872006-12-21 01:29:22 +00005391#ifndef SQLITE_OMIT_LOAD_EXTENSION
5392/*
5393** Interfaces for opening a shared library, finding entry points
5394** within the shared library, and closing the shared library.
5395*/
5396#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005397static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5398 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005399 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5400}
danielk197795c8a542007-09-01 06:51:27 +00005401
5402/*
5403** SQLite calls this function immediately after a call to unixDlSym() or
5404** unixDlOpen() fails (returns a null pointer). If a more detailed error
5405** message is available, it is written to zBufOut. If no error message
5406** is available, zBufOut is left unmodified and SQLite uses a default
5407** error message.
5408*/
danielk1977397d65f2008-11-19 11:35:39 +00005409static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005410 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005411 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005412 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005413 zErr = dlerror();
5414 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005415 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005416 }
drh6c7d5c52008-11-21 20:32:33 +00005417 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005418}
drh1875f7a2008-12-08 18:19:17 +00005419static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5420 /*
5421 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5422 ** cast into a pointer to a function. And yet the library dlsym() routine
5423 ** returns a void* which is really a pointer to a function. So how do we
5424 ** use dlsym() with -pedantic-errors?
5425 **
5426 ** Variable x below is defined to be a pointer to a function taking
5427 ** parameters void* and const char* and returning a pointer to a function.
5428 ** We initialize x by assigning it a pointer to the dlsym() function.
5429 ** (That assignment requires a cast.) Then we call the function that
5430 ** x points to.
5431 **
5432 ** This work-around is unlikely to work correctly on any system where
5433 ** you really cannot cast a function pointer into void*. But then, on the
5434 ** other hand, dlsym() will not work on such a system either, so we have
5435 ** not really lost anything.
5436 */
5437 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005438 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005439 x = (void(*(*)(void*,const char*))(void))dlsym;
5440 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005441}
danielk1977397d65f2008-11-19 11:35:39 +00005442static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5443 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005444 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005445}
danielk1977b4b47412007-08-17 15:53:36 +00005446#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5447 #define unixDlOpen 0
5448 #define unixDlError 0
5449 #define unixDlSym 0
5450 #define unixDlClose 0
5451#endif
5452
5453/*
danielk197790949c22007-08-17 16:50:38 +00005454** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005455*/
danielk1977397d65f2008-11-19 11:35:39 +00005456static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5457 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005458 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005459
drhbbd42a62004-05-22 17:41:58 +00005460 /* We have to initialize zBuf to prevent valgrind from reporting
5461 ** errors. The reports issued by valgrind are incorrect - we would
5462 ** prefer that the randomness be increased by making use of the
5463 ** uninitialized space in zBuf - but valgrind errors tend to worry
5464 ** some users. Rather than argue, it seems easier just to initialize
5465 ** the whole array and silence valgrind, even if that means less randomness
5466 ** in the random seed.
5467 **
5468 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005469 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005470 ** tests repeatable.
5471 */
danielk1977b4b47412007-08-17 15:53:36 +00005472 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005473#if !defined(SQLITE_TEST)
5474 {
drhc18b4042012-02-10 03:10:27 +00005475 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005476 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005477 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005478 time_t t;
5479 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005480 memcpy(zBuf, &t, sizeof(t));
5481 pid = getpid();
5482 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005483 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005484 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005485 }else{
drhc18b4042012-02-10 03:10:27 +00005486 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005487 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005488 }
drhbbd42a62004-05-22 17:41:58 +00005489 }
5490#endif
drh72cbd072008-10-14 17:58:38 +00005491 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005492}
5493
danielk1977b4b47412007-08-17 15:53:36 +00005494
drhbbd42a62004-05-22 17:41:58 +00005495/*
5496** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005497** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005498** The return value is the number of microseconds of sleep actually
5499** requested from the underlying operating system, a number which
5500** might be greater than or equal to the argument, but not less
5501** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005502*/
danielk1977397d65f2008-11-19 11:35:39 +00005503static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005504#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005505 struct timespec sp;
5506
5507 sp.tv_sec = microseconds / 1000000;
5508 sp.tv_nsec = (microseconds % 1000000) * 1000;
5509 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005510 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005511 return microseconds;
5512#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005513 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005514 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005515 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005516#else
danielk1977b4b47412007-08-17 15:53:36 +00005517 int seconds = (microseconds+999999)/1000000;
5518 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005519 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005520 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005521#endif
drh88f474a2006-01-02 20:00:12 +00005522}
5523
5524/*
drh6b9d6dd2008-12-03 19:34:47 +00005525** The following variable, if set to a non-zero value, is interpreted as
5526** the number of seconds since 1970 and is used to set the result of
5527** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005528*/
5529#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005530int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005531#endif
5532
5533/*
drhb7e8ea22010-05-03 14:32:30 +00005534** Find the current time (in Universal Coordinated Time). Write into *piNow
5535** the current time and date as a Julian Day number times 86_400_000. In
5536** other words, write into *piNow the number of milliseconds since the Julian
5537** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5538** proleptic Gregorian calendar.
5539**
drh31702252011-10-12 23:13:43 +00005540** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5541** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005542*/
5543static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5544 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005545 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005546#if defined(NO_GETTOD)
5547 time_t t;
5548 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005549 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005550#elif OS_VXWORKS
5551 struct timespec sNow;
5552 clock_gettime(CLOCK_REALTIME, &sNow);
5553 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5554#else
5555 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005556 if( gettimeofday(&sNow, 0)==0 ){
5557 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5558 }else{
5559 rc = SQLITE_ERROR;
5560 }
drhb7e8ea22010-05-03 14:32:30 +00005561#endif
5562
5563#ifdef SQLITE_TEST
5564 if( sqlite3_current_time ){
5565 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5566 }
5567#endif
5568 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005569 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005570}
5571
5572/*
drhbbd42a62004-05-22 17:41:58 +00005573** Find the current time (in Universal Coordinated Time). Write the
5574** current time and date as a Julian Day number into *prNow and
5575** return 0. Return 1 if the time and date cannot be found.
5576*/
danielk1977397d65f2008-11-19 11:35:39 +00005577static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005578 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005579 int rc;
drhff828942010-06-26 21:34:06 +00005580 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005581 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005582 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005583 return rc;
drhbbd42a62004-05-22 17:41:58 +00005584}
danielk1977b4b47412007-08-17 15:53:36 +00005585
drh6b9d6dd2008-12-03 19:34:47 +00005586/*
5587** We added the xGetLastError() method with the intention of providing
5588** better low-level error messages when operating-system problems come up
5589** during SQLite operation. But so far, none of that has been implemented
5590** in the core. So this routine is never called. For now, it is merely
5591** a place-holder.
5592*/
danielk1977397d65f2008-11-19 11:35:39 +00005593static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5594 UNUSED_PARAMETER(NotUsed);
5595 UNUSED_PARAMETER(NotUsed2);
5596 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005597 return 0;
5598}
5599
drhf2424c52010-04-26 00:04:55 +00005600
5601/*
drh734c9862008-11-28 15:37:20 +00005602************************ End of sqlite3_vfs methods ***************************
5603******************************************************************************/
5604
drh715ff302008-12-03 22:32:44 +00005605/******************************************************************************
5606************************** Begin Proxy Locking ********************************
5607**
5608** Proxy locking is a "uber-locking-method" in this sense: It uses the
5609** other locking methods on secondary lock files. Proxy locking is a
5610** meta-layer over top of the primitive locking implemented above. For
5611** this reason, the division that implements of proxy locking is deferred
5612** until late in the file (here) after all of the other I/O methods have
5613** been defined - so that the primitive locking methods are available
5614** as services to help with the implementation of proxy locking.
5615**
5616****
5617**
5618** The default locking schemes in SQLite use byte-range locks on the
5619** database file to coordinate safe, concurrent access by multiple readers
5620** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5621** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5622** as POSIX read & write locks over fixed set of locations (via fsctl),
5623** on AFP and SMB only exclusive byte-range locks are available via fsctl
5624** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5625** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5626** address in the shared range is taken for a SHARED lock, the entire
5627** shared range is taken for an EXCLUSIVE lock):
5628**
5629** PENDING_BYTE 0x40000000
5630** RESERVED_BYTE 0x40000001
5631** SHARED_RANGE 0x40000002 -> 0x40000200
5632**
5633** This works well on the local file system, but shows a nearly 100x
5634** slowdown in read performance on AFP because the AFP client disables
5635** the read cache when byte-range locks are present. Enabling the read
5636** cache exposes a cache coherency problem that is present on all OS X
5637** supported network file systems. NFS and AFP both observe the
5638** close-to-open semantics for ensuring cache coherency
5639** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5640** address the requirements for concurrent database access by multiple
5641** readers and writers
5642** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5643**
5644** To address the performance and cache coherency issues, proxy file locking
5645** changes the way database access is controlled by limiting access to a
5646** single host at a time and moving file locks off of the database file
5647** and onto a proxy file on the local file system.
5648**
5649**
5650** Using proxy locks
5651** -----------------
5652**
5653** C APIs
5654**
5655** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5656** <proxy_path> | ":auto:");
5657** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5658**
5659**
5660** SQL pragmas
5661**
5662** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5663** PRAGMA [database.]lock_proxy_file
5664**
5665** Specifying ":auto:" means that if there is a conch file with a matching
5666** host ID in it, the proxy path in the conch file will be used, otherwise
5667** a proxy path based on the user's temp dir
5668** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5669** actual proxy file name is generated from the name and path of the
5670** database file. For example:
5671**
5672** For database path "/Users/me/foo.db"
5673** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5674**
5675** Once a lock proxy is configured for a database connection, it can not
5676** be removed, however it may be switched to a different proxy path via
5677** the above APIs (assuming the conch file is not being held by another
5678** connection or process).
5679**
5680**
5681** How proxy locking works
5682** -----------------------
5683**
5684** Proxy file locking relies primarily on two new supporting files:
5685**
5686** * conch file to limit access to the database file to a single host
5687** at a time
5688**
5689** * proxy file to act as a proxy for the advisory locks normally
5690** taken on the database
5691**
5692** The conch file - to use a proxy file, sqlite must first "hold the conch"
5693** by taking an sqlite-style shared lock on the conch file, reading the
5694** contents and comparing the host's unique host ID (see below) and lock
5695** proxy path against the values stored in the conch. The conch file is
5696** stored in the same directory as the database file and the file name
5697** is patterned after the database file name as ".<databasename>-conch".
5698** If the conch file does not exist, or it's contents do not match the
5699** host ID and/or proxy path, then the lock is escalated to an exclusive
5700** lock and the conch file contents is updated with the host ID and proxy
5701** path and the lock is downgraded to a shared lock again. If the conch
5702** is held by another process (with a shared lock), the exclusive lock
5703** will fail and SQLITE_BUSY is returned.
5704**
5705** The proxy file - a single-byte file used for all advisory file locks
5706** normally taken on the database file. This allows for safe sharing
5707** of the database file for multiple readers and writers on the same
5708** host (the conch ensures that they all use the same local lock file).
5709**
drh715ff302008-12-03 22:32:44 +00005710** Requesting the lock proxy does not immediately take the conch, it is
5711** only taken when the first request to lock database file is made.
5712** This matches the semantics of the traditional locking behavior, where
5713** opening a connection to a database file does not take a lock on it.
5714** The shared lock and an open file descriptor are maintained until
5715** the connection to the database is closed.
5716**
5717** The proxy file and the lock file are never deleted so they only need
5718** to be created the first time they are used.
5719**
5720** Configuration options
5721** ---------------------
5722**
5723** SQLITE_PREFER_PROXY_LOCKING
5724**
5725** Database files accessed on non-local file systems are
5726** automatically configured for proxy locking, lock files are
5727** named automatically using the same logic as
5728** PRAGMA lock_proxy_file=":auto:"
5729**
5730** SQLITE_PROXY_DEBUG
5731**
5732** Enables the logging of error messages during host id file
5733** retrieval and creation
5734**
drh715ff302008-12-03 22:32:44 +00005735** LOCKPROXYDIR
5736**
5737** Overrides the default directory used for lock proxy files that
5738** are named automatically via the ":auto:" setting
5739**
5740** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5741**
5742** Permissions to use when creating a directory for storing the
5743** lock proxy files, only used when LOCKPROXYDIR is not set.
5744**
5745**
5746** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5747** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5748** force proxy locking to be used for every database file opened, and 0
5749** will force automatic proxy locking to be disabled for all database
5750** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5751** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5752*/
5753
5754/*
5755** Proxy locking is only available on MacOSX
5756*/
drhd2cb50b2009-01-09 21:41:17 +00005757#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005758
drh715ff302008-12-03 22:32:44 +00005759/*
5760** The proxyLockingContext has the path and file structures for the remote
5761** and local proxy files in it
5762*/
5763typedef struct proxyLockingContext proxyLockingContext;
5764struct proxyLockingContext {
5765 unixFile *conchFile; /* Open conch file */
5766 char *conchFilePath; /* Name of the conch file */
5767 unixFile *lockProxy; /* Open proxy lock file */
5768 char *lockProxyPath; /* Name of the proxy lock file */
5769 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005770 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005771 void *oldLockingContext; /* Original lockingcontext to restore on close */
5772 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5773};
5774
drh7ed97b92010-01-20 13:07:21 +00005775/*
5776** The proxy lock file path for the database at dbPath is written into lPath,
5777** which must point to valid, writable memory large enough for a maxLen length
5778** file path.
drh715ff302008-12-03 22:32:44 +00005779*/
drh715ff302008-12-03 22:32:44 +00005780static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5781 int len;
5782 int dbLen;
5783 int i;
5784
5785#ifdef LOCKPROXYDIR
5786 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5787#else
5788# ifdef _CS_DARWIN_USER_TEMP_DIR
5789 {
drh7ed97b92010-01-20 13:07:21 +00005790 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005791 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5792 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005793 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005794 }
drh7ed97b92010-01-20 13:07:21 +00005795 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005796 }
5797# else
5798 len = strlcpy(lPath, "/tmp/", maxLen);
5799# endif
5800#endif
5801
5802 if( lPath[len-1]!='/' ){
5803 len = strlcat(lPath, "/", maxLen);
5804 }
5805
5806 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005807 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005808 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005809 char c = dbPath[i];
5810 lPath[i+len] = (c=='/')?'_':c;
5811 }
5812 lPath[i+len]='\0';
5813 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005814 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005815 return SQLITE_OK;
5816}
5817
drh7ed97b92010-01-20 13:07:21 +00005818/*
5819 ** Creates the lock file and any missing directories in lockPath
5820 */
5821static int proxyCreateLockPath(const char *lockPath){
5822 int i, len;
5823 char buf[MAXPATHLEN];
5824 int start = 0;
5825
5826 assert(lockPath!=NULL);
5827 /* try to create all the intermediate directories */
5828 len = (int)strlen(lockPath);
5829 buf[0] = lockPath[0];
5830 for( i=1; i<len; i++ ){
5831 if( lockPath[i] == '/' && (i - start > 0) ){
5832 /* only mkdir if leaf dir != "." or "/" or ".." */
5833 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5834 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5835 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005836 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005837 int err=errno;
5838 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005839 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005840 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005841 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005842 return err;
5843 }
5844 }
5845 }
5846 start=i+1;
5847 }
5848 buf[i] = lockPath[i];
5849 }
drh308c2a52010-05-14 11:30:18 +00005850 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005851 return 0;
5852}
5853
drh715ff302008-12-03 22:32:44 +00005854/*
5855** Create a new VFS file descriptor (stored in memory obtained from
5856** sqlite3_malloc) and open the file named "path" in the file descriptor.
5857**
5858** The caller is responsible not only for closing the file descriptor
5859** but also for freeing the memory associated with the file descriptor.
5860*/
drh7ed97b92010-01-20 13:07:21 +00005861static int proxyCreateUnixFile(
5862 const char *path, /* path for the new unixFile */
5863 unixFile **ppFile, /* unixFile created and returned by ref */
5864 int islockfile /* if non zero missing dirs will be created */
5865) {
5866 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005867 unixFile *pNew;
5868 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005869 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005870 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005871 int terrno = 0;
5872 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005873
drh7ed97b92010-01-20 13:07:21 +00005874 /* 1. first try to open/create the file
5875 ** 2. if that fails, and this is a lock file (not-conch), try creating
5876 ** the parent directories and then try again.
5877 ** 3. if that fails, try to open the file read-only
5878 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5879 */
5880 pUnused = findReusableFd(path, openFlags);
5881 if( pUnused ){
5882 fd = pUnused->fd;
5883 }else{
5884 pUnused = sqlite3_malloc(sizeof(*pUnused));
5885 if( !pUnused ){
5886 return SQLITE_NOMEM;
5887 }
5888 }
5889 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00005890 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005891 terrno = errno;
5892 if( fd<0 && errno==ENOENT && islockfile ){
5893 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00005894 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005895 }
5896 }
5897 }
5898 if( fd<0 ){
5899 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00005900 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005901 terrno = errno;
5902 }
5903 if( fd<0 ){
5904 if( islockfile ){
5905 return SQLITE_BUSY;
5906 }
5907 switch (terrno) {
5908 case EACCES:
5909 return SQLITE_PERM;
5910 case EIO:
5911 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5912 default:
drh9978c972010-02-23 17:36:32 +00005913 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005914 }
5915 }
5916
5917 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5918 if( pNew==NULL ){
5919 rc = SQLITE_NOMEM;
5920 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005921 }
5922 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005923 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005924 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005925 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005926 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005927 pUnused->fd = fd;
5928 pUnused->flags = openFlags;
5929 pNew->pUnused = pUnused;
5930
drhc02a43a2012-01-10 23:18:38 +00005931 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005932 if( rc==SQLITE_OK ){
5933 *ppFile = pNew;
5934 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005935 }
drh7ed97b92010-01-20 13:07:21 +00005936end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005937 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005938 sqlite3_free(pNew);
5939 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005940 return rc;
5941}
5942
drh7ed97b92010-01-20 13:07:21 +00005943#ifdef SQLITE_TEST
5944/* simulate multiple hosts by creating unique hostid file paths */
5945int sqlite3_hostid_num = 0;
5946#endif
5947
5948#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5949
drh0ab216a2010-07-02 17:10:40 +00005950/* Not always defined in the headers as it ought to be */
5951extern int gethostuuid(uuid_t id, const struct timespec *wait);
5952
drh7ed97b92010-01-20 13:07:21 +00005953/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5954** bytes of writable memory.
5955*/
5956static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005957 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5958 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005959#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5960 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005961 {
5962 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5963 if( gethostuuid(pHostID, &timeout) ){
5964 int err = errno;
5965 if( pError ){
5966 *pError = err;
5967 }
5968 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005969 }
drh7ed97b92010-01-20 13:07:21 +00005970 }
drh3d4435b2011-08-26 20:55:50 +00005971#else
5972 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005973#endif
drh7ed97b92010-01-20 13:07:21 +00005974#ifdef SQLITE_TEST
5975 /* simulate multiple hosts by creating unique hostid file paths */
5976 if( sqlite3_hostid_num != 0){
5977 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5978 }
5979#endif
5980
5981 return SQLITE_OK;
5982}
5983
5984/* The conch file contains the header, host id and lock file path
5985 */
5986#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5987#define PROXY_HEADERLEN 1 /* conch file header length */
5988#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5989#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5990
5991/*
5992** Takes an open conch file, copies the contents to a new path and then moves
5993** it back. The newly created file's file descriptor is assigned to the
5994** conch file structure and finally the original conch file descriptor is
5995** closed. Returns zero if successful.
5996*/
5997static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5998 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5999 unixFile *conchFile = pCtx->conchFile;
6000 char tPath[MAXPATHLEN];
6001 char buf[PROXY_MAXCONCHLEN];
6002 char *cPath = pCtx->conchFilePath;
6003 size_t readLen = 0;
6004 size_t pathLen = 0;
6005 char errmsg[64] = "";
6006 int fd = -1;
6007 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006008 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006009
6010 /* create a new path by replace the trailing '-conch' with '-break' */
6011 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6012 if( pathLen>MAXPATHLEN || pathLen<6 ||
6013 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006014 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006015 goto end_breaklock;
6016 }
6017 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006018 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006019 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006020 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006021 goto end_breaklock;
6022 }
6023 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006024 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006025 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006026 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006027 goto end_breaklock;
6028 }
drhe562be52011-03-02 18:01:10 +00006029 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006030 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006031 goto end_breaklock;
6032 }
6033 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006034 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006035 goto end_breaklock;
6036 }
6037 rc = 0;
6038 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006039 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006040 conchFile->h = fd;
6041 conchFile->openFlags = O_RDWR | O_CREAT;
6042
6043end_breaklock:
6044 if( rc ){
6045 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006046 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006047 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006048 }
6049 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6050 }
6051 return rc;
6052}
6053
6054/* Take the requested lock on the conch file and break a stale lock if the
6055** host id matches.
6056*/
6057static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6058 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6059 unixFile *conchFile = pCtx->conchFile;
6060 int rc = SQLITE_OK;
6061 int nTries = 0;
6062 struct timespec conchModTime;
6063
drh3d4435b2011-08-26 20:55:50 +00006064 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006065 do {
6066 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6067 nTries ++;
6068 if( rc==SQLITE_BUSY ){
6069 /* If the lock failed (busy):
6070 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6071 * 2nd try: fail if the mod time changed or host id is different, wait
6072 * 10 sec and try again
6073 * 3rd try: break the lock unless the mod time has changed.
6074 */
6075 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006076 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006077 pFile->lastErrno = errno;
6078 return SQLITE_IOERR_LOCK;
6079 }
6080
6081 if( nTries==1 ){
6082 conchModTime = buf.st_mtimespec;
6083 usleep(500000); /* wait 0.5 sec and try the lock again*/
6084 continue;
6085 }
6086
6087 assert( nTries>1 );
6088 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6089 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6090 return SQLITE_BUSY;
6091 }
6092
6093 if( nTries==2 ){
6094 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006095 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006096 if( len<0 ){
6097 pFile->lastErrno = errno;
6098 return SQLITE_IOERR_LOCK;
6099 }
6100 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6101 /* don't break the lock if the host id doesn't match */
6102 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6103 return SQLITE_BUSY;
6104 }
6105 }else{
6106 /* don't break the lock on short read or a version mismatch */
6107 return SQLITE_BUSY;
6108 }
6109 usleep(10000000); /* wait 10 sec and try the lock again */
6110 continue;
6111 }
6112
6113 assert( nTries==3 );
6114 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6115 rc = SQLITE_OK;
6116 if( lockType==EXCLUSIVE_LOCK ){
6117 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6118 }
6119 if( !rc ){
6120 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6121 }
6122 }
6123 }
6124 } while( rc==SQLITE_BUSY && nTries<3 );
6125
6126 return rc;
6127}
6128
6129/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006130** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6131** lockPath means that the lockPath in the conch file will be used if the
6132** host IDs match, or a new lock path will be generated automatically
6133** and written to the conch file.
6134*/
6135static int proxyTakeConch(unixFile *pFile){
6136 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6137
drh7ed97b92010-01-20 13:07:21 +00006138 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006139 return SQLITE_OK;
6140 }else{
6141 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006142 uuid_t myHostID;
6143 int pError = 0;
6144 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006145 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006146 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006147 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006148 int createConch = 0;
6149 int hostIdMatch = 0;
6150 int readLen = 0;
6151 int tryOldLockPath = 0;
6152 int forceNewLockPath = 0;
6153
drh308c2a52010-05-14 11:30:18 +00006154 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6155 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006156
drh7ed97b92010-01-20 13:07:21 +00006157 rc = proxyGetHostID(myHostID, &pError);
6158 if( (rc&0xff)==SQLITE_IOERR ){
6159 pFile->lastErrno = pError;
6160 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006161 }
drh7ed97b92010-01-20 13:07:21 +00006162 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006163 if( rc!=SQLITE_OK ){
6164 goto end_takeconch;
6165 }
drh7ed97b92010-01-20 13:07:21 +00006166 /* read the existing conch file */
6167 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6168 if( readLen<0 ){
6169 /* I/O error: lastErrno set by seekAndRead */
6170 pFile->lastErrno = conchFile->lastErrno;
6171 rc = SQLITE_IOERR_READ;
6172 goto end_takeconch;
6173 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6174 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6175 /* a short read or version format mismatch means we need to create a new
6176 ** conch file.
6177 */
6178 createConch = 1;
6179 }
6180 /* if the host id matches and the lock path already exists in the conch
6181 ** we'll try to use the path there, if we can't open that path, we'll
6182 ** retry with a new auto-generated path
6183 */
6184 do { /* in case we need to try again for an :auto: named lock file */
6185
6186 if( !createConch && !forceNewLockPath ){
6187 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6188 PROXY_HOSTIDLEN);
6189 /* if the conch has data compare the contents */
6190 if( !pCtx->lockProxyPath ){
6191 /* for auto-named local lock file, just check the host ID and we'll
6192 ** use the local lock file path that's already in there
6193 */
6194 if( hostIdMatch ){
6195 size_t pathLen = (readLen - PROXY_PATHINDEX);
6196
6197 if( pathLen>=MAXPATHLEN ){
6198 pathLen=MAXPATHLEN-1;
6199 }
6200 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6201 lockPath[pathLen] = 0;
6202 tempLockPath = lockPath;
6203 tryOldLockPath = 1;
6204 /* create a copy of the lock path if the conch is taken */
6205 goto end_takeconch;
6206 }
6207 }else if( hostIdMatch
6208 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6209 readLen-PROXY_PATHINDEX)
6210 ){
6211 /* conch host and lock path match */
6212 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006213 }
drh7ed97b92010-01-20 13:07:21 +00006214 }
6215
6216 /* if the conch isn't writable and doesn't match, we can't take it */
6217 if( (conchFile->openFlags&O_RDWR) == 0 ){
6218 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006219 goto end_takeconch;
6220 }
drh7ed97b92010-01-20 13:07:21 +00006221
6222 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006223 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006224 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6225 tempLockPath = lockPath;
6226 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006227 }
drh7ed97b92010-01-20 13:07:21 +00006228
6229 /* update conch with host and path (this will fail if other process
6230 ** has a shared lock already), if the host id matches, use the big
6231 ** stick.
drh715ff302008-12-03 22:32:44 +00006232 */
drh7ed97b92010-01-20 13:07:21 +00006233 futimes(conchFile->h, NULL);
6234 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006235 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006236 /* We are trying for an exclusive lock but another thread in this
6237 ** same process is still holding a shared lock. */
6238 rc = SQLITE_BUSY;
6239 } else {
6240 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006241 }
drh715ff302008-12-03 22:32:44 +00006242 }else{
drh7ed97b92010-01-20 13:07:21 +00006243 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006244 }
drh7ed97b92010-01-20 13:07:21 +00006245 if( rc==SQLITE_OK ){
6246 char writeBuffer[PROXY_MAXCONCHLEN];
6247 int writeSize = 0;
6248
6249 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6250 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6251 if( pCtx->lockProxyPath!=NULL ){
6252 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6253 }else{
6254 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6255 }
6256 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006257 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006258 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6259 fsync(conchFile->h);
6260 /* If we created a new conch file (not just updated the contents of a
6261 ** valid conch file), try to match the permissions of the database
6262 */
6263 if( rc==SQLITE_OK && createConch ){
6264 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006265 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006266 if( err==0 ){
6267 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6268 S_IROTH|S_IWOTH);
6269 /* try to match the database file R/W permissions, ignore failure */
6270#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006271 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006272#else
drhff812312011-02-23 13:33:46 +00006273 do{
drhe562be52011-03-02 18:01:10 +00006274 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006275 }while( rc==(-1) && errno==EINTR );
6276 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006277 int code = errno;
6278 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6279 cmode, code, strerror(code));
6280 } else {
6281 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6282 }
6283 }else{
6284 int code = errno;
6285 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6286 err, code, strerror(code));
6287#endif
6288 }
drh715ff302008-12-03 22:32:44 +00006289 }
6290 }
drh7ed97b92010-01-20 13:07:21 +00006291 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6292
6293 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006294 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006295 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006296 int fd;
drh7ed97b92010-01-20 13:07:21 +00006297 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006298 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006299 }
6300 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006301 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006302 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006303 if( fd>=0 ){
6304 pFile->h = fd;
6305 }else{
drh9978c972010-02-23 17:36:32 +00006306 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006307 during locking */
6308 }
6309 }
6310 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6311 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6312 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6313 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6314 /* we couldn't create the proxy lock file with the old lock file path
6315 ** so try again via auto-naming
6316 */
6317 forceNewLockPath = 1;
6318 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006319 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006320 }
6321 }
6322 if( rc==SQLITE_OK ){
6323 /* Need to make a copy of path if we extracted the value
6324 ** from the conch file or the path was allocated on the stack
6325 */
6326 if( tempLockPath ){
6327 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6328 if( !pCtx->lockProxyPath ){
6329 rc = SQLITE_NOMEM;
6330 }
6331 }
6332 }
6333 if( rc==SQLITE_OK ){
6334 pCtx->conchHeld = 1;
6335
6336 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6337 afpLockingContext *afpCtx;
6338 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6339 afpCtx->dbPath = pCtx->lockProxyPath;
6340 }
6341 } else {
6342 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6343 }
drh308c2a52010-05-14 11:30:18 +00006344 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6345 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006346 return rc;
drh308c2a52010-05-14 11:30:18 +00006347 } while (1); /* in case we need to retry the :auto: lock file -
6348 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006349 }
6350}
6351
6352/*
6353** If pFile holds a lock on a conch file, then release that lock.
6354*/
6355static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006356 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006357 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6358 unixFile *conchFile; /* Name of the conch file */
6359
6360 pCtx = (proxyLockingContext *)pFile->lockingContext;
6361 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006362 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006363 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006364 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006365 if( pCtx->conchHeld>0 ){
6366 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6367 }
drh715ff302008-12-03 22:32:44 +00006368 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006369 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6370 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006371 return rc;
6372}
6373
6374/*
6375** Given the name of a database file, compute the name of its conch file.
6376** Store the conch filename in memory obtained from sqlite3_malloc().
6377** Make *pConchPath point to the new name. Return SQLITE_OK on success
6378** or SQLITE_NOMEM if unable to obtain memory.
6379**
6380** The caller is responsible for ensuring that the allocated memory
6381** space is eventually freed.
6382**
6383** *pConchPath is set to NULL if a memory allocation error occurs.
6384*/
6385static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6386 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006387 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006388 char *conchPath; /* buffer in which to construct conch name */
6389
6390 /* Allocate space for the conch filename and initialize the name to
6391 ** the name of the original database file. */
6392 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6393 if( conchPath==0 ){
6394 return SQLITE_NOMEM;
6395 }
6396 memcpy(conchPath, dbPath, len+1);
6397
6398 /* now insert a "." before the last / character */
6399 for( i=(len-1); i>=0; i-- ){
6400 if( conchPath[i]=='/' ){
6401 i++;
6402 break;
6403 }
6404 }
6405 conchPath[i]='.';
6406 while ( i<len ){
6407 conchPath[i+1]=dbPath[i];
6408 i++;
6409 }
6410
6411 /* append the "-conch" suffix to the file */
6412 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006413 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006414
6415 return SQLITE_OK;
6416}
6417
6418
6419/* Takes a fully configured proxy locking-style unix file and switches
6420** the local lock file path
6421*/
6422static int switchLockProxyPath(unixFile *pFile, const char *path) {
6423 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6424 char *oldPath = pCtx->lockProxyPath;
6425 int rc = SQLITE_OK;
6426
drh308c2a52010-05-14 11:30:18 +00006427 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006428 return SQLITE_BUSY;
6429 }
6430
6431 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6432 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6433 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6434 return SQLITE_OK;
6435 }else{
6436 unixFile *lockProxy = pCtx->lockProxy;
6437 pCtx->lockProxy=NULL;
6438 pCtx->conchHeld = 0;
6439 if( lockProxy!=NULL ){
6440 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6441 if( rc ) return rc;
6442 sqlite3_free(lockProxy);
6443 }
6444 sqlite3_free(oldPath);
6445 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6446 }
6447
6448 return rc;
6449}
6450
6451/*
6452** pFile is a file that has been opened by a prior xOpen call. dbPath
6453** is a string buffer at least MAXPATHLEN+1 characters in size.
6454**
6455** This routine find the filename associated with pFile and writes it
6456** int dbPath.
6457*/
6458static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006459#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006460 if( pFile->pMethod == &afpIoMethods ){
6461 /* afp style keeps a reference to the db path in the filePath field
6462 ** of the struct */
drhea678832008-12-10 19:26:22 +00006463 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006464 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6465 } else
drh715ff302008-12-03 22:32:44 +00006466#endif
6467 if( pFile->pMethod == &dotlockIoMethods ){
6468 /* dot lock style uses the locking context to store the dot lock
6469 ** file path */
6470 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6471 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6472 }else{
6473 /* all other styles use the locking context to store the db file path */
6474 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006475 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006476 }
6477 return SQLITE_OK;
6478}
6479
6480/*
6481** Takes an already filled in unix file and alters it so all file locking
6482** will be performed on the local proxy lock file. The following fields
6483** are preserved in the locking context so that they can be restored and
6484** the unix structure properly cleaned up at close time:
6485** ->lockingContext
6486** ->pMethod
6487*/
6488static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6489 proxyLockingContext *pCtx;
6490 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6491 char *lockPath=NULL;
6492 int rc = SQLITE_OK;
6493
drh308c2a52010-05-14 11:30:18 +00006494 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006495 return SQLITE_BUSY;
6496 }
6497 proxyGetDbPathForUnixFile(pFile, dbPath);
6498 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6499 lockPath=NULL;
6500 }else{
6501 lockPath=(char *)path;
6502 }
6503
drh308c2a52010-05-14 11:30:18 +00006504 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6505 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006506
6507 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6508 if( pCtx==0 ){
6509 return SQLITE_NOMEM;
6510 }
6511 memset(pCtx, 0, sizeof(*pCtx));
6512
6513 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6514 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006515 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6516 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6517 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6518 ** (c) the file system is read-only, then enable no-locking access.
6519 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6520 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6521 */
6522 struct statfs fsInfo;
6523 struct stat conchInfo;
6524 int goLockless = 0;
6525
drh99ab3b12011-03-02 15:09:07 +00006526 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006527 int err = errno;
6528 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6529 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6530 }
6531 }
6532 if( goLockless ){
6533 pCtx->conchHeld = -1; /* read only FS/ lockless */
6534 rc = SQLITE_OK;
6535 }
6536 }
drh715ff302008-12-03 22:32:44 +00006537 }
6538 if( rc==SQLITE_OK && lockPath ){
6539 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6540 }
6541
6542 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006543 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6544 if( pCtx->dbPath==NULL ){
6545 rc = SQLITE_NOMEM;
6546 }
6547 }
6548 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006549 /* all memory is allocated, proxys are created and assigned,
6550 ** switch the locking context and pMethod then return.
6551 */
drh715ff302008-12-03 22:32:44 +00006552 pCtx->oldLockingContext = pFile->lockingContext;
6553 pFile->lockingContext = pCtx;
6554 pCtx->pOldMethod = pFile->pMethod;
6555 pFile->pMethod = &proxyIoMethods;
6556 }else{
6557 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006558 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006559 sqlite3_free(pCtx->conchFile);
6560 }
drhd56b1212010-08-11 06:14:15 +00006561 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006562 sqlite3_free(pCtx->conchFilePath);
6563 sqlite3_free(pCtx);
6564 }
drh308c2a52010-05-14 11:30:18 +00006565 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6566 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006567 return rc;
6568}
6569
6570
6571/*
6572** This routine handles sqlite3_file_control() calls that are specific
6573** to proxy locking.
6574*/
6575static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6576 switch( op ){
6577 case SQLITE_GET_LOCKPROXYFILE: {
6578 unixFile *pFile = (unixFile*)id;
6579 if( pFile->pMethod == &proxyIoMethods ){
6580 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6581 proxyTakeConch(pFile);
6582 if( pCtx->lockProxyPath ){
6583 *(const char **)pArg = pCtx->lockProxyPath;
6584 }else{
6585 *(const char **)pArg = ":auto: (not held)";
6586 }
6587 } else {
6588 *(const char **)pArg = NULL;
6589 }
6590 return SQLITE_OK;
6591 }
6592 case SQLITE_SET_LOCKPROXYFILE: {
6593 unixFile *pFile = (unixFile*)id;
6594 int rc = SQLITE_OK;
6595 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6596 if( pArg==NULL || (const char *)pArg==0 ){
6597 if( isProxyStyle ){
6598 /* turn off proxy locking - not supported */
6599 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6600 }else{
6601 /* turn off proxy locking - already off - NOOP */
6602 rc = SQLITE_OK;
6603 }
6604 }else{
6605 const char *proxyPath = (const char *)pArg;
6606 if( isProxyStyle ){
6607 proxyLockingContext *pCtx =
6608 (proxyLockingContext*)pFile->lockingContext;
6609 if( !strcmp(pArg, ":auto:")
6610 || (pCtx->lockProxyPath &&
6611 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6612 ){
6613 rc = SQLITE_OK;
6614 }else{
6615 rc = switchLockProxyPath(pFile, proxyPath);
6616 }
6617 }else{
6618 /* turn on proxy file locking */
6619 rc = proxyTransformUnixFile(pFile, proxyPath);
6620 }
6621 }
6622 return rc;
6623 }
6624 default: {
6625 assert( 0 ); /* The call assures that only valid opcodes are sent */
6626 }
6627 }
6628 /*NOTREACHED*/
6629 return SQLITE_ERROR;
6630}
6631
6632/*
6633** Within this division (the proxying locking implementation) the procedures
6634** above this point are all utilities. The lock-related methods of the
6635** proxy-locking sqlite3_io_method object follow.
6636*/
6637
6638
6639/*
6640** This routine checks if there is a RESERVED lock held on the specified
6641** file by this or any other process. If such a lock is held, set *pResOut
6642** to a non-zero value otherwise *pResOut is set to zero. The return value
6643** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6644*/
6645static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6646 unixFile *pFile = (unixFile*)id;
6647 int rc = proxyTakeConch(pFile);
6648 if( rc==SQLITE_OK ){
6649 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006650 if( pCtx->conchHeld>0 ){
6651 unixFile *proxy = pCtx->lockProxy;
6652 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6653 }else{ /* conchHeld < 0 is lockless */
6654 pResOut=0;
6655 }
drh715ff302008-12-03 22:32:44 +00006656 }
6657 return rc;
6658}
6659
6660/*
drh308c2a52010-05-14 11:30:18 +00006661** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006662** of the following:
6663**
6664** (1) SHARED_LOCK
6665** (2) RESERVED_LOCK
6666** (3) PENDING_LOCK
6667** (4) EXCLUSIVE_LOCK
6668**
6669** Sometimes when requesting one lock state, additional lock states
6670** are inserted in between. The locking might fail on one of the later
6671** transitions leaving the lock state different from what it started but
6672** still short of its goal. The following chart shows the allowed
6673** transitions and the inserted intermediate states:
6674**
6675** UNLOCKED -> SHARED
6676** SHARED -> RESERVED
6677** SHARED -> (PENDING) -> EXCLUSIVE
6678** RESERVED -> (PENDING) -> EXCLUSIVE
6679** PENDING -> EXCLUSIVE
6680**
6681** This routine will only increase a lock. Use the sqlite3OsUnlock()
6682** routine to lower a locking level.
6683*/
drh308c2a52010-05-14 11:30:18 +00006684static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006685 unixFile *pFile = (unixFile*)id;
6686 int rc = proxyTakeConch(pFile);
6687 if( rc==SQLITE_OK ){
6688 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006689 if( pCtx->conchHeld>0 ){
6690 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006691 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6692 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006693 }else{
6694 /* conchHeld < 0 is lockless */
6695 }
drh715ff302008-12-03 22:32:44 +00006696 }
6697 return rc;
6698}
6699
6700
6701/*
drh308c2a52010-05-14 11:30:18 +00006702** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006703** must be either NO_LOCK or SHARED_LOCK.
6704**
6705** If the locking level of the file descriptor is already at or below
6706** the requested locking level, this routine is a no-op.
6707*/
drh308c2a52010-05-14 11:30:18 +00006708static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006709 unixFile *pFile = (unixFile*)id;
6710 int rc = proxyTakeConch(pFile);
6711 if( rc==SQLITE_OK ){
6712 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006713 if( pCtx->conchHeld>0 ){
6714 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006715 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6716 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006717 }else{
6718 /* conchHeld < 0 is lockless */
6719 }
drh715ff302008-12-03 22:32:44 +00006720 }
6721 return rc;
6722}
6723
6724/*
6725** Close a file that uses proxy locks.
6726*/
6727static int proxyClose(sqlite3_file *id) {
6728 if( id ){
6729 unixFile *pFile = (unixFile*)id;
6730 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6731 unixFile *lockProxy = pCtx->lockProxy;
6732 unixFile *conchFile = pCtx->conchFile;
6733 int rc = SQLITE_OK;
6734
6735 if( lockProxy ){
6736 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6737 if( rc ) return rc;
6738 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6739 if( rc ) return rc;
6740 sqlite3_free(lockProxy);
6741 pCtx->lockProxy = 0;
6742 }
6743 if( conchFile ){
6744 if( pCtx->conchHeld ){
6745 rc = proxyReleaseConch(pFile);
6746 if( rc ) return rc;
6747 }
6748 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6749 if( rc ) return rc;
6750 sqlite3_free(conchFile);
6751 }
drhd56b1212010-08-11 06:14:15 +00006752 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006753 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006754 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006755 /* restore the original locking context and pMethod then close it */
6756 pFile->lockingContext = pCtx->oldLockingContext;
6757 pFile->pMethod = pCtx->pOldMethod;
6758 sqlite3_free(pCtx);
6759 return pFile->pMethod->xClose(id);
6760 }
6761 return SQLITE_OK;
6762}
6763
6764
6765
drhd2cb50b2009-01-09 21:41:17 +00006766#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006767/*
6768** The proxy locking style is intended for use with AFP filesystems.
6769** And since AFP is only supported on MacOSX, the proxy locking is also
6770** restricted to MacOSX.
6771**
6772**
6773******************* End of the proxy lock implementation **********************
6774******************************************************************************/
6775
drh734c9862008-11-28 15:37:20 +00006776/*
danielk1977e339d652008-06-28 11:23:00 +00006777** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006778**
6779** This routine registers all VFS implementations for unix-like operating
6780** systems. This routine, and the sqlite3_os_end() routine that follows,
6781** should be the only routines in this file that are visible from other
6782** files.
drh6b9d6dd2008-12-03 19:34:47 +00006783**
6784** This routine is called once during SQLite initialization and by a
6785** single thread. The memory allocation and mutex subsystems have not
6786** necessarily been initialized when this routine is called, and so they
6787** should not be used.
drh153c62c2007-08-24 03:51:33 +00006788*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006789int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006790 /*
6791 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006792 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6793 ** to the "finder" function. (pAppData is a pointer to a pointer because
6794 ** silly C90 rules prohibit a void* from being cast to a function pointer
6795 ** and so we have to go through the intermediate pointer to avoid problems
6796 ** when compiling with -pedantic-errors on GCC.)
6797 **
6798 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006799 ** finder-function. The finder-function returns a pointer to the
6800 ** sqlite_io_methods object that implements the desired locking
6801 ** behaviors. See the division above that contains the IOMETHODS
6802 ** macro for addition information on finder-functions.
6803 **
6804 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6805 ** object. But the "autolockIoFinder" available on MacOSX does a little
6806 ** more than that; it looks at the filesystem type that hosts the
6807 ** database file and tries to choose an locking method appropriate for
6808 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006809 */
drh7708e972008-11-29 00:56:52 +00006810 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006811 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006812 sizeof(unixFile), /* szOsFile */ \
6813 MAX_PATHNAME, /* mxPathname */ \
6814 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006815 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006816 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006817 unixOpen, /* xOpen */ \
6818 unixDelete, /* xDelete */ \
6819 unixAccess, /* xAccess */ \
6820 unixFullPathname, /* xFullPathname */ \
6821 unixDlOpen, /* xDlOpen */ \
6822 unixDlError, /* xDlError */ \
6823 unixDlSym, /* xDlSym */ \
6824 unixDlClose, /* xDlClose */ \
6825 unixRandomness, /* xRandomness */ \
6826 unixSleep, /* xSleep */ \
6827 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006828 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006829 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006830 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006831 unixGetSystemCall, /* xGetSystemCall */ \
6832 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006833 }
6834
drh6b9d6dd2008-12-03 19:34:47 +00006835 /*
6836 ** All default VFSes for unix are contained in the following array.
6837 **
6838 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6839 ** by the SQLite core when the VFS is registered. So the following
6840 ** array cannot be const.
6841 */
danielk1977e339d652008-06-28 11:23:00 +00006842 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006843#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006844 UNIXVFS("unix", autolockIoFinder ),
6845#else
6846 UNIXVFS("unix", posixIoFinder ),
6847#endif
6848 UNIXVFS("unix-none", nolockIoFinder ),
6849 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006850 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006851#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006852 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006853#endif
6854#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006855 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006856#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006857 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006858#endif
chw78a13182009-04-07 05:35:03 +00006859#endif
drhd2cb50b2009-01-09 21:41:17 +00006860#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006861 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006862 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006863 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006864#endif
drh153c62c2007-08-24 03:51:33 +00006865 };
drh6b9d6dd2008-12-03 19:34:47 +00006866 unsigned int i; /* Loop counter */
6867
drh2aa5a002011-04-13 13:42:25 +00006868 /* Double-check that the aSyscall[] array has been constructed
6869 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8c815d12012-02-13 20:16:37 +00006870 assert( ArraySize(aSyscall)==22 );
drh2aa5a002011-04-13 13:42:25 +00006871
drh6b9d6dd2008-12-03 19:34:47 +00006872 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006873 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006874 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006875 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006876 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006877}
danielk1977e339d652008-06-28 11:23:00 +00006878
6879/*
drh6b9d6dd2008-12-03 19:34:47 +00006880** Shutdown the operating system interface.
6881**
6882** Some operating systems might need to do some cleanup in this routine,
6883** to release dynamically allocated objects. But not on unix.
6884** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006885*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006886int sqlite3_os_end(void){
6887 return SQLITE_OK;
6888}
drhdce8bdb2007-08-16 13:01:44 +00006889
danielk197729bafea2008-06-26 10:41:19 +00006890#endif /* SQLITE_OS_UNIX */