blob: 48613b420a845d755cba1324ccabaac9899ecc3e [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000209 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000210 int lastErrno; /* The unix errno from last I/O error */
211 void *lockingContext; /* Locking style specific state */
212 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
drh77197112011-03-15 19:08:48 +0000250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
drha7e61d82011-03-12 17:02:57 +0000251
252/*
drh198bf392006-01-06 21:52:49 +0000253** Include code that is common to all os_*.c files
254*/
255#include "os_common.h"
256
257/*
drh0ccebe72005-06-07 22:22:50 +0000258** Define various macros that are missing from some systems.
259*/
drhbbd42a62004-05-22 17:41:58 +0000260#ifndef O_LARGEFILE
261# define O_LARGEFILE 0
262#endif
263#ifdef SQLITE_DISABLE_LFS
264# undef O_LARGEFILE
265# define O_LARGEFILE 0
266#endif
267#ifndef O_NOFOLLOW
268# define O_NOFOLLOW 0
269#endif
270#ifndef O_BINARY
271# define O_BINARY 0
272#endif
273
274/*
drh2b4b5962005-06-15 17:47:55 +0000275** The threadid macro resolves to the thread-id or to 0. Used for
276** testing and debugging only.
277*/
drhd677b3d2007-08-20 22:48:41 +0000278#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000279#define threadid pthread_self()
280#else
281#define threadid 0
282#endif
283
drh99ab3b12011-03-02 15:09:07 +0000284/*
285** Many system calls are accessed through pointer-to-functions so that
286** they may be overridden at runtime to facilitate fault injection during
287** testing and sandboxing. The following array holds the names and pointers
288** to all overrideable system calls.
289*/
290static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000291 const char *zName; /* Name of the sytem call */
292 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
293 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000294} aSyscall[] = {
drh58ad5802011-03-23 22:02:23 +0000295 { "open", (sqlite3_syscall_ptr)open, 0 },
drh99ab3b12011-03-02 15:09:07 +0000296#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
297
drh58ad5802011-03-23 22:02:23 +0000298 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000299#define osClose ((int(*)(int))aSyscall[1].pCurrent)
300
drh58ad5802011-03-23 22:02:23 +0000301 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000302#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
303
drh58ad5802011-03-23 22:02:23 +0000304 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000305#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
306
drh58ad5802011-03-23 22:02:23 +0000307 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000308#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
309
310/*
311** The DJGPP compiler environment looks mostly like Unix, but it
312** lacks the fcntl() system call. So redefine fcntl() to be something
313** that always succeeds. This means that locking does not occur under
314** DJGPP. But it is DOS - what did you expect?
315*/
316#ifdef __DJGPP__
317 { "fstat", 0, 0 },
318#define osFstat(a,b,c) 0
319#else
drh58ad5802011-03-23 22:02:23 +0000320 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000321#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
322#endif
323
drh58ad5802011-03-23 22:02:23 +0000324 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
326
drh58ad5802011-03-23 22:02:23 +0000327 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000328#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000329
drh58ad5802011-03-23 22:02:23 +0000330 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000331#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
332
drhd4a80312011-04-15 14:33:20 +0000333#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000334 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000335#else
drh58ad5802011-03-23 22:02:23 +0000336 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000337#endif
338#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
339
340#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000341 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000342#else
drh58ad5802011-03-23 22:02:23 +0000343 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000344#endif
345#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000348#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
349
drhd4a80312011-04-15 14:33:20 +0000350#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000351 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000352#else
drh58ad5802011-03-23 22:02:23 +0000353 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000354#endif
355#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
356 aSyscall[12].pCurrent)
357
358#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000359 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000360#else
drh58ad5802011-03-23 22:02:23 +0000361 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000362#endif
363#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
364 aSyscall[13].pCurrent)
365
drha6c47492011-04-11 18:35:09 +0000366#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000367 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000368#else
369 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000370#endif
drh2aa5a002011-04-13 13:42:25 +0000371#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000372
373#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000374 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000375#else
drh58ad5802011-03-23 22:02:23 +0000376 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000377#endif
dan0fd7d862011-03-29 10:04:23 +0000378#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000379
380}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000381
382/*
383** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000384** "unix" VFSes. Return SQLITE_OK opon successfully updating the
385** system call pointer, or SQLITE_NOTFOUND if there is no configurable
386** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000387*/
388static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000389 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
390 const char *zName, /* Name of system call to override */
391 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000392){
drh58ad5802011-03-23 22:02:23 +0000393 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000394 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000395
396 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000397 if( zName==0 ){
398 /* If no zName is given, restore all system calls to their default
399 ** settings and return NULL
400 */
dan51438a72011-04-02 17:00:47 +0000401 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000402 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
403 if( aSyscall[i].pDefault ){
404 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000405 }
406 }
407 }else{
408 /* If zName is specified, operate on only the one system call
409 ** specified.
410 */
411 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
412 if( strcmp(zName, aSyscall[i].zName)==0 ){
413 if( aSyscall[i].pDefault==0 ){
414 aSyscall[i].pDefault = aSyscall[i].pCurrent;
415 }
drh1df30962011-03-02 19:06:42 +0000416 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000417 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
418 aSyscall[i].pCurrent = pNewFunc;
419 break;
420 }
421 }
422 }
423 return rc;
424}
425
drh1df30962011-03-02 19:06:42 +0000426/*
427** Return the value of a system call. Return NULL if zName is not a
428** recognized system call name. NULL is also returned if the system call
429** is currently undefined.
430*/
drh58ad5802011-03-23 22:02:23 +0000431static sqlite3_syscall_ptr unixGetSystemCall(
432 sqlite3_vfs *pNotUsed,
433 const char *zName
434){
435 unsigned int i;
436
437 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000438 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
439 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
440 }
441 return 0;
442}
443
444/*
445** Return the name of the first system call after zName. If zName==NULL
446** then return the name of the first system call. Return NULL if zName
447** is the last system call or if zName is not the name of a valid
448** system call.
449*/
450static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000451 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000452
453 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000454 if( zName ){
455 for(i=0; i<ArraySize(aSyscall)-1; i++){
456 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000457 }
458 }
dan0fd7d862011-03-29 10:04:23 +0000459 for(i++; i<ArraySize(aSyscall); i++){
460 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000461 }
462 return 0;
463}
464
drhad4f1e52011-03-04 15:43:57 +0000465/*
466** Retry open() calls that fail due to EINTR
467*/
468static int robust_open(const char *z, int f, int m){
469 int rc;
470 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
471 return rc;
472}
danielk197713adf8a2004-06-03 16:08:41 +0000473
drh107886a2008-11-21 22:21:50 +0000474/*
dan9359c7b2009-08-21 08:29:10 +0000475** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000476** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000477** vxworksFileId objects used by this file, all of which may be
478** shared by multiple threads.
479**
480** Function unixMutexHeld() is used to assert() that the global mutex
481** is held when required. This function is only used as part of assert()
482** statements. e.g.
483**
484** unixEnterMutex()
485** assert( unixMutexHeld() );
486** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000487*/
488static void unixEnterMutex(void){
489 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
490}
491static void unixLeaveMutex(void){
492 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
493}
dan9359c7b2009-08-21 08:29:10 +0000494#ifdef SQLITE_DEBUG
495static int unixMutexHeld(void) {
496 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
497}
498#endif
drh107886a2008-11-21 22:21:50 +0000499
drh734c9862008-11-28 15:37:20 +0000500
501#ifdef SQLITE_DEBUG
502/*
503** Helper function for printing out trace information from debugging
504** binaries. This returns the string represetation of the supplied
505** integer lock-type.
506*/
drh308c2a52010-05-14 11:30:18 +0000507static const char *azFileLock(int eFileLock){
508 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000509 case NO_LOCK: return "NONE";
510 case SHARED_LOCK: return "SHARED";
511 case RESERVED_LOCK: return "RESERVED";
512 case PENDING_LOCK: return "PENDING";
513 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000514 }
515 return "ERROR";
516}
517#endif
518
519#ifdef SQLITE_LOCK_TRACE
520/*
521** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000522**
drh734c9862008-11-28 15:37:20 +0000523** This routine is used for troubleshooting locks on multithreaded
524** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
525** command-line option on the compiler. This code is normally
526** turned off.
527*/
528static int lockTrace(int fd, int op, struct flock *p){
529 char *zOpName, *zType;
530 int s;
531 int savedErrno;
532 if( op==F_GETLK ){
533 zOpName = "GETLK";
534 }else if( op==F_SETLK ){
535 zOpName = "SETLK";
536 }else{
drh99ab3b12011-03-02 15:09:07 +0000537 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000538 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
539 return s;
540 }
541 if( p->l_type==F_RDLCK ){
542 zType = "RDLCK";
543 }else if( p->l_type==F_WRLCK ){
544 zType = "WRLCK";
545 }else if( p->l_type==F_UNLCK ){
546 zType = "UNLCK";
547 }else{
548 assert( 0 );
549 }
550 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000551 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000552 savedErrno = errno;
553 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
554 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
555 (int)p->l_pid, s);
556 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
557 struct flock l2;
558 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000559 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000560 if( l2.l_type==F_RDLCK ){
561 zType = "RDLCK";
562 }else if( l2.l_type==F_WRLCK ){
563 zType = "WRLCK";
564 }else if( l2.l_type==F_UNLCK ){
565 zType = "UNLCK";
566 }else{
567 assert( 0 );
568 }
569 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
570 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
571 }
572 errno = savedErrno;
573 return s;
574}
drh99ab3b12011-03-02 15:09:07 +0000575#undef osFcntl
576#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000577#endif /* SQLITE_LOCK_TRACE */
578
drhff812312011-02-23 13:33:46 +0000579/*
580** Retry ftruncate() calls that fail due to EINTR
581*/
drhff812312011-02-23 13:33:46 +0000582static int robust_ftruncate(int h, sqlite3_int64 sz){
583 int rc;
drh99ab3b12011-03-02 15:09:07 +0000584 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000585 return rc;
586}
drh734c9862008-11-28 15:37:20 +0000587
588/*
589** This routine translates a standard POSIX errno code into something
590** useful to the clients of the sqlite3 functions. Specifically, it is
591** intended to translate a variety of "try again" errors into SQLITE_BUSY
592** and a variety of "please close the file descriptor NOW" errors into
593** SQLITE_IOERR
594**
595** Errors during initialization of locks, or file system support for locks,
596** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
597*/
598static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
599 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000600#if 0
601 /* At one point this code was not commented out. In theory, this branch
602 ** should never be hit, as this function should only be called after
603 ** a locking-related function (i.e. fcntl()) has returned non-zero with
604 ** the value of errno as the first argument. Since a system call has failed,
605 ** errno should be non-zero.
606 **
607 ** Despite this, if errno really is zero, we still don't want to return
608 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
609 ** propagated back to the caller. Commenting this branch out means errno==0
610 ** will be handled by the "default:" case below.
611 */
drh734c9862008-11-28 15:37:20 +0000612 case 0:
613 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000614#endif
615
drh734c9862008-11-28 15:37:20 +0000616 case EAGAIN:
617 case ETIMEDOUT:
618 case EBUSY:
619 case EINTR:
620 case ENOLCK:
621 /* random NFS retry error, unless during file system support
622 * introspection, in which it actually means what it says */
623 return SQLITE_BUSY;
624
625 case EACCES:
626 /* EACCES is like EAGAIN during locking operations, but not any other time*/
627 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
628 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
629 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
630 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
631 return SQLITE_BUSY;
632 }
633 /* else fall through */
634 case EPERM:
635 return SQLITE_PERM;
636
danea83bc62011-04-01 11:56:32 +0000637 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
638 ** this module never makes such a call. And the code in SQLite itself
639 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
640 ** this case is also commented out. If the system does set errno to EDEADLK,
641 ** the default SQLITE_IOERR_XXX code will be returned. */
642#if 0
drh734c9862008-11-28 15:37:20 +0000643 case EDEADLK:
644 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000645#endif
drh734c9862008-11-28 15:37:20 +0000646
647#if EOPNOTSUPP!=ENOTSUP
648 case EOPNOTSUPP:
649 /* something went terribly awry, unless during file system support
650 * introspection, in which it actually means what it says */
651#endif
652#ifdef ENOTSUP
653 case ENOTSUP:
654 /* invalid fd, unless during file system support introspection, in which
655 * it actually means what it says */
656#endif
657 case EIO:
658 case EBADF:
659 case EINVAL:
660 case ENOTCONN:
661 case ENODEV:
662 case ENXIO:
663 case ENOENT:
664 case ESTALE:
665 case ENOSYS:
666 /* these should force the client to close the file and reconnect */
667
668 default:
669 return sqliteIOErr;
670 }
671}
672
673
674
675/******************************************************************************
676****************** Begin Unique File ID Utility Used By VxWorks ***************
677**
678** On most versions of unix, we can get a unique ID for a file by concatenating
679** the device number and the inode number. But this does not work on VxWorks.
680** On VxWorks, a unique file id must be based on the canonical filename.
681**
682** A pointer to an instance of the following structure can be used as a
683** unique file ID in VxWorks. Each instance of this structure contains
684** a copy of the canonical filename. There is also a reference count.
685** The structure is reclaimed when the number of pointers to it drops to
686** zero.
687**
688** There are never very many files open at one time and lookups are not
689** a performance-critical path, so it is sufficient to put these
690** structures on a linked list.
691*/
692struct vxworksFileId {
693 struct vxworksFileId *pNext; /* Next in a list of them all */
694 int nRef; /* Number of references to this one */
695 int nName; /* Length of the zCanonicalName[] string */
696 char *zCanonicalName; /* Canonical filename */
697};
698
699#if OS_VXWORKS
700/*
drh9b35ea62008-11-29 02:20:26 +0000701** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000702** variable:
703*/
704static struct vxworksFileId *vxworksFileList = 0;
705
706/*
707** Simplify a filename into its canonical form
708** by making the following changes:
709**
710** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000711** * convert /./ into just /
712** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000713**
714** Changes are made in-place. Return the new name length.
715**
716** The original filename is in z[0..n-1]. Return the number of
717** characters in the simplified name.
718*/
719static int vxworksSimplifyName(char *z, int n){
720 int i, j;
721 while( n>1 && z[n-1]=='/' ){ n--; }
722 for(i=j=0; i<n; i++){
723 if( z[i]=='/' ){
724 if( z[i+1]=='/' ) continue;
725 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
726 i += 1;
727 continue;
728 }
729 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
730 while( j>0 && z[j-1]!='/' ){ j--; }
731 if( j>0 ){ j--; }
732 i += 2;
733 continue;
734 }
735 }
736 z[j++] = z[i];
737 }
738 z[j] = 0;
739 return j;
740}
741
742/*
743** Find a unique file ID for the given absolute pathname. Return
744** a pointer to the vxworksFileId object. This pointer is the unique
745** file ID.
746**
747** The nRef field of the vxworksFileId object is incremented before
748** the object is returned. A new vxworksFileId object is created
749** and added to the global list if necessary.
750**
751** If a memory allocation error occurs, return NULL.
752*/
753static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
754 struct vxworksFileId *pNew; /* search key and new file ID */
755 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
756 int n; /* Length of zAbsoluteName string */
757
758 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000759 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000760 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
761 if( pNew==0 ) return 0;
762 pNew->zCanonicalName = (char*)&pNew[1];
763 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
764 n = vxworksSimplifyName(pNew->zCanonicalName, n);
765
766 /* Search for an existing entry that matching the canonical name.
767 ** If found, increment the reference count and return a pointer to
768 ** the existing file ID.
769 */
770 unixEnterMutex();
771 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
772 if( pCandidate->nName==n
773 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
774 ){
775 sqlite3_free(pNew);
776 pCandidate->nRef++;
777 unixLeaveMutex();
778 return pCandidate;
779 }
780 }
781
782 /* No match was found. We will make a new file ID */
783 pNew->nRef = 1;
784 pNew->nName = n;
785 pNew->pNext = vxworksFileList;
786 vxworksFileList = pNew;
787 unixLeaveMutex();
788 return pNew;
789}
790
791/*
792** Decrement the reference count on a vxworksFileId object. Free
793** the object when the reference count reaches zero.
794*/
795static void vxworksReleaseFileId(struct vxworksFileId *pId){
796 unixEnterMutex();
797 assert( pId->nRef>0 );
798 pId->nRef--;
799 if( pId->nRef==0 ){
800 struct vxworksFileId **pp;
801 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
802 assert( *pp==pId );
803 *pp = pId->pNext;
804 sqlite3_free(pId);
805 }
806 unixLeaveMutex();
807}
808#endif /* OS_VXWORKS */
809/*************** End of Unique File ID Utility Used By VxWorks ****************
810******************************************************************************/
811
812
813/******************************************************************************
814*************************** Posix Advisory Locking ****************************
815**
drh9b35ea62008-11-29 02:20:26 +0000816** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000817** section 6.5.2.2 lines 483 through 490 specify that when a process
818** sets or clears a lock, that operation overrides any prior locks set
819** by the same process. It does not explicitly say so, but this implies
820** that it overrides locks set by the same process using a different
821** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000822**
823** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000824** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
825**
826** Suppose ./file1 and ./file2 are really the same file (because
827** one is a hard or symbolic link to the other) then if you set
828** an exclusive lock on fd1, then try to get an exclusive lock
829** on fd2, it works. I would have expected the second lock to
830** fail since there was already a lock on the file due to fd1.
831** But not so. Since both locks came from the same process, the
832** second overrides the first, even though they were on different
833** file descriptors opened on different file names.
834**
drh734c9862008-11-28 15:37:20 +0000835** This means that we cannot use POSIX locks to synchronize file access
836** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000837** to synchronize access for threads in separate processes, but not
838** threads within the same process.
839**
840** To work around the problem, SQLite has to manage file locks internally
841** on its own. Whenever a new database is opened, we have to find the
842** specific inode of the database file (the inode is determined by the
843** st_dev and st_ino fields of the stat structure that fstat() fills in)
844** and check for locks already existing on that inode. When locks are
845** created or removed, we have to look at our own internal record of the
846** locks to see if another thread has previously set a lock on that same
847** inode.
848**
drh9b35ea62008-11-29 02:20:26 +0000849** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
850** For VxWorks, we have to use the alternative unique ID system based on
851** canonical filename and implemented in the previous division.)
852**
danielk1977ad94b582007-08-20 06:44:22 +0000853** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000854** descriptor. It is now a structure that holds the integer file
855** descriptor and a pointer to a structure that describes the internal
856** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000857** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000858** point to the same locking structure. The locking structure keeps
859** a reference count (so we will know when to delete it) and a "cnt"
860** field that tells us its internal lock status. cnt==0 means the
861** file is unlocked. cnt==-1 means the file has an exclusive lock.
862** cnt>0 means there are cnt shared locks on the file.
863**
864** Any attempt to lock or unlock a file first checks the locking
865** structure. The fcntl() system call is only invoked to set a
866** POSIX lock if the internal lock structure transitions between
867** a locked and an unlocked state.
868**
drh734c9862008-11-28 15:37:20 +0000869** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000870**
871** If you close a file descriptor that points to a file that has locks,
872** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000873** released. To work around this problem, each unixInodeInfo object
874** maintains a count of the number of pending locks on tha inode.
875** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000876** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000877** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000878** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000879** be closed and that list is walked (and cleared) when the last lock
880** clears.
881**
drh9b35ea62008-11-29 02:20:26 +0000882** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000883**
drh9b35ea62008-11-29 02:20:26 +0000884** Many older versions of linux use the LinuxThreads library which is
885** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000886** A cannot be modified or overridden by a different thread B.
887** Only thread A can modify the lock. Locking behavior is correct
888** if the appliation uses the newer Native Posix Thread Library (NPTL)
889** on linux - with NPTL a lock created by thread A can override locks
890** in thread B. But there is no way to know at compile-time which
891** threading library is being used. So there is no way to know at
892** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000893** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000894** current process.
drh5fdae772004-06-29 03:29:00 +0000895**
drh8af6c222010-05-14 12:43:01 +0000896** SQLite used to support LinuxThreads. But support for LinuxThreads
897** was dropped beginning with version 3.7.0. SQLite will still work with
898** LinuxThreads provided that (1) there is no more than one connection
899** per database file in the same process and (2) database connections
900** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000901*/
902
903/*
904** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000905** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000906*/
907struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000908 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000909#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000910 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000911#else
drh107886a2008-11-21 22:21:50 +0000912 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000913#endif
914};
915
916/*
drhbbd42a62004-05-22 17:41:58 +0000917** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000918** inode. Or, on LinuxThreads, there is one of these structures for
919** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000920**
danielk1977ad94b582007-08-20 06:44:22 +0000921** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000922** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000923** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000924*/
drh8af6c222010-05-14 12:43:01 +0000925struct unixInodeInfo {
926 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000927 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000928 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
929 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000930 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000931 unixShmNode *pShmNode; /* Shared memory associated with this inode */
932 int nLock; /* Number of outstanding file locks */
933 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
934 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
935 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000936#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000937 unsigned long long sharedByte; /* for AFP simulated shared lock */
938#endif
drh6c7d5c52008-11-21 20:32:33 +0000939#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000940 sem_t *pSem; /* Named POSIX semaphore */
941 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000942#endif
drhbbd42a62004-05-22 17:41:58 +0000943};
944
drhda0e7682008-07-30 15:27:54 +0000945/*
drh8af6c222010-05-14 12:43:01 +0000946** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000947*/
drhd91c68f2010-05-14 14:52:25 +0000948static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000949
drh5fdae772004-06-29 03:29:00 +0000950/*
dane18d4952011-02-21 11:46:24 +0000951**
952** This function - unixLogError_x(), is only ever called via the macro
953** unixLogError().
954**
955** It is invoked after an error occurs in an OS function and errno has been
956** set. It logs a message using sqlite3_log() containing the current value of
957** errno and, if possible, the human-readable equivalent from strerror() or
958** strerror_r().
959**
960** The first argument passed to the macro should be the error code that
961** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
962** The two subsequent arguments should be the name of the OS function that
963** failed (e.g. "unlink", "open") and the the associated file-system path,
964** if any.
965*/
drh0e9365c2011-03-02 02:08:13 +0000966#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
967static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000968 int errcode, /* SQLite error code */
969 const char *zFunc, /* Name of OS function that failed */
970 const char *zPath, /* File path associated with error */
971 int iLine /* Source line number where error occurred */
972){
973 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000974 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000975
976 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
977 ** the strerror() function to obtain the human-readable error message
978 ** equivalent to errno. Otherwise, use strerror_r().
979 */
980#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
981 char aErr[80];
982 memset(aErr, 0, sizeof(aErr));
983 zErr = aErr;
984
985 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
986 ** assume that the system provides the the GNU version of strerror_r() that
987 ** returns a pointer to a buffer containing the error message. That pointer
988 ** may point to aErr[], or it may point to some static storage somewhere.
989 ** Otherwise, assume that the system provides the POSIX version of
990 ** strerror_r(), which always writes an error message into aErr[].
991 **
992 ** If the code incorrectly assumes that it is the POSIX version that is
993 ** available, the error message will often be an empty string. Not a
994 ** huge problem. Incorrectly concluding that the GNU version is available
995 ** could lead to a segfault though.
996 */
997#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
998 zErr =
999# endif
drh0e9365c2011-03-02 02:08:13 +00001000 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001001
1002#elif SQLITE_THREADSAFE
1003 /* This is a threadsafe build, but strerror_r() is not available. */
1004 zErr = "";
1005#else
1006 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001007 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001008#endif
1009
1010 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001011 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001012 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001013 "os_unix.c:%d: (%d) %s(%s) - %s",
1014 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001015 );
1016
1017 return errcode;
1018}
1019
drh0e9365c2011-03-02 02:08:13 +00001020/*
1021** Close a file descriptor.
1022**
1023** We assume that close() almost always works, since it is only in a
1024** very sick application or on a very sick platform that it might fail.
1025** If it does fail, simply leak the file descriptor, but do log the
1026** error.
1027**
1028** Note that it is not safe to retry close() after EINTR since the
1029** file descriptor might have already been reused by another thread.
1030** So we don't even try to recover from an EINTR. Just log the error
1031** and move on.
1032*/
1033static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001034 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001035 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1036 pFile ? pFile->zPath : 0, lineno);
1037 }
1038}
dane18d4952011-02-21 11:46:24 +00001039
1040/*
danb0ac3e32010-06-16 10:55:42 +00001041** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001042*/
drh0e9365c2011-03-02 02:08:13 +00001043static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001044 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001045 UnixUnusedFd *p;
1046 UnixUnusedFd *pNext;
1047 for(p=pInode->pUnused; p; p=pNext){
1048 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001049 robust_close(pFile, p->fd, __LINE__);
1050 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001051 }
drh0e9365c2011-03-02 02:08:13 +00001052 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001053}
1054
1055/*
drh8af6c222010-05-14 12:43:01 +00001056** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001057**
1058** The mutex entered using the unixEnterMutex() function must be held
1059** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001060*/
danb0ac3e32010-06-16 10:55:42 +00001061static void releaseInodeInfo(unixFile *pFile){
1062 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001063 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001064 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001065 pInode->nRef--;
1066 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001067 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001068 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001069 if( pInode->pPrev ){
1070 assert( pInode->pPrev->pNext==pInode );
1071 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001072 }else{
drh8af6c222010-05-14 12:43:01 +00001073 assert( inodeList==pInode );
1074 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001075 }
drh8af6c222010-05-14 12:43:01 +00001076 if( pInode->pNext ){
1077 assert( pInode->pNext->pPrev==pInode );
1078 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001079 }
drh8af6c222010-05-14 12:43:01 +00001080 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001081 }
drhbbd42a62004-05-22 17:41:58 +00001082 }
1083}
1084
1085/*
drh8af6c222010-05-14 12:43:01 +00001086** Given a file descriptor, locate the unixInodeInfo object that
1087** describes that file descriptor. Create a new one if necessary. The
1088** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001089**
dan9359c7b2009-08-21 08:29:10 +00001090** The mutex entered using the unixEnterMutex() function must be held
1091** when this function is called.
1092**
drh6c7d5c52008-11-21 20:32:33 +00001093** Return an appropriate error code.
1094*/
drh8af6c222010-05-14 12:43:01 +00001095static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001096 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001097 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001098){
1099 int rc; /* System call return code */
1100 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001101 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1102 struct stat statbuf; /* Low-level file information */
1103 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001104
dan9359c7b2009-08-21 08:29:10 +00001105 assert( unixMutexHeld() );
1106
drh6c7d5c52008-11-21 20:32:33 +00001107 /* Get low-level information about the file that we can used to
1108 ** create a unique name for the file.
1109 */
1110 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001111 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001112 if( rc!=0 ){
1113 pFile->lastErrno = errno;
1114#ifdef EOVERFLOW
1115 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1116#endif
1117 return SQLITE_IOERR;
1118 }
1119
drheb0d74f2009-02-03 15:27:02 +00001120#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001121 /* On OS X on an msdos filesystem, the inode number is reported
1122 ** incorrectly for zero-size files. See ticket #3260. To work
1123 ** around this problem (we consider it a bug in OS X, not SQLite)
1124 ** we always increase the file size to 1 by writing a single byte
1125 ** prior to accessing the inode number. The one byte written is
1126 ** an ASCII 'S' character which also happens to be the first byte
1127 ** in the header of every SQLite database. In this way, if there
1128 ** is a race condition such that another thread has already populated
1129 ** the first page of the database, no damage is done.
1130 */
drh7ed97b92010-01-20 13:07:21 +00001131 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001132 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001133 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001134 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001135 return SQLITE_IOERR;
1136 }
drh99ab3b12011-03-02 15:09:07 +00001137 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001138 if( rc!=0 ){
1139 pFile->lastErrno = errno;
1140 return SQLITE_IOERR;
1141 }
1142 }
drheb0d74f2009-02-03 15:27:02 +00001143#endif
drh6c7d5c52008-11-21 20:32:33 +00001144
drh8af6c222010-05-14 12:43:01 +00001145 memset(&fileId, 0, sizeof(fileId));
1146 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001147#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001148 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001149#else
drh8af6c222010-05-14 12:43:01 +00001150 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001151#endif
drh8af6c222010-05-14 12:43:01 +00001152 pInode = inodeList;
1153 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1154 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001155 }
drh8af6c222010-05-14 12:43:01 +00001156 if( pInode==0 ){
1157 pInode = sqlite3_malloc( sizeof(*pInode) );
1158 if( pInode==0 ){
1159 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001160 }
drh8af6c222010-05-14 12:43:01 +00001161 memset(pInode, 0, sizeof(*pInode));
1162 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1163 pInode->nRef = 1;
1164 pInode->pNext = inodeList;
1165 pInode->pPrev = 0;
1166 if( inodeList ) inodeList->pPrev = pInode;
1167 inodeList = pInode;
1168 }else{
1169 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001170 }
drh8af6c222010-05-14 12:43:01 +00001171 *ppInode = pInode;
1172 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001173}
drh6c7d5c52008-11-21 20:32:33 +00001174
aswift5b1a2562008-08-22 00:22:35 +00001175
1176/*
danielk197713adf8a2004-06-03 16:08:41 +00001177** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001178** file by this or any other process. If such a lock is held, set *pResOut
1179** to a non-zero value otherwise *pResOut is set to zero. The return value
1180** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001181*/
danielk1977861f7452008-06-05 11:39:11 +00001182static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001183 int rc = SQLITE_OK;
1184 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001185 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001186
danielk1977861f7452008-06-05 11:39:11 +00001187 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1188
drh054889e2005-11-30 03:20:31 +00001189 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001190 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001191
1192 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001193 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001194 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001195 }
1196
drh2ac3ee92004-06-07 16:27:46 +00001197 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001198 */
danielk197709480a92009-02-09 05:32:32 +00001199#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001200 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001201 struct flock lock;
1202 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001203 lock.l_start = RESERVED_BYTE;
1204 lock.l_len = 1;
1205 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001206 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1207 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1208 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001209 } else if( lock.l_type!=F_UNLCK ){
1210 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001211 }
1212 }
danielk197709480a92009-02-09 05:32:32 +00001213#endif
danielk197713adf8a2004-06-03 16:08:41 +00001214
drh6c7d5c52008-11-21 20:32:33 +00001215 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001216 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001217
aswift5b1a2562008-08-22 00:22:35 +00001218 *pResOut = reserved;
1219 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001220}
1221
1222/*
drha7e61d82011-03-12 17:02:57 +00001223** Attempt to set a system-lock on the file pFile. The lock is
1224** described by pLock.
1225**
drh77197112011-03-15 19:08:48 +00001226** If the pFile was opened read/write from unix-excl, then the only lock
1227** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001228** the first time any lock is attempted. All subsequent system locking
1229** operations become no-ops. Locking operations still happen internally,
1230** in order to coordinate access between separate database connections
1231** within this process, but all of that is handled in memory and the
1232** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001233**
1234** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1235** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1236** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001237**
1238** Zero is returned if the call completes successfully, or -1 if a call
1239** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001240*/
1241static int unixFileLock(unixFile *pFile, struct flock *pLock){
1242 int rc;
drh3cb93392011-03-12 18:10:44 +00001243 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001244 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001245 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001246 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1247 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1248 ){
drh3cb93392011-03-12 18:10:44 +00001249 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001250 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001251 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001252 lock.l_whence = SEEK_SET;
1253 lock.l_start = SHARED_FIRST;
1254 lock.l_len = SHARED_SIZE;
1255 lock.l_type = F_WRLCK;
1256 rc = osFcntl(pFile->h, F_SETLK, &lock);
1257 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001258 pInode->bProcessLock = 1;
1259 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001260 }else{
1261 rc = 0;
1262 }
1263 }else{
1264 rc = osFcntl(pFile->h, F_SETLK, pLock);
1265 }
1266 return rc;
1267}
1268
1269/*
drh308c2a52010-05-14 11:30:18 +00001270** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001271** of the following:
1272**
drh2ac3ee92004-06-07 16:27:46 +00001273** (1) SHARED_LOCK
1274** (2) RESERVED_LOCK
1275** (3) PENDING_LOCK
1276** (4) EXCLUSIVE_LOCK
1277**
drhb3e04342004-06-08 00:47:47 +00001278** Sometimes when requesting one lock state, additional lock states
1279** are inserted in between. The locking might fail on one of the later
1280** transitions leaving the lock state different from what it started but
1281** still short of its goal. The following chart shows the allowed
1282** transitions and the inserted intermediate states:
1283**
1284** UNLOCKED -> SHARED
1285** SHARED -> RESERVED
1286** SHARED -> (PENDING) -> EXCLUSIVE
1287** RESERVED -> (PENDING) -> EXCLUSIVE
1288** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001289**
drha6abd042004-06-09 17:37:22 +00001290** This routine will only increase a lock. Use the sqlite3OsUnlock()
1291** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001292*/
drh308c2a52010-05-14 11:30:18 +00001293static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001294 /* The following describes the implementation of the various locks and
1295 ** lock transitions in terms of the POSIX advisory shared and exclusive
1296 ** lock primitives (called read-locks and write-locks below, to avoid
1297 ** confusion with SQLite lock names). The algorithms are complicated
1298 ** slightly in order to be compatible with windows systems simultaneously
1299 ** accessing the same database file, in case that is ever required.
1300 **
1301 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1302 ** byte', each single bytes at well known offsets, and the 'shared byte
1303 ** range', a range of 510 bytes at a well known offset.
1304 **
1305 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1306 ** byte'. If this is successful, a random byte from the 'shared byte
1307 ** range' is read-locked and the lock on the 'pending byte' released.
1308 **
danielk197790ba3bd2004-06-25 08:32:25 +00001309 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1310 ** A RESERVED lock is implemented by grabbing a write-lock on the
1311 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001312 **
1313 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001314 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1315 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1316 ** obtained, but existing SHARED locks are allowed to persist. A process
1317 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1318 ** This property is used by the algorithm for rolling back a journal file
1319 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001320 **
danielk197790ba3bd2004-06-25 08:32:25 +00001321 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1322 ** implemented by obtaining a write-lock on the entire 'shared byte
1323 ** range'. Since all other locks require a read-lock on one of the bytes
1324 ** within this range, this ensures that no other locks are held on the
1325 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001326 **
1327 ** The reason a single byte cannot be used instead of the 'shared byte
1328 ** range' is that some versions of windows do not support read-locks. By
1329 ** locking a random byte from a range, concurrent SHARED locks may exist
1330 ** even if the locking primitive used is always a write-lock.
1331 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001332 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001333 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001334 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001335 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001336 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001337
drh054889e2005-11-30 03:20:31 +00001338 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001339 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1340 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001341 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001342
1343 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001344 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001345 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001346 */
drh308c2a52010-05-14 11:30:18 +00001347 if( pFile->eFileLock>=eFileLock ){
1348 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1349 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 return SQLITE_OK;
1351 }
1352
drh0c2694b2009-09-03 16:23:44 +00001353 /* Make sure the locking sequence is correct.
1354 ** (1) We never move from unlocked to anything higher than shared lock.
1355 ** (2) SQLite never explicitly requests a pendig lock.
1356 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001357 */
drh308c2a52010-05-14 11:30:18 +00001358 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1359 assert( eFileLock!=PENDING_LOCK );
1360 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001361
drh8af6c222010-05-14 12:43:01 +00001362 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001363 */
drh6c7d5c52008-11-21 20:32:33 +00001364 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001365 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001366
danielk1977ad94b582007-08-20 06:44:22 +00001367 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001368 ** handle that precludes the requested lock, return BUSY.
1369 */
drh8af6c222010-05-14 12:43:01 +00001370 if( (pFile->eFileLock!=pInode->eFileLock &&
1371 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 ){
1373 rc = SQLITE_BUSY;
1374 goto end_lock;
1375 }
1376
1377 /* If a SHARED lock is requested, and some thread using this PID already
1378 ** has a SHARED or RESERVED lock, then increment reference counts and
1379 ** return SQLITE_OK.
1380 */
drh308c2a52010-05-14 11:30:18 +00001381 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001382 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001383 assert( eFileLock==SHARED_LOCK );
1384 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001385 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001386 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001387 pInode->nShared++;
1388 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001389 goto end_lock;
1390 }
1391
danielk19779a1d0ab2004-06-01 14:09:28 +00001392
drh3cde3bb2004-06-12 02:17:14 +00001393 /* A PENDING lock is needed before acquiring a SHARED lock and before
1394 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1395 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 */
drh0c2694b2009-09-03 16:23:44 +00001397 lock.l_len = 1L;
1398 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001399 if( eFileLock==SHARED_LOCK
1400 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001401 ){
drh308c2a52010-05-14 11:30:18 +00001402 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001403 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001404 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001405 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001407 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001408 pFile->lastErrno = tErrno;
1409 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001410 goto end_lock;
1411 }
drh3cde3bb2004-06-12 02:17:14 +00001412 }
1413
1414
1415 /* If control gets to this point, then actually go ahead and make
1416 ** operating system calls for the specified lock.
1417 */
drh308c2a52010-05-14 11:30:18 +00001418 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001419 assert( pInode->nShared==0 );
1420 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001421 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001422
drh2ac3ee92004-06-07 16:27:46 +00001423 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001424 lock.l_start = SHARED_FIRST;
1425 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001426 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001427 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001428 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001429 }
dan661d71a2011-03-30 19:08:03 +00001430
drh2ac3ee92004-06-07 16:27:46 +00001431 /* Drop the temporary PENDING lock */
1432 lock.l_start = PENDING_BYTE;
1433 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001434 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001435 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1436 /* This could happen with a network mount */
1437 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001438 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001439 }
dan661d71a2011-03-30 19:08:03 +00001440
1441 if( rc ){
1442 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001443 pFile->lastErrno = tErrno;
1444 }
dan661d71a2011-03-30 19:08:03 +00001445 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001446 }else{
drh308c2a52010-05-14 11:30:18 +00001447 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001448 pInode->nLock++;
1449 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001450 }
drh8af6c222010-05-14 12:43:01 +00001451 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001452 /* We are trying for an exclusive lock but another thread in this
1453 ** same process is still holding a shared lock. */
1454 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001455 }else{
drh3cde3bb2004-06-12 02:17:14 +00001456 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001457 ** assumed that there is a SHARED or greater lock on the file
1458 ** already.
1459 */
drh308c2a52010-05-14 11:30:18 +00001460 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001461 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001462
1463 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1464 if( eFileLock==RESERVED_LOCK ){
1465 lock.l_start = RESERVED_BYTE;
1466 lock.l_len = 1L;
1467 }else{
1468 lock.l_start = SHARED_FIRST;
1469 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001470 }
dan661d71a2011-03-30 19:08:03 +00001471
1472 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001473 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001474 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001475 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001476 pFile->lastErrno = tErrno;
1477 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001478 }
drhbbd42a62004-05-22 17:41:58 +00001479 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001480
drh8f941bc2009-01-14 23:03:40 +00001481
1482#ifndef NDEBUG
1483 /* Set up the transaction-counter change checking flags when
1484 ** transitioning from a SHARED to a RESERVED lock. The change
1485 ** from SHARED to RESERVED marks the beginning of a normal
1486 ** write operation (not a hot journal rollback).
1487 */
1488 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001489 && pFile->eFileLock<=SHARED_LOCK
1490 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001491 ){
1492 pFile->transCntrChng = 0;
1493 pFile->dbUpdate = 0;
1494 pFile->inNormalWrite = 1;
1495 }
1496#endif
1497
1498
danielk1977ecb2a962004-06-02 06:30:16 +00001499 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001500 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001501 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001502 }else if( eFileLock==EXCLUSIVE_LOCK ){
1503 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001504 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001505 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001506
1507end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001508 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001509 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1510 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001511 return rc;
1512}
1513
1514/*
dan08da86a2009-08-21 17:18:03 +00001515** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001516** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001517*/
1518static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001519 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001520 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001521 p->pNext = pInode->pUnused;
1522 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001523 pFile->h = -1;
1524 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001525}
1526
1527/*
drh308c2a52010-05-14 11:30:18 +00001528** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001529** must be either NO_LOCK or SHARED_LOCK.
1530**
1531** If the locking level of the file descriptor is already at or below
1532** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001533**
1534** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1535** the byte range is divided into 2 parts and the first part is unlocked then
1536** set to a read lock, then the other part is simply unlocked. This works
1537** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1538** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001539*/
drha7e61d82011-03-12 17:02:57 +00001540static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001541 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001542 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001543 struct flock lock;
1544 int rc = SQLITE_OK;
1545 int h;
drha6abd042004-06-09 17:37:22 +00001546
drh054889e2005-11-30 03:20:31 +00001547 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001548 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001549 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001550 getpid()));
drha6abd042004-06-09 17:37:22 +00001551
drh308c2a52010-05-14 11:30:18 +00001552 assert( eFileLock<=SHARED_LOCK );
1553 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001554 return SQLITE_OK;
1555 }
drh6c7d5c52008-11-21 20:32:33 +00001556 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001557 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001558 pInode = pFile->pInode;
1559 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001560 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001561 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001562 SimulateIOErrorBenign(1);
1563 SimulateIOError( h=(-1) )
1564 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001565
1566#ifndef NDEBUG
1567 /* When reducing a lock such that other processes can start
1568 ** reading the database file again, make sure that the
1569 ** transaction counter was updated if any part of the database
1570 ** file changed. If the transaction counter is not updated,
1571 ** other connections to the same file might not realize that
1572 ** the file has changed and hence might not know to flush their
1573 ** cache. The use of a stale cache can lead to database corruption.
1574 */
dan7c246102010-04-12 19:00:29 +00001575#if 0
drh8f941bc2009-01-14 23:03:40 +00001576 assert( pFile->inNormalWrite==0
1577 || pFile->dbUpdate==0
1578 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001579#endif
drh8f941bc2009-01-14 23:03:40 +00001580 pFile->inNormalWrite = 0;
1581#endif
1582
drh7ed97b92010-01-20 13:07:21 +00001583 /* downgrading to a shared lock on NFS involves clearing the write lock
1584 ** before establishing the readlock - to avoid a race condition we downgrade
1585 ** the lock in 2 blocks, so that part of the range will be covered by a
1586 ** write lock until the rest is covered by a read lock:
1587 ** 1: [WWWWW]
1588 ** 2: [....W]
1589 ** 3: [RRRRW]
1590 ** 4: [RRRR.]
1591 */
drh308c2a52010-05-14 11:30:18 +00001592 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001593
1594#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001595 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001596 assert( handleNFSUnlock==0 );
1597#endif
1598#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001599 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001600 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001601 off_t divSize = SHARED_SIZE - 1;
1602
1603 lock.l_type = F_UNLCK;
1604 lock.l_whence = SEEK_SET;
1605 lock.l_start = SHARED_FIRST;
1606 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001607 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001608 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001609 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001610 if( IS_LOCK_ERROR(rc) ){
1611 pFile->lastErrno = tErrno;
1612 }
1613 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001614 }
drh7ed97b92010-01-20 13:07:21 +00001615 lock.l_type = F_RDLCK;
1616 lock.l_whence = SEEK_SET;
1617 lock.l_start = SHARED_FIRST;
1618 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001619 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001620 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001621 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1622 if( IS_LOCK_ERROR(rc) ){
1623 pFile->lastErrno = tErrno;
1624 }
1625 goto end_unlock;
1626 }
1627 lock.l_type = F_UNLCK;
1628 lock.l_whence = SEEK_SET;
1629 lock.l_start = SHARED_FIRST+divSize;
1630 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001631 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001632 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001633 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001634 if( IS_LOCK_ERROR(rc) ){
1635 pFile->lastErrno = tErrno;
1636 }
1637 goto end_unlock;
1638 }
drh30f776f2011-02-25 03:25:07 +00001639 }else
1640#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1641 {
drh7ed97b92010-01-20 13:07:21 +00001642 lock.l_type = F_RDLCK;
1643 lock.l_whence = SEEK_SET;
1644 lock.l_start = SHARED_FIRST;
1645 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001646 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001647 /* In theory, the call to unixFileLock() cannot fail because another
1648 ** process is holding an incompatible lock. If it does, this
1649 ** indicates that the other process is not following the locking
1650 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1651 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1652 ** an assert to fail). */
1653 rc = SQLITE_IOERR_RDLOCK;
1654 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001655 goto end_unlock;
1656 }
drh9c105bb2004-10-02 20:38:28 +00001657 }
1658 }
drhbbd42a62004-05-22 17:41:58 +00001659 lock.l_type = F_UNLCK;
1660 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001661 lock.l_start = PENDING_BYTE;
1662 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001663 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001664 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001665 }else{
danea83bc62011-04-01 11:56:32 +00001666 rc = SQLITE_IOERR_UNLOCK;
1667 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001668 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001669 }
drhbbd42a62004-05-22 17:41:58 +00001670 }
drh308c2a52010-05-14 11:30:18 +00001671 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001672 /* Decrement the shared lock counter. Release the lock using an
1673 ** OS call only when all threads in this same process have released
1674 ** the lock.
1675 */
drh8af6c222010-05-14 12:43:01 +00001676 pInode->nShared--;
1677 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001678 lock.l_type = F_UNLCK;
1679 lock.l_whence = SEEK_SET;
1680 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001681 SimulateIOErrorBenign(1);
1682 SimulateIOError( h=(-1) )
1683 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001684 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001685 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001686 }else{
danea83bc62011-04-01 11:56:32 +00001687 rc = SQLITE_IOERR_UNLOCK;
1688 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001689 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001690 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001691 }
drha6abd042004-06-09 17:37:22 +00001692 }
1693
drhbbd42a62004-05-22 17:41:58 +00001694 /* Decrement the count of locks against this same file. When the
1695 ** count reaches zero, close any other file descriptors whose close
1696 ** was deferred because of outstanding locks.
1697 */
drh8af6c222010-05-14 12:43:01 +00001698 pInode->nLock--;
1699 assert( pInode->nLock>=0 );
1700 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001701 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001702 }
1703 }
aswift5b1a2562008-08-22 00:22:35 +00001704
1705end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001706 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001707 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001708 return rc;
drhbbd42a62004-05-22 17:41:58 +00001709}
1710
1711/*
drh308c2a52010-05-14 11:30:18 +00001712** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001713** must be either NO_LOCK or SHARED_LOCK.
1714**
1715** If the locking level of the file descriptor is already at or below
1716** the requested locking level, this routine is a no-op.
1717*/
drh308c2a52010-05-14 11:30:18 +00001718static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001719 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001720}
1721
1722/*
danielk1977e339d652008-06-28 11:23:00 +00001723** This function performs the parts of the "close file" operation
1724** common to all locking schemes. It closes the directory and file
1725** handles, if they are valid, and sets all fields of the unixFile
1726** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001727**
1728** It is *not* necessary to hold the mutex when this routine is called,
1729** even on VxWorks. A mutex will be acquired on VxWorks by the
1730** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001731*/
1732static int closeUnixFile(sqlite3_file *id){
1733 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001734 if( pFile->dirfd>=0 ){
1735 robust_close(pFile, pFile->dirfd, __LINE__);
1736 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001737 }
dan661d71a2011-03-30 19:08:03 +00001738 if( pFile->h>=0 ){
1739 robust_close(pFile, pFile->h, __LINE__);
1740 pFile->h = -1;
1741 }
1742#if OS_VXWORKS
1743 if( pFile->pId ){
1744 if( pFile->isDelete ){
1745 unlink(pFile->pId->zCanonicalName);
1746 }
1747 vxworksReleaseFileId(pFile->pId);
1748 pFile->pId = 0;
1749 }
1750#endif
1751 OSTRACE(("CLOSE %-3d\n", pFile->h));
1752 OpenCounter(-1);
1753 sqlite3_free(pFile->pUnused);
1754 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001755 return SQLITE_OK;
1756}
1757
1758/*
danielk1977e3026632004-06-22 11:29:02 +00001759** Close a file.
1760*/
danielk197762079062007-08-15 17:08:46 +00001761static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001762 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001763 unixFile *pFile = (unixFile *)id;
1764 unixUnlock(id, NO_LOCK);
1765 unixEnterMutex();
1766
1767 /* unixFile.pInode is always valid here. Otherwise, a different close
1768 ** routine (e.g. nolockClose()) would be called instead.
1769 */
1770 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1771 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1772 /* If there are outstanding locks, do not actually close the file just
1773 ** yet because that would clear those locks. Instead, add the file
1774 ** descriptor to pInode->pUnused list. It will be automatically closed
1775 ** when the last lock is cleared.
1776 */
1777 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001778 }
dan661d71a2011-03-30 19:08:03 +00001779 releaseInodeInfo(pFile);
1780 rc = closeUnixFile(id);
1781 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001782 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001783}
1784
drh734c9862008-11-28 15:37:20 +00001785/************** End of the posix advisory lock implementation *****************
1786******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001787
drh734c9862008-11-28 15:37:20 +00001788/******************************************************************************
1789****************************** No-op Locking **********************************
1790**
1791** Of the various locking implementations available, this is by far the
1792** simplest: locking is ignored. No attempt is made to lock the database
1793** file for reading or writing.
1794**
1795** This locking mode is appropriate for use on read-only databases
1796** (ex: databases that are burned into CD-ROM, for example.) It can
1797** also be used if the application employs some external mechanism to
1798** prevent simultaneous access of the same database by two or more
1799** database connections. But there is a serious risk of database
1800** corruption if this locking mode is used in situations where multiple
1801** database connections are accessing the same database file at the same
1802** time and one or more of those connections are writing.
1803*/
drhbfe66312006-10-03 17:40:40 +00001804
drh734c9862008-11-28 15:37:20 +00001805static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1806 UNUSED_PARAMETER(NotUsed);
1807 *pResOut = 0;
1808 return SQLITE_OK;
1809}
drh734c9862008-11-28 15:37:20 +00001810static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1811 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1812 return SQLITE_OK;
1813}
drh734c9862008-11-28 15:37:20 +00001814static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1815 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1816 return SQLITE_OK;
1817}
1818
1819/*
drh9b35ea62008-11-29 02:20:26 +00001820** Close the file.
drh734c9862008-11-28 15:37:20 +00001821*/
1822static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001823 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001824}
1825
1826/******************* End of the no-op lock implementation *********************
1827******************************************************************************/
1828
1829/******************************************************************************
1830************************* Begin dot-file Locking ******************************
1831**
drh0c2694b2009-09-03 16:23:44 +00001832** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001833** files in order to control access to the database. This works on just
1834** about every filesystem imaginable. But there are serious downsides:
1835**
1836** (1) There is zero concurrency. A single reader blocks all other
1837** connections from reading or writing the database.
1838**
1839** (2) An application crash or power loss can leave stale lock files
1840** sitting around that need to be cleared manually.
1841**
1842** Nevertheless, a dotlock is an appropriate locking mode for use if no
1843** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001844**
1845** Dotfile locking works by creating a file in the same directory as the
1846** database and with the same name but with a ".lock" extension added.
1847** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1848** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001849*/
1850
1851/*
1852** The file suffix added to the data base filename in order to create the
1853** lock file.
1854*/
1855#define DOTLOCK_SUFFIX ".lock"
1856
drh7708e972008-11-29 00:56:52 +00001857/*
1858** This routine checks if there is a RESERVED lock held on the specified
1859** file by this or any other process. If such a lock is held, set *pResOut
1860** to a non-zero value otherwise *pResOut is set to zero. The return value
1861** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1862**
1863** In dotfile locking, either a lock exists or it does not. So in this
1864** variation of CheckReservedLock(), *pResOut is set to true if any lock
1865** is held on the file and false if the file is unlocked.
1866*/
drh734c9862008-11-28 15:37:20 +00001867static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1868 int rc = SQLITE_OK;
1869 int reserved = 0;
1870 unixFile *pFile = (unixFile*)id;
1871
1872 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1873
1874 assert( pFile );
1875
1876 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001877 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001878 /* Either this connection or some other connection in the same process
1879 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001880 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001881 }else{
1882 /* The lock is held if and only if the lockfile exists */
1883 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001884 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001885 }
drh308c2a52010-05-14 11:30:18 +00001886 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001887 *pResOut = reserved;
1888 return rc;
1889}
1890
drh7708e972008-11-29 00:56:52 +00001891/*
drh308c2a52010-05-14 11:30:18 +00001892** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001893** of the following:
1894**
1895** (1) SHARED_LOCK
1896** (2) RESERVED_LOCK
1897** (3) PENDING_LOCK
1898** (4) EXCLUSIVE_LOCK
1899**
1900** Sometimes when requesting one lock state, additional lock states
1901** are inserted in between. The locking might fail on one of the later
1902** transitions leaving the lock state different from what it started but
1903** still short of its goal. The following chart shows the allowed
1904** transitions and the inserted intermediate states:
1905**
1906** UNLOCKED -> SHARED
1907** SHARED -> RESERVED
1908** SHARED -> (PENDING) -> EXCLUSIVE
1909** RESERVED -> (PENDING) -> EXCLUSIVE
1910** PENDING -> EXCLUSIVE
1911**
1912** This routine will only increase a lock. Use the sqlite3OsUnlock()
1913** routine to lower a locking level.
1914**
1915** With dotfile locking, we really only support state (4): EXCLUSIVE.
1916** But we track the other locking levels internally.
1917*/
drh308c2a52010-05-14 11:30:18 +00001918static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001919 unixFile *pFile = (unixFile*)id;
1920 int fd;
1921 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001922 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001923
drh7708e972008-11-29 00:56:52 +00001924
1925 /* If we have any lock, then the lock file already exists. All we have
1926 ** to do is adjust our internal record of the lock level.
1927 */
drh308c2a52010-05-14 11:30:18 +00001928 if( pFile->eFileLock > NO_LOCK ){
1929 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001930#if !OS_VXWORKS
1931 /* Always update the timestamp on the old file */
1932 utimes(zLockFile, NULL);
1933#endif
drh7708e972008-11-29 00:56:52 +00001934 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001935 }
1936
1937 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001938 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001939 if( fd<0 ){
1940 /* failed to open/create the file, someone else may have stolen the lock */
1941 int tErrno = errno;
1942 if( EEXIST == tErrno ){
1943 rc = SQLITE_BUSY;
1944 } else {
1945 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1946 if( IS_LOCK_ERROR(rc) ){
1947 pFile->lastErrno = tErrno;
1948 }
1949 }
drh7708e972008-11-29 00:56:52 +00001950 return rc;
drh734c9862008-11-28 15:37:20 +00001951 }
drh0e9365c2011-03-02 02:08:13 +00001952 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001953
1954 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001955 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001956 return rc;
1957}
1958
drh7708e972008-11-29 00:56:52 +00001959/*
drh308c2a52010-05-14 11:30:18 +00001960** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001961** must be either NO_LOCK or SHARED_LOCK.
1962**
1963** If the locking level of the file descriptor is already at or below
1964** the requested locking level, this routine is a no-op.
1965**
1966** When the locking level reaches NO_LOCK, delete the lock file.
1967*/
drh308c2a52010-05-14 11:30:18 +00001968static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001969 unixFile *pFile = (unixFile*)id;
1970 char *zLockFile = (char *)pFile->lockingContext;
1971
1972 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001973 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1974 pFile->eFileLock, getpid()));
1975 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001976
1977 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001978 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001979 return SQLITE_OK;
1980 }
drh7708e972008-11-29 00:56:52 +00001981
1982 /* To downgrade to shared, simply update our internal notion of the
1983 ** lock state. No need to mess with the file on disk.
1984 */
drh308c2a52010-05-14 11:30:18 +00001985 if( eFileLock==SHARED_LOCK ){
1986 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001987 return SQLITE_OK;
1988 }
1989
drh7708e972008-11-29 00:56:52 +00001990 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001991 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001992 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001993 int rc = 0;
1994 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001995 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00001996 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00001997 }
1998 if( IS_LOCK_ERROR(rc) ){
1999 pFile->lastErrno = tErrno;
2000 }
2001 return rc;
2002 }
drh308c2a52010-05-14 11:30:18 +00002003 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002004 return SQLITE_OK;
2005}
2006
2007/*
drh9b35ea62008-11-29 02:20:26 +00002008** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002009*/
2010static int dotlockClose(sqlite3_file *id) {
2011 int rc;
2012 if( id ){
2013 unixFile *pFile = (unixFile*)id;
2014 dotlockUnlock(id, NO_LOCK);
2015 sqlite3_free(pFile->lockingContext);
2016 }
drh734c9862008-11-28 15:37:20 +00002017 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002018 return rc;
2019}
2020/****************** End of the dot-file lock implementation *******************
2021******************************************************************************/
2022
2023/******************************************************************************
2024************************** Begin flock Locking ********************************
2025**
2026** Use the flock() system call to do file locking.
2027**
drh6b9d6dd2008-12-03 19:34:47 +00002028** flock() locking is like dot-file locking in that the various
2029** fine-grain locking levels supported by SQLite are collapsed into
2030** a single exclusive lock. In other words, SHARED, RESERVED, and
2031** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2032** still works when you do this, but concurrency is reduced since
2033** only a single process can be reading the database at a time.
2034**
drh734c9862008-11-28 15:37:20 +00002035** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2036** compiling for VXWORKS.
2037*/
2038#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002039
drh6b9d6dd2008-12-03 19:34:47 +00002040/*
drhff812312011-02-23 13:33:46 +00002041** Retry flock() calls that fail with EINTR
2042*/
2043#ifdef EINTR
2044static int robust_flock(int fd, int op){
2045 int rc;
2046 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2047 return rc;
2048}
2049#else
drh5c819272011-02-23 14:00:12 +00002050# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002051#endif
2052
2053
2054/*
drh6b9d6dd2008-12-03 19:34:47 +00002055** This routine checks if there is a RESERVED lock held on the specified
2056** file by this or any other process. If such a lock is held, set *pResOut
2057** to a non-zero value otherwise *pResOut is set to zero. The return value
2058** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2059*/
drh734c9862008-11-28 15:37:20 +00002060static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2061 int rc = SQLITE_OK;
2062 int reserved = 0;
2063 unixFile *pFile = (unixFile*)id;
2064
2065 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2066
2067 assert( pFile );
2068
2069 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002070 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002071 reserved = 1;
2072 }
2073
2074 /* Otherwise see if some other process holds it. */
2075 if( !reserved ){
2076 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002077 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002078 if( !lrc ){
2079 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002080 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002081 if ( lrc ) {
2082 int tErrno = errno;
2083 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002084 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002085 if( IS_LOCK_ERROR(lrc) ){
2086 pFile->lastErrno = tErrno;
2087 rc = lrc;
2088 }
2089 }
2090 } else {
2091 int tErrno = errno;
2092 reserved = 1;
2093 /* someone else might have it reserved */
2094 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2095 if( IS_LOCK_ERROR(lrc) ){
2096 pFile->lastErrno = tErrno;
2097 rc = lrc;
2098 }
2099 }
2100 }
drh308c2a52010-05-14 11:30:18 +00002101 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002102
2103#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2104 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2105 rc = SQLITE_OK;
2106 reserved=1;
2107 }
2108#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2109 *pResOut = reserved;
2110 return rc;
2111}
2112
drh6b9d6dd2008-12-03 19:34:47 +00002113/*
drh308c2a52010-05-14 11:30:18 +00002114** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002115** of the following:
2116**
2117** (1) SHARED_LOCK
2118** (2) RESERVED_LOCK
2119** (3) PENDING_LOCK
2120** (4) EXCLUSIVE_LOCK
2121**
2122** Sometimes when requesting one lock state, additional lock states
2123** are inserted in between. The locking might fail on one of the later
2124** transitions leaving the lock state different from what it started but
2125** still short of its goal. The following chart shows the allowed
2126** transitions and the inserted intermediate states:
2127**
2128** UNLOCKED -> SHARED
2129** SHARED -> RESERVED
2130** SHARED -> (PENDING) -> EXCLUSIVE
2131** RESERVED -> (PENDING) -> EXCLUSIVE
2132** PENDING -> EXCLUSIVE
2133**
2134** flock() only really support EXCLUSIVE locks. We track intermediate
2135** lock states in the sqlite3_file structure, but all locks SHARED or
2136** above are really EXCLUSIVE locks and exclude all other processes from
2137** access the file.
2138**
2139** This routine will only increase a lock. Use the sqlite3OsUnlock()
2140** routine to lower a locking level.
2141*/
drh308c2a52010-05-14 11:30:18 +00002142static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002143 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002144 unixFile *pFile = (unixFile*)id;
2145
2146 assert( pFile );
2147
2148 /* if we already have a lock, it is exclusive.
2149 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002150 if (pFile->eFileLock > NO_LOCK) {
2151 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002152 return SQLITE_OK;
2153 }
2154
2155 /* grab an exclusive lock */
2156
drhff812312011-02-23 13:33:46 +00002157 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002158 int tErrno = errno;
2159 /* didn't get, must be busy */
2160 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2161 if( IS_LOCK_ERROR(rc) ){
2162 pFile->lastErrno = tErrno;
2163 }
2164 } else {
2165 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002166 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002167 }
drh308c2a52010-05-14 11:30:18 +00002168 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2169 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002170#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2171 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2172 rc = SQLITE_BUSY;
2173 }
2174#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2175 return rc;
2176}
2177
drh6b9d6dd2008-12-03 19:34:47 +00002178
2179/*
drh308c2a52010-05-14 11:30:18 +00002180** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002181** must be either NO_LOCK or SHARED_LOCK.
2182**
2183** If the locking level of the file descriptor is already at or below
2184** the requested locking level, this routine is a no-op.
2185*/
drh308c2a52010-05-14 11:30:18 +00002186static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002187 unixFile *pFile = (unixFile*)id;
2188
2189 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002190 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2191 pFile->eFileLock, getpid()));
2192 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002193
2194 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002195 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002196 return SQLITE_OK;
2197 }
2198
2199 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002200 if (eFileLock==SHARED_LOCK) {
2201 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002202 return SQLITE_OK;
2203 }
2204
2205 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002206 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002207#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002208 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002209#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002210 return SQLITE_IOERR_UNLOCK;
2211 }else{
drh308c2a52010-05-14 11:30:18 +00002212 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002213 return SQLITE_OK;
2214 }
2215}
2216
2217/*
2218** Close a file.
2219*/
2220static int flockClose(sqlite3_file *id) {
2221 if( id ){
2222 flockUnlock(id, NO_LOCK);
2223 }
2224 return closeUnixFile(id);
2225}
2226
2227#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2228
2229/******************* End of the flock lock implementation *********************
2230******************************************************************************/
2231
2232/******************************************************************************
2233************************ Begin Named Semaphore Locking ************************
2234**
2235** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002236**
2237** Semaphore locking is like dot-lock and flock in that it really only
2238** supports EXCLUSIVE locking. Only a single process can read or write
2239** the database file at a time. This reduces potential concurrency, but
2240** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002241*/
2242#if OS_VXWORKS
2243
drh6b9d6dd2008-12-03 19:34:47 +00002244/*
2245** This routine checks if there is a RESERVED lock held on the specified
2246** file by this or any other process. If such a lock is held, set *pResOut
2247** to a non-zero value otherwise *pResOut is set to zero. The return value
2248** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2249*/
drh734c9862008-11-28 15:37:20 +00002250static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2251 int rc = SQLITE_OK;
2252 int reserved = 0;
2253 unixFile *pFile = (unixFile*)id;
2254
2255 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2256
2257 assert( pFile );
2258
2259 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002260 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002261 reserved = 1;
2262 }
2263
2264 /* Otherwise see if some other process holds it. */
2265 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002266 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002267 struct stat statBuf;
2268
2269 if( sem_trywait(pSem)==-1 ){
2270 int tErrno = errno;
2271 if( EAGAIN != tErrno ){
2272 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2273 pFile->lastErrno = tErrno;
2274 } else {
2275 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002276 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002277 }
2278 }else{
2279 /* we could have it if we want it */
2280 sem_post(pSem);
2281 }
2282 }
drh308c2a52010-05-14 11:30:18 +00002283 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002284
2285 *pResOut = reserved;
2286 return rc;
2287}
2288
drh6b9d6dd2008-12-03 19:34:47 +00002289/*
drh308c2a52010-05-14 11:30:18 +00002290** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002291** of the following:
2292**
2293** (1) SHARED_LOCK
2294** (2) RESERVED_LOCK
2295** (3) PENDING_LOCK
2296** (4) EXCLUSIVE_LOCK
2297**
2298** Sometimes when requesting one lock state, additional lock states
2299** are inserted in between. The locking might fail on one of the later
2300** transitions leaving the lock state different from what it started but
2301** still short of its goal. The following chart shows the allowed
2302** transitions and the inserted intermediate states:
2303**
2304** UNLOCKED -> SHARED
2305** SHARED -> RESERVED
2306** SHARED -> (PENDING) -> EXCLUSIVE
2307** RESERVED -> (PENDING) -> EXCLUSIVE
2308** PENDING -> EXCLUSIVE
2309**
2310** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2311** lock states in the sqlite3_file structure, but all locks SHARED or
2312** above are really EXCLUSIVE locks and exclude all other processes from
2313** access the file.
2314**
2315** This routine will only increase a lock. Use the sqlite3OsUnlock()
2316** routine to lower a locking level.
2317*/
drh308c2a52010-05-14 11:30:18 +00002318static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002319 unixFile *pFile = (unixFile*)id;
2320 int fd;
drh8af6c222010-05-14 12:43:01 +00002321 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002322 int rc = SQLITE_OK;
2323
2324 /* if we already have a lock, it is exclusive.
2325 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002326 if (pFile->eFileLock > NO_LOCK) {
2327 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002328 rc = SQLITE_OK;
2329 goto sem_end_lock;
2330 }
2331
2332 /* lock semaphore now but bail out when already locked. */
2333 if( sem_trywait(pSem)==-1 ){
2334 rc = SQLITE_BUSY;
2335 goto sem_end_lock;
2336 }
2337
2338 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002339 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002340
2341 sem_end_lock:
2342 return rc;
2343}
2344
drh6b9d6dd2008-12-03 19:34:47 +00002345/*
drh308c2a52010-05-14 11:30:18 +00002346** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002347** must be either NO_LOCK or SHARED_LOCK.
2348**
2349** If the locking level of the file descriptor is already at or below
2350** the requested locking level, this routine is a no-op.
2351*/
drh308c2a52010-05-14 11:30:18 +00002352static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002353 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002354 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002355
2356 assert( pFile );
2357 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002358 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2359 pFile->eFileLock, getpid()));
2360 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002361
2362 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002363 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002364 return SQLITE_OK;
2365 }
2366
2367 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002368 if (eFileLock==SHARED_LOCK) {
2369 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002370 return SQLITE_OK;
2371 }
2372
2373 /* no, really unlock. */
2374 if ( sem_post(pSem)==-1 ) {
2375 int rc, tErrno = errno;
2376 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2377 if( IS_LOCK_ERROR(rc) ){
2378 pFile->lastErrno = tErrno;
2379 }
2380 return rc;
2381 }
drh308c2a52010-05-14 11:30:18 +00002382 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002383 return SQLITE_OK;
2384}
2385
2386/*
2387 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002388 */
drh734c9862008-11-28 15:37:20 +00002389static int semClose(sqlite3_file *id) {
2390 if( id ){
2391 unixFile *pFile = (unixFile*)id;
2392 semUnlock(id, NO_LOCK);
2393 assert( pFile );
2394 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002395 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002396 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002397 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002398 }
2399 return SQLITE_OK;
2400}
2401
2402#endif /* OS_VXWORKS */
2403/*
2404** Named semaphore locking is only available on VxWorks.
2405**
2406*************** End of the named semaphore lock implementation ****************
2407******************************************************************************/
2408
2409
2410/******************************************************************************
2411*************************** Begin AFP Locking *********************************
2412**
2413** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2414** on Apple Macintosh computers - both OS9 and OSX.
2415**
2416** Third-party implementations of AFP are available. But this code here
2417** only works on OSX.
2418*/
2419
drhd2cb50b2009-01-09 21:41:17 +00002420#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002421/*
2422** The afpLockingContext structure contains all afp lock specific state
2423*/
drhbfe66312006-10-03 17:40:40 +00002424typedef struct afpLockingContext afpLockingContext;
2425struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002426 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002427 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002428};
2429
2430struct ByteRangeLockPB2
2431{
2432 unsigned long long offset; /* offset to first byte to lock */
2433 unsigned long long length; /* nbr of bytes to lock */
2434 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2435 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2436 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2437 int fd; /* file desc to assoc this lock with */
2438};
2439
drhfd131da2007-08-07 17:13:03 +00002440#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002441
drh6b9d6dd2008-12-03 19:34:47 +00002442/*
2443** This is a utility for setting or clearing a bit-range lock on an
2444** AFP filesystem.
2445**
2446** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2447*/
2448static int afpSetLock(
2449 const char *path, /* Name of the file to be locked or unlocked */
2450 unixFile *pFile, /* Open file descriptor on path */
2451 unsigned long long offset, /* First byte to be locked */
2452 unsigned long long length, /* Number of bytes to lock */
2453 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002454){
drh6b9d6dd2008-12-03 19:34:47 +00002455 struct ByteRangeLockPB2 pb;
2456 int err;
drhbfe66312006-10-03 17:40:40 +00002457
2458 pb.unLockFlag = setLockFlag ? 0 : 1;
2459 pb.startEndFlag = 0;
2460 pb.offset = offset;
2461 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002462 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002463
drh308c2a52010-05-14 11:30:18 +00002464 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002465 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002466 offset, length));
drhbfe66312006-10-03 17:40:40 +00002467 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2468 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002469 int rc;
2470 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002471 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2472 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002473#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2474 rc = SQLITE_BUSY;
2475#else
drh734c9862008-11-28 15:37:20 +00002476 rc = sqliteErrorFromPosixError(tErrno,
2477 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002478#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002479 if( IS_LOCK_ERROR(rc) ){
2480 pFile->lastErrno = tErrno;
2481 }
2482 return rc;
drhbfe66312006-10-03 17:40:40 +00002483 } else {
aswift5b1a2562008-08-22 00:22:35 +00002484 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002485 }
2486}
2487
drh6b9d6dd2008-12-03 19:34:47 +00002488/*
2489** This routine checks if there is a RESERVED lock held on the specified
2490** file by this or any other process. If such a lock is held, set *pResOut
2491** to a non-zero value otherwise *pResOut is set to zero. The return value
2492** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2493*/
danielk1977e339d652008-06-28 11:23:00 +00002494static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002495 int rc = SQLITE_OK;
2496 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002497 unixFile *pFile = (unixFile*)id;
2498
aswift5b1a2562008-08-22 00:22:35 +00002499 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2500
2501 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002502 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002503 if( context->reserved ){
2504 *pResOut = 1;
2505 return SQLITE_OK;
2506 }
drh8af6c222010-05-14 12:43:01 +00002507 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002508
2509 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002510 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002511 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002512 }
2513
2514 /* Otherwise see if some other process holds it.
2515 */
aswift5b1a2562008-08-22 00:22:35 +00002516 if( !reserved ){
2517 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002518 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002519 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002520 /* if we succeeded in taking the reserved lock, unlock it to restore
2521 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002522 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002523 } else {
2524 /* if we failed to get the lock then someone else must have it */
2525 reserved = 1;
2526 }
2527 if( IS_LOCK_ERROR(lrc) ){
2528 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002529 }
2530 }
drhbfe66312006-10-03 17:40:40 +00002531
drh7ed97b92010-01-20 13:07:21 +00002532 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002533 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002534
2535 *pResOut = reserved;
2536 return rc;
drhbfe66312006-10-03 17:40:40 +00002537}
2538
drh6b9d6dd2008-12-03 19:34:47 +00002539/*
drh308c2a52010-05-14 11:30:18 +00002540** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002541** of the following:
2542**
2543** (1) SHARED_LOCK
2544** (2) RESERVED_LOCK
2545** (3) PENDING_LOCK
2546** (4) EXCLUSIVE_LOCK
2547**
2548** Sometimes when requesting one lock state, additional lock states
2549** are inserted in between. The locking might fail on one of the later
2550** transitions leaving the lock state different from what it started but
2551** still short of its goal. The following chart shows the allowed
2552** transitions and the inserted intermediate states:
2553**
2554** UNLOCKED -> SHARED
2555** SHARED -> RESERVED
2556** SHARED -> (PENDING) -> EXCLUSIVE
2557** RESERVED -> (PENDING) -> EXCLUSIVE
2558** PENDING -> EXCLUSIVE
2559**
2560** This routine will only increase a lock. Use the sqlite3OsUnlock()
2561** routine to lower a locking level.
2562*/
drh308c2a52010-05-14 11:30:18 +00002563static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002564 int rc = SQLITE_OK;
2565 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002566 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002567 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002568
2569 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002570 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2571 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002572 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002573
drhbfe66312006-10-03 17:40:40 +00002574 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002575 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002576 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002577 */
drh308c2a52010-05-14 11:30:18 +00002578 if( pFile->eFileLock>=eFileLock ){
2579 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2580 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002581 return SQLITE_OK;
2582 }
2583
2584 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002585 ** (1) We never move from unlocked to anything higher than shared lock.
2586 ** (2) SQLite never explicitly requests a pendig lock.
2587 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002588 */
drh308c2a52010-05-14 11:30:18 +00002589 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2590 assert( eFileLock!=PENDING_LOCK );
2591 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002592
drh8af6c222010-05-14 12:43:01 +00002593 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002594 */
drh6c7d5c52008-11-21 20:32:33 +00002595 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002596 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002597
2598 /* If some thread using this PID has a lock via a different unixFile*
2599 ** handle that precludes the requested lock, return BUSY.
2600 */
drh8af6c222010-05-14 12:43:01 +00002601 if( (pFile->eFileLock!=pInode->eFileLock &&
2602 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002603 ){
2604 rc = SQLITE_BUSY;
2605 goto afp_end_lock;
2606 }
2607
2608 /* If a SHARED lock is requested, and some thread using this PID already
2609 ** has a SHARED or RESERVED lock, then increment reference counts and
2610 ** return SQLITE_OK.
2611 */
drh308c2a52010-05-14 11:30:18 +00002612 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002613 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002614 assert( eFileLock==SHARED_LOCK );
2615 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002616 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002617 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002618 pInode->nShared++;
2619 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002620 goto afp_end_lock;
2621 }
drhbfe66312006-10-03 17:40:40 +00002622
2623 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002624 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2625 ** be released.
2626 */
drh308c2a52010-05-14 11:30:18 +00002627 if( eFileLock==SHARED_LOCK
2628 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002629 ){
2630 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002631 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002632 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002633 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002634 goto afp_end_lock;
2635 }
2636 }
2637
2638 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002639 ** operating system calls for the specified lock.
2640 */
drh308c2a52010-05-14 11:30:18 +00002641 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002642 int lrc1, lrc2, lrc1Errno;
2643 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002644
drh8af6c222010-05-14 12:43:01 +00002645 assert( pInode->nShared==0 );
2646 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002647
2648 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002649 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002650 /* note that the quality of the randomness doesn't matter that much */
2651 lk = random();
drh8af6c222010-05-14 12:43:01 +00002652 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002653 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002654 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002655 if( IS_LOCK_ERROR(lrc1) ){
2656 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002657 }
aswift5b1a2562008-08-22 00:22:35 +00002658 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002659 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002660
aswift5b1a2562008-08-22 00:22:35 +00002661 if( IS_LOCK_ERROR(lrc1) ) {
2662 pFile->lastErrno = lrc1Errno;
2663 rc = lrc1;
2664 goto afp_end_lock;
2665 } else if( IS_LOCK_ERROR(lrc2) ){
2666 rc = lrc2;
2667 goto afp_end_lock;
2668 } else if( lrc1 != SQLITE_OK ) {
2669 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002670 } else {
drh308c2a52010-05-14 11:30:18 +00002671 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002672 pInode->nLock++;
2673 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002674 }
drh8af6c222010-05-14 12:43:01 +00002675 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002676 /* We are trying for an exclusive lock but another thread in this
2677 ** same process is still holding a shared lock. */
2678 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002679 }else{
2680 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2681 ** assumed that there is a SHARED or greater lock on the file
2682 ** already.
2683 */
2684 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002685 assert( 0!=pFile->eFileLock );
2686 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002687 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002688 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002689 if( !failed ){
2690 context->reserved = 1;
2691 }
drhbfe66312006-10-03 17:40:40 +00002692 }
drh308c2a52010-05-14 11:30:18 +00002693 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002694 /* Acquire an EXCLUSIVE lock */
2695
2696 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002697 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002698 */
drh6b9d6dd2008-12-03 19:34:47 +00002699 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002700 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002701 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002702 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002703 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002704 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002705 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002706 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002707 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2708 ** a critical I/O error
2709 */
2710 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2711 SQLITE_IOERR_LOCK;
2712 goto afp_end_lock;
2713 }
2714 }else{
aswift5b1a2562008-08-22 00:22:35 +00002715 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002716 }
2717 }
aswift5b1a2562008-08-22 00:22:35 +00002718 if( failed ){
2719 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002720 }
2721 }
2722
2723 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002724 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002725 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002726 }else if( eFileLock==EXCLUSIVE_LOCK ){
2727 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002728 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002729 }
2730
2731afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002732 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002733 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2734 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002735 return rc;
2736}
2737
2738/*
drh308c2a52010-05-14 11:30:18 +00002739** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002740** must be either NO_LOCK or SHARED_LOCK.
2741**
2742** If the locking level of the file descriptor is already at or below
2743** the requested locking level, this routine is a no-op.
2744*/
drh308c2a52010-05-14 11:30:18 +00002745static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002746 int rc = SQLITE_OK;
2747 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002748 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002749 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2750 int skipShared = 0;
2751#ifdef SQLITE_TEST
2752 int h = pFile->h;
2753#endif
drhbfe66312006-10-03 17:40:40 +00002754
2755 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002756 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002757 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002758 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002759
drh308c2a52010-05-14 11:30:18 +00002760 assert( eFileLock<=SHARED_LOCK );
2761 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002762 return SQLITE_OK;
2763 }
drh6c7d5c52008-11-21 20:32:33 +00002764 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002765 pInode = pFile->pInode;
2766 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002767 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002768 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002769 SimulateIOErrorBenign(1);
2770 SimulateIOError( h=(-1) )
2771 SimulateIOErrorBenign(0);
2772
2773#ifndef NDEBUG
2774 /* When reducing a lock such that other processes can start
2775 ** reading the database file again, make sure that the
2776 ** transaction counter was updated if any part of the database
2777 ** file changed. If the transaction counter is not updated,
2778 ** other connections to the same file might not realize that
2779 ** the file has changed and hence might not know to flush their
2780 ** cache. The use of a stale cache can lead to database corruption.
2781 */
2782 assert( pFile->inNormalWrite==0
2783 || pFile->dbUpdate==0
2784 || pFile->transCntrChng==1 );
2785 pFile->inNormalWrite = 0;
2786#endif
aswiftaebf4132008-11-21 00:10:35 +00002787
drh308c2a52010-05-14 11:30:18 +00002788 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002789 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002790 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002791 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002792 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002793 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2794 } else {
2795 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002796 }
2797 }
drh308c2a52010-05-14 11:30:18 +00002798 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002799 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002800 }
drh308c2a52010-05-14 11:30:18 +00002801 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002802 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2803 if( !rc ){
2804 context->reserved = 0;
2805 }
aswiftaebf4132008-11-21 00:10:35 +00002806 }
drh8af6c222010-05-14 12:43:01 +00002807 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2808 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002809 }
aswiftaebf4132008-11-21 00:10:35 +00002810 }
drh308c2a52010-05-14 11:30:18 +00002811 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002812
drh7ed97b92010-01-20 13:07:21 +00002813 /* Decrement the shared lock counter. Release the lock using an
2814 ** OS call only when all threads in this same process have released
2815 ** the lock.
2816 */
drh8af6c222010-05-14 12:43:01 +00002817 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2818 pInode->nShared--;
2819 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002820 SimulateIOErrorBenign(1);
2821 SimulateIOError( h=(-1) )
2822 SimulateIOErrorBenign(0);
2823 if( !skipShared ){
2824 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2825 }
2826 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002827 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002828 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002829 }
2830 }
2831 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002832 pInode->nLock--;
2833 assert( pInode->nLock>=0 );
2834 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002835 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002836 }
2837 }
drhbfe66312006-10-03 17:40:40 +00002838 }
drh7ed97b92010-01-20 13:07:21 +00002839
drh6c7d5c52008-11-21 20:32:33 +00002840 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002841 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002842 return rc;
2843}
2844
2845/*
drh339eb0b2008-03-07 15:34:11 +00002846** Close a file & cleanup AFP specific locking context
2847*/
danielk1977e339d652008-06-28 11:23:00 +00002848static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002849 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002850 if( id ){
2851 unixFile *pFile = (unixFile*)id;
2852 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002853 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002854 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002855 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002856 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002857 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002858 ** the last lock is cleared.
2859 */
dan08da86a2009-08-21 17:18:03 +00002860 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002861 }
danb0ac3e32010-06-16 10:55:42 +00002862 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002863 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002864 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002865 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002866 }
drh7ed97b92010-01-20 13:07:21 +00002867 return rc;
drhbfe66312006-10-03 17:40:40 +00002868}
2869
drhd2cb50b2009-01-09 21:41:17 +00002870#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002871/*
2872** The code above is the AFP lock implementation. The code is specific
2873** to MacOSX and does not work on other unix platforms. No alternative
2874** is available. If you don't compile for a mac, then the "unix-afp"
2875** VFS is not available.
2876**
2877********************* End of the AFP lock implementation **********************
2878******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002879
drh7ed97b92010-01-20 13:07:21 +00002880/******************************************************************************
2881*************************** Begin NFS Locking ********************************/
2882
2883#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2884/*
drh308c2a52010-05-14 11:30:18 +00002885 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002886 ** must be either NO_LOCK or SHARED_LOCK.
2887 **
2888 ** If the locking level of the file descriptor is already at or below
2889 ** the requested locking level, this routine is a no-op.
2890 */
drh308c2a52010-05-14 11:30:18 +00002891static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002892 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002893}
2894
2895#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2896/*
2897** The code above is the NFS lock implementation. The code is specific
2898** to MacOSX and does not work on other unix platforms. No alternative
2899** is available.
2900**
2901********************* End of the NFS lock implementation **********************
2902******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002903
2904/******************************************************************************
2905**************** Non-locking sqlite3_file methods *****************************
2906**
2907** The next division contains implementations for all methods of the
2908** sqlite3_file object other than the locking methods. The locking
2909** methods were defined in divisions above (one locking method per
2910** division). Those methods that are common to all locking modes
2911** are gather together into this division.
2912*/
drhbfe66312006-10-03 17:40:40 +00002913
2914/*
drh734c9862008-11-28 15:37:20 +00002915** Seek to the offset passed as the second argument, then read cnt
2916** bytes into pBuf. Return the number of bytes actually read.
2917**
2918** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2919** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2920** one system to another. Since SQLite does not define USE_PREAD
2921** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2922** See tickets #2741 and #2681.
2923**
2924** To avoid stomping the errno value on a failed read the lastErrno value
2925** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002926*/
drh734c9862008-11-28 15:37:20 +00002927static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2928 int got;
drh7ed97b92010-01-20 13:07:21 +00002929#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002930 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002931#endif
drh734c9862008-11-28 15:37:20 +00002932 TIMER_START;
2933#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002934 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002935 SimulateIOError( got = -1 );
2936#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002937 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002938 SimulateIOError( got = -1 );
2939#else
2940 newOffset = lseek(id->h, offset, SEEK_SET);
2941 SimulateIOError( newOffset-- );
2942 if( newOffset!=offset ){
2943 if( newOffset == -1 ){
2944 ((unixFile*)id)->lastErrno = errno;
2945 }else{
2946 ((unixFile*)id)->lastErrno = 0;
2947 }
2948 return -1;
2949 }
drhe562be52011-03-02 18:01:10 +00002950 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002951#endif
2952 TIMER_END;
2953 if( got<0 ){
2954 ((unixFile*)id)->lastErrno = errno;
2955 }
drh308c2a52010-05-14 11:30:18 +00002956 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002957 return got;
drhbfe66312006-10-03 17:40:40 +00002958}
2959
2960/*
drh734c9862008-11-28 15:37:20 +00002961** Read data from a file into a buffer. Return SQLITE_OK if all
2962** bytes were read successfully and SQLITE_IOERR if anything goes
2963** wrong.
drh339eb0b2008-03-07 15:34:11 +00002964*/
drh734c9862008-11-28 15:37:20 +00002965static int unixRead(
2966 sqlite3_file *id,
2967 void *pBuf,
2968 int amt,
2969 sqlite3_int64 offset
2970){
dan08da86a2009-08-21 17:18:03 +00002971 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002972 int got;
2973 assert( id );
drh08c6d442009-02-09 17:34:07 +00002974
dan08da86a2009-08-21 17:18:03 +00002975 /* If this is a database file (not a journal, master-journal or temp
2976 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002977#if 0
dane946c392009-08-22 11:39:46 +00002978 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002979 || offset>=PENDING_BYTE+512
2980 || offset+amt<=PENDING_BYTE
2981 );
dan7c246102010-04-12 19:00:29 +00002982#endif
drh08c6d442009-02-09 17:34:07 +00002983
dan08da86a2009-08-21 17:18:03 +00002984 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002985 if( got==amt ){
2986 return SQLITE_OK;
2987 }else if( got<0 ){
2988 /* lastErrno set by seekAndRead */
2989 return SQLITE_IOERR_READ;
2990 }else{
dan08da86a2009-08-21 17:18:03 +00002991 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002992 /* Unread parts of the buffer must be zero-filled */
2993 memset(&((char*)pBuf)[got], 0, amt-got);
2994 return SQLITE_IOERR_SHORT_READ;
2995 }
2996}
2997
2998/*
2999** Seek to the offset in id->offset then read cnt bytes into pBuf.
3000** Return the number of bytes actually read. Update the offset.
3001**
3002** To avoid stomping the errno value on a failed write the lastErrno value
3003** is set before returning.
3004*/
3005static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3006 int got;
drh7ed97b92010-01-20 13:07:21 +00003007#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003008 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003009#endif
drh734c9862008-11-28 15:37:20 +00003010 TIMER_START;
3011#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003012 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003013#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003014 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003015#else
3016 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003017 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003018 if( newOffset!=offset ){
3019 if( newOffset == -1 ){
3020 ((unixFile*)id)->lastErrno = errno;
3021 }else{
3022 ((unixFile*)id)->lastErrno = 0;
3023 }
3024 return -1;
3025 }
drhe562be52011-03-02 18:01:10 +00003026 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003027#endif
3028 TIMER_END;
3029 if( got<0 ){
3030 ((unixFile*)id)->lastErrno = errno;
3031 }
3032
drh308c2a52010-05-14 11:30:18 +00003033 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003034 return got;
3035}
3036
3037
3038/*
3039** Write data from a buffer into a file. Return SQLITE_OK on success
3040** or some other error code on failure.
3041*/
3042static int unixWrite(
3043 sqlite3_file *id,
3044 const void *pBuf,
3045 int amt,
3046 sqlite3_int64 offset
3047){
dan08da86a2009-08-21 17:18:03 +00003048 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003049 int wrote = 0;
3050 assert( id );
3051 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003052
dan08da86a2009-08-21 17:18:03 +00003053 /* If this is a database file (not a journal, master-journal or temp
3054 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003055#if 0
dane946c392009-08-22 11:39:46 +00003056 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003057 || offset>=PENDING_BYTE+512
3058 || offset+amt<=PENDING_BYTE
3059 );
dan7c246102010-04-12 19:00:29 +00003060#endif
drh08c6d442009-02-09 17:34:07 +00003061
drh8f941bc2009-01-14 23:03:40 +00003062#ifndef NDEBUG
3063 /* If we are doing a normal write to a database file (as opposed to
3064 ** doing a hot-journal rollback or a write to some file other than a
3065 ** normal database file) then record the fact that the database
3066 ** has changed. If the transaction counter is modified, record that
3067 ** fact too.
3068 */
dan08da86a2009-08-21 17:18:03 +00003069 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003070 pFile->dbUpdate = 1; /* The database has been modified */
3071 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003072 int rc;
drh8f941bc2009-01-14 23:03:40 +00003073 char oldCntr[4];
3074 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003075 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003076 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003077 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003078 pFile->transCntrChng = 1; /* The transaction counter has changed */
3079 }
3080 }
3081 }
3082#endif
3083
dan08da86a2009-08-21 17:18:03 +00003084 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003085 amt -= wrote;
3086 offset += wrote;
3087 pBuf = &((char*)pBuf)[wrote];
3088 }
3089 SimulateIOError(( wrote=(-1), amt=1 ));
3090 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003091
drh734c9862008-11-28 15:37:20 +00003092 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003093 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003094 /* lastErrno set by seekAndWrite */
3095 return SQLITE_IOERR_WRITE;
3096 }else{
dan08da86a2009-08-21 17:18:03 +00003097 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003098 return SQLITE_FULL;
3099 }
3100 }
dan6e09d692010-07-27 18:34:15 +00003101
drh734c9862008-11-28 15:37:20 +00003102 return SQLITE_OK;
3103}
3104
3105#ifdef SQLITE_TEST
3106/*
3107** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003108** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003109*/
3110int sqlite3_sync_count = 0;
3111int sqlite3_fullsync_count = 0;
3112#endif
3113
3114/*
drh89240432009-03-25 01:06:01 +00003115** We do not trust systems to provide a working fdatasync(). Some do.
3116** Others do no. To be safe, we will stick with the (slower) fsync().
3117** If you know that your system does support fdatasync() correctly,
3118** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003119*/
drh89240432009-03-25 01:06:01 +00003120#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003121# define fdatasync fsync
3122#endif
3123
3124/*
3125** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3126** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3127** only available on Mac OS X. But that could change.
3128*/
3129#ifdef F_FULLFSYNC
3130# define HAVE_FULLFSYNC 1
3131#else
3132# define HAVE_FULLFSYNC 0
3133#endif
3134
3135
3136/*
3137** The fsync() system call does not work as advertised on many
3138** unix systems. The following procedure is an attempt to make
3139** it work better.
3140**
3141** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3142** for testing when we want to run through the test suite quickly.
3143** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3144** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3145** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003146**
3147** SQLite sets the dataOnly flag if the size of the file is unchanged.
3148** The idea behind dataOnly is that it should only write the file content
3149** to disk, not the inode. We only set dataOnly if the file size is
3150** unchanged since the file size is part of the inode. However,
3151** Ted Ts'o tells us that fdatasync() will also write the inode if the
3152** file size has changed. The only real difference between fdatasync()
3153** and fsync(), Ted tells us, is that fdatasync() will not flush the
3154** inode if the mtime or owner or other inode attributes have changed.
3155** We only care about the file size, not the other file attributes, so
3156** as far as SQLite is concerned, an fdatasync() is always adequate.
3157** So, we always use fdatasync() if it is available, regardless of
3158** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003159*/
3160static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003161 int rc;
drh734c9862008-11-28 15:37:20 +00003162
3163 /* The following "ifdef/elif/else/" block has the same structure as
3164 ** the one below. It is replicated here solely to avoid cluttering
3165 ** up the real code with the UNUSED_PARAMETER() macros.
3166 */
3167#ifdef SQLITE_NO_SYNC
3168 UNUSED_PARAMETER(fd);
3169 UNUSED_PARAMETER(fullSync);
3170 UNUSED_PARAMETER(dataOnly);
3171#elif HAVE_FULLFSYNC
3172 UNUSED_PARAMETER(dataOnly);
3173#else
3174 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003175 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003176#endif
3177
3178 /* Record the number of times that we do a normal fsync() and
3179 ** FULLSYNC. This is used during testing to verify that this procedure
3180 ** gets called with the correct arguments.
3181 */
3182#ifdef SQLITE_TEST
3183 if( fullSync ) sqlite3_fullsync_count++;
3184 sqlite3_sync_count++;
3185#endif
3186
3187 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3188 ** no-op
3189 */
3190#ifdef SQLITE_NO_SYNC
3191 rc = SQLITE_OK;
3192#elif HAVE_FULLFSYNC
3193 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003194 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003195 }else{
3196 rc = 1;
3197 }
3198 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003199 ** It shouldn't be possible for fullfsync to fail on the local
3200 ** file system (on OSX), so failure indicates that FULLFSYNC
3201 ** isn't supported for this file system. So, attempt an fsync
3202 ** and (for now) ignore the overhead of a superfluous fcntl call.
3203 ** It'd be better to detect fullfsync support once and avoid
3204 ** the fcntl call every time sync is called.
3205 */
drh734c9862008-11-28 15:37:20 +00003206 if( rc ) rc = fsync(fd);
3207
drh7ed97b92010-01-20 13:07:21 +00003208#elif defined(__APPLE__)
3209 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3210 ** so currently we default to the macro that redefines fdatasync to fsync
3211 */
3212 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003213#else
drh0b647ff2009-03-21 14:41:04 +00003214 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003215#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003216 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003217 rc = fsync(fd);
3218 }
drh0b647ff2009-03-21 14:41:04 +00003219#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003220#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3221
3222 if( OS_VXWORKS && rc!= -1 ){
3223 rc = 0;
3224 }
chw97185482008-11-17 08:05:31 +00003225 return rc;
drhbfe66312006-10-03 17:40:40 +00003226}
3227
drh734c9862008-11-28 15:37:20 +00003228/*
3229** Make sure all writes to a particular file are committed to disk.
3230**
3231** If dataOnly==0 then both the file itself and its metadata (file
3232** size, access time, etc) are synced. If dataOnly!=0 then only the
3233** file data is synced.
3234**
3235** Under Unix, also make sure that the directory entry for the file
3236** has been created by fsync-ing the directory that contains the file.
3237** If we do not do this and we encounter a power failure, the directory
3238** entry for the journal might not exist after we reboot. The next
3239** SQLite to access the file will not know that the journal exists (because
3240** the directory entry for the journal was never created) and the transaction
3241** will not roll back - possibly leading to database corruption.
3242*/
3243static int unixSync(sqlite3_file *id, int flags){
3244 int rc;
3245 unixFile *pFile = (unixFile*)id;
3246
3247 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3248 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3249
3250 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3251 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3252 || (flags&0x0F)==SQLITE_SYNC_FULL
3253 );
3254
3255 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3256 ** line is to test that doing so does not cause any problems.
3257 */
3258 SimulateDiskfullError( return SQLITE_FULL );
3259
3260 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003261 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003262 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3263 SimulateIOError( rc=1 );
3264 if( rc ){
3265 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003266 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003267 }
3268 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003269 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3270 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003271#ifndef SQLITE_DISABLE_DIRSYNC
3272 /* The directory sync is only attempted if full_fsync is
3273 ** turned off or unavailable. If a full_fsync occurred above,
3274 ** then the directory sync is superfluous.
3275 */
3276 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3277 /*
3278 ** We have received multiple reports of fsync() returning
3279 ** errors when applied to directories on certain file systems.
3280 ** A failed directory sync is not a big deal. So it seems
3281 ** better to ignore the error. Ticket #1657
3282 */
3283 /* pFile->lastErrno = errno; */
3284 /* return SQLITE_IOERR; */
3285 }
3286#endif
drh0e9365c2011-03-02 02:08:13 +00003287 /* Only need to sync once, so close the directory when we are done */
3288 robust_close(pFile, pFile->dirfd, __LINE__);
3289 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003290 }
3291 return rc;
3292}
3293
3294/*
3295** Truncate an open file to a specified size
3296*/
3297static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003298 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003299 int rc;
dan6e09d692010-07-27 18:34:15 +00003300 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003301 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003302
3303 /* If the user has configured a chunk-size for this file, truncate the
3304 ** file so that it consists of an integer number of chunks (i.e. the
3305 ** actual file size after the operation may be larger than the requested
3306 ** size).
3307 */
3308 if( pFile->szChunk ){
3309 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3310 }
3311
drhff812312011-02-23 13:33:46 +00003312 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003313 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003314 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003315 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003316 }else{
drh3313b142009-11-06 04:13:18 +00003317#ifndef NDEBUG
3318 /* If we are doing a normal write to a database file (as opposed to
3319 ** doing a hot-journal rollback or a write to some file other than a
3320 ** normal database file) and we truncate the file to zero length,
3321 ** that effectively updates the change counter. This might happen
3322 ** when restoring a database using the backup API from a zero-length
3323 ** source.
3324 */
dan6e09d692010-07-27 18:34:15 +00003325 if( pFile->inNormalWrite && nByte==0 ){
3326 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003327 }
3328#endif
3329
drh734c9862008-11-28 15:37:20 +00003330 return SQLITE_OK;
3331 }
3332}
3333
3334/*
3335** Determine the current size of a file in bytes
3336*/
3337static int unixFileSize(sqlite3_file *id, i64 *pSize){
3338 int rc;
3339 struct stat buf;
3340 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003341 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003342 SimulateIOError( rc=1 );
3343 if( rc!=0 ){
3344 ((unixFile*)id)->lastErrno = errno;
3345 return SQLITE_IOERR_FSTAT;
3346 }
3347 *pSize = buf.st_size;
3348
drh8af6c222010-05-14 12:43:01 +00003349 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003350 ** writes a single byte into that file in order to work around a bug
3351 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3352 ** layers, we need to report this file size as zero even though it is
3353 ** really 1. Ticket #3260.
3354 */
3355 if( *pSize==1 ) *pSize = 0;
3356
3357
3358 return SQLITE_OK;
3359}
3360
drhd2cb50b2009-01-09 21:41:17 +00003361#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003362/*
3363** Handler for proxy-locking file-control verbs. Defined below in the
3364** proxying locking division.
3365*/
3366static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003367#endif
drh715ff302008-12-03 22:32:44 +00003368
dan502019c2010-07-28 14:26:17 +00003369/*
3370** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3371** file-control operation.
3372**
3373** If the user has configured a chunk-size for this file, it could be
3374** that the file needs to be extended at this point. Otherwise, the
3375** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3376*/
3377static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3378 if( pFile->szChunk ){
3379 i64 nSize; /* Required file size */
3380 struct stat buf; /* Used to hold return values of fstat() */
3381
drh99ab3b12011-03-02 15:09:07 +00003382 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003383
3384 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3385 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003386
dan502019c2010-07-28 14:26:17 +00003387#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003388 /* The code below is handling the return value of osFallocate()
3389 ** correctly. posix_fallocate() is defined to "returns zero on success,
3390 ** or an error number on failure". See the manpage for details. */
3391 int err;
drhff812312011-02-23 13:33:46 +00003392 do{
dan661d71a2011-03-30 19:08:03 +00003393 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3394 }while( err==EINTR );
3395 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003396#else
3397 /* If the OS does not have posix_fallocate(), fake it. First use
3398 ** ftruncate() to set the file size, then write a single byte to
3399 ** the last byte in each block within the extended region. This
3400 ** is the same technique used by glibc to implement posix_fallocate()
3401 ** on systems that do not have a real fallocate() system call.
3402 */
3403 int nBlk = buf.st_blksize; /* File-system block size */
3404 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003405
drhff812312011-02-23 13:33:46 +00003406 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003407 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003408 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003409 }
3410 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003411 while( iWrite<nSize ){
3412 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3413 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003414 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003415 }
dan502019c2010-07-28 14:26:17 +00003416#endif
3417 }
3418 }
3419
3420 return SQLITE_OK;
3421}
danielk1977ad94b582007-08-20 06:44:22 +00003422
danielk1977e3026632004-06-22 11:29:02 +00003423/*
drh9e33c2c2007-08-31 18:34:59 +00003424** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003425*/
drhcc6bb3e2007-08-31 16:11:35 +00003426static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003427 switch( op ){
3428 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003429 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003430 return SQLITE_OK;
3431 }
drh7708e972008-11-29 00:56:52 +00003432 case SQLITE_LAST_ERRNO: {
3433 *(int*)pArg = ((unixFile*)id)->lastErrno;
3434 return SQLITE_OK;
3435 }
dan6e09d692010-07-27 18:34:15 +00003436 case SQLITE_FCNTL_CHUNK_SIZE: {
3437 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003438 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003439 }
drh9ff27ec2010-05-19 19:26:05 +00003440 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003441 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003442 }
drh8f941bc2009-01-14 23:03:40 +00003443#ifndef NDEBUG
3444 /* The pager calls this method to signal that it has done
3445 ** a rollback and that the database is therefore unchanged and
3446 ** it hence it is OK for the transaction change counter to be
3447 ** unchanged.
3448 */
3449 case SQLITE_FCNTL_DB_UNCHANGED: {
3450 ((unixFile*)id)->dbUpdate = 0;
3451 return SQLITE_OK;
3452 }
3453#endif
drhd2cb50b2009-01-09 21:41:17 +00003454#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003455 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003456 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003457 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003458 }
drhd2cb50b2009-01-09 21:41:17 +00003459#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003460 case SQLITE_FCNTL_SYNC_OMITTED: {
3461 return SQLITE_OK; /* A no-op */
3462 }
drh9e33c2c2007-08-31 18:34:59 +00003463 }
drh0b52b7d2011-01-26 19:46:22 +00003464 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003465}
3466
3467/*
danielk1977a3d4c882007-03-23 10:08:38 +00003468** Return the sector size in bytes of the underlying block device for
3469** the specified file. This is almost always 512 bytes, but may be
3470** larger for some devices.
3471**
3472** SQLite code assumes this function cannot fail. It also assumes that
3473** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003474** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003475** same for both.
3476*/
danielk1977397d65f2008-11-19 11:35:39 +00003477static int unixSectorSize(sqlite3_file *NotUsed){
3478 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003479 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003480}
3481
danielk197790949c22007-08-17 16:50:38 +00003482/*
danielk1977397d65f2008-11-19 11:35:39 +00003483** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003484*/
danielk1977397d65f2008-11-19 11:35:39 +00003485static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3486 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003487 return 0;
3488}
3489
drhd9e5c4f2010-05-12 18:01:39 +00003490#ifndef SQLITE_OMIT_WAL
3491
3492
3493/*
drhd91c68f2010-05-14 14:52:25 +00003494** Object used to represent an shared memory buffer.
3495**
3496** When multiple threads all reference the same wal-index, each thread
3497** has its own unixShm object, but they all point to a single instance
3498** of this unixShmNode object. In other words, each wal-index is opened
3499** only once per process.
3500**
3501** Each unixShmNode object is connected to a single unixInodeInfo object.
3502** We could coalesce this object into unixInodeInfo, but that would mean
3503** every open file that does not use shared memory (in other words, most
3504** open files) would have to carry around this extra information. So
3505** the unixInodeInfo object contains a pointer to this unixShmNode object
3506** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003507**
3508** unixMutexHeld() must be true when creating or destroying
3509** this object or while reading or writing the following fields:
3510**
3511** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003512**
3513** The following fields are read-only after the object is created:
3514**
3515** fid
3516** zFilename
3517**
drhd91c68f2010-05-14 14:52:25 +00003518** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003519** unixMutexHeld() is true when reading or writing any other field
3520** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003521*/
drhd91c68f2010-05-14 14:52:25 +00003522struct unixShmNode {
3523 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003524 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003525 char *zFilename; /* Name of the mmapped file */
3526 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003527 int szRegion; /* Size of shared-memory regions */
3528 int nRegion; /* Size of array apRegion */
3529 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003530 int nRef; /* Number of unixShm objects pointing to this */
3531 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003532#ifdef SQLITE_DEBUG
3533 u8 exclMask; /* Mask of exclusive locks held */
3534 u8 sharedMask; /* Mask of shared locks held */
3535 u8 nextShmId; /* Next available unixShm.id value */
3536#endif
3537};
3538
3539/*
drhd9e5c4f2010-05-12 18:01:39 +00003540** Structure used internally by this VFS to record the state of an
3541** open shared memory connection.
3542**
drhd91c68f2010-05-14 14:52:25 +00003543** The following fields are initialized when this object is created and
3544** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003545**
drhd91c68f2010-05-14 14:52:25 +00003546** unixShm.pFile
3547** unixShm.id
3548**
3549** All other fields are read/write. The unixShm.pFile->mutex must be held
3550** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003551*/
3552struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003553 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3554 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003555 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003556 u16 sharedMask; /* Mask of shared locks held */
3557 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003558#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003559 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003560#endif
3561};
3562
3563/*
drhd9e5c4f2010-05-12 18:01:39 +00003564** Constants used for locking
3565*/
drhbd9676c2010-06-23 17:58:38 +00003566#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003567#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003568
drhd9e5c4f2010-05-12 18:01:39 +00003569/*
drh73b64e42010-05-30 19:55:15 +00003570** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003571**
3572** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3573** otherwise.
3574*/
3575static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003576 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3577 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003578 int ofst, /* First byte of the locking range */
3579 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003580){
3581 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003582 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003583
drhd91c68f2010-05-14 14:52:25 +00003584 /* Access to the unixShmNode object is serialized by the caller */
3585 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003586
drh73b64e42010-05-30 19:55:15 +00003587 /* Shared locks never span more than one byte */
3588 assert( n==1 || lockType!=F_RDLCK );
3589
3590 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003591 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003592
drh3cb93392011-03-12 18:10:44 +00003593 if( pShmNode->h>=0 ){
3594 /* Initialize the locking parameters */
3595 memset(&f, 0, sizeof(f));
3596 f.l_type = lockType;
3597 f.l_whence = SEEK_SET;
3598 f.l_start = ofst;
3599 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003600
drh3cb93392011-03-12 18:10:44 +00003601 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3602 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3603 }
drhd9e5c4f2010-05-12 18:01:39 +00003604
3605 /* Update the global lock state and do debug tracing */
3606#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003607 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003608 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003609 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003610 if( rc==SQLITE_OK ){
3611 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003612 OSTRACE(("unlock %d ok", ofst));
3613 pShmNode->exclMask &= ~mask;
3614 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003615 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003616 OSTRACE(("read-lock %d ok", ofst));
3617 pShmNode->exclMask &= ~mask;
3618 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003619 }else{
3620 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003621 OSTRACE(("write-lock %d ok", ofst));
3622 pShmNode->exclMask |= mask;
3623 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003624 }
3625 }else{
3626 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003627 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003628 }else if( lockType==F_RDLCK ){
3629 OSTRACE(("read-lock failed"));
3630 }else{
3631 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003632 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003633 }
3634 }
drh20e1f082010-05-31 16:10:12 +00003635 OSTRACE((" - afterwards %03x,%03x\n",
3636 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003637 }
drhd9e5c4f2010-05-12 18:01:39 +00003638#endif
3639
3640 return rc;
3641}
3642
drhd9e5c4f2010-05-12 18:01:39 +00003643
3644/*
drhd91c68f2010-05-14 14:52:25 +00003645** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003646**
3647** This is not a VFS shared-memory method; it is a utility function called
3648** by VFS shared-memory methods.
3649*/
drhd91c68f2010-05-14 14:52:25 +00003650static void unixShmPurge(unixFile *pFd){
3651 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003652 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003653 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003654 int i;
drhd91c68f2010-05-14 14:52:25 +00003655 assert( p->pInode==pFd->pInode );
3656 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003657 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003658 if( p->h>=0 ){
3659 munmap(p->apRegion[i], p->szRegion);
3660 }else{
3661 sqlite3_free(p->apRegion[i]);
3662 }
dan13a3cb82010-06-11 19:04:21 +00003663 }
dan18801912010-06-14 14:07:50 +00003664 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003665 if( p->h>=0 ){
3666 robust_close(pFd, p->h, __LINE__);
3667 p->h = -1;
3668 }
drhd91c68f2010-05-14 14:52:25 +00003669 p->pInode->pShmNode = 0;
3670 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003671 }
3672}
3673
3674/*
danda9fe0c2010-07-13 18:44:03 +00003675** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003676** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003677**
drh7234c6d2010-06-19 15:10:09 +00003678** The file used to implement shared-memory is in the same directory
3679** as the open database file and has the same name as the open database
3680** file with the "-shm" suffix added. For example, if the database file
3681** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003682** for shared memory will be called "/home/user1/config.db-shm".
3683**
3684** Another approach to is to use files in /dev/shm or /dev/tmp or an
3685** some other tmpfs mount. But if a file in a different directory
3686** from the database file is used, then differing access permissions
3687** or a chroot() might cause two different processes on the same
3688** database to end up using different files for shared memory -
3689** meaning that their memory would not really be shared - resulting
3690** in database corruption. Nevertheless, this tmpfs file usage
3691** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3692** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3693** option results in an incompatible build of SQLite; builds of SQLite
3694** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3695** same database file at the same time, database corruption will likely
3696** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3697** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003698**
3699** When opening a new shared-memory file, if no other instances of that
3700** file are currently open, in this process or in other processes, then
3701** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003702**
3703** If the original database file (pDbFd) is using the "unix-excl" VFS
3704** that means that an exclusive lock is held on the database file and
3705** that no other processes are able to read or write the database. In
3706** that case, we do not really need shared memory. No shared memory
3707** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003708*/
danda9fe0c2010-07-13 18:44:03 +00003709static int unixOpenSharedMemory(unixFile *pDbFd){
3710 struct unixShm *p = 0; /* The connection to be opened */
3711 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3712 int rc; /* Result code */
3713 unixInodeInfo *pInode; /* The inode of fd */
3714 char *zShmFilename; /* Name of the file used for SHM */
3715 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003716
danda9fe0c2010-07-13 18:44:03 +00003717 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003718 p = sqlite3_malloc( sizeof(*p) );
3719 if( p==0 ) return SQLITE_NOMEM;
3720 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003721 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003722
danda9fe0c2010-07-13 18:44:03 +00003723 /* Check to see if a unixShmNode object already exists. Reuse an existing
3724 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003725 */
3726 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003727 pInode = pDbFd->pInode;
3728 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003729 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003730 struct stat sStat; /* fstat() info for database file */
3731
3732 /* Call fstat() to figure out the permissions on the database file. If
3733 ** a new *-shm file is created, an attempt will be made to create it
3734 ** with the same permissions. The actual permissions the file is created
3735 ** with are subject to the current umask setting.
3736 */
drh3cb93392011-03-12 18:10:44 +00003737 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003738 rc = SQLITE_IOERR_FSTAT;
3739 goto shm_open_err;
3740 }
3741
drha4ced192010-07-15 18:32:40 +00003742#ifdef SQLITE_SHM_DIRECTORY
3743 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3744#else
drh7234c6d2010-06-19 15:10:09 +00003745 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003746#endif
drh7234c6d2010-06-19 15:10:09 +00003747 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003748 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003749 rc = SQLITE_NOMEM;
3750 goto shm_open_err;
3751 }
drhd91c68f2010-05-14 14:52:25 +00003752 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003753 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003754#ifdef SQLITE_SHM_DIRECTORY
3755 sqlite3_snprintf(nShmFilename, zShmFilename,
3756 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3757 (u32)sStat.st_ino, (u32)sStat.st_dev);
3758#else
drh7234c6d2010-06-19 15:10:09 +00003759 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003760#endif
drhd91c68f2010-05-14 14:52:25 +00003761 pShmNode->h = -1;
3762 pDbFd->pInode->pShmNode = pShmNode;
3763 pShmNode->pInode = pDbFd->pInode;
3764 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3765 if( pShmNode->mutex==0 ){
3766 rc = SQLITE_NOMEM;
3767 goto shm_open_err;
3768 }
drhd9e5c4f2010-05-12 18:01:39 +00003769
drh3cb93392011-03-12 18:10:44 +00003770 if( pInode->bProcessLock==0 ){
3771 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3772 (sStat.st_mode & 0777));
3773 if( pShmNode->h<0 ){
3774 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3775 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003776 }
drh3cb93392011-03-12 18:10:44 +00003777
3778 /* Check to see if another process is holding the dead-man switch.
3779 ** If not, truncate the file to zero length.
3780 */
3781 rc = SQLITE_OK;
3782 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3783 if( robust_ftruncate(pShmNode->h, 0) ){
3784 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3785 }
3786 }
3787 if( rc==SQLITE_OK ){
3788 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3789 }
3790 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003791 }
drhd9e5c4f2010-05-12 18:01:39 +00003792 }
3793
drhd91c68f2010-05-14 14:52:25 +00003794 /* Make the new connection a child of the unixShmNode */
3795 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003796#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003797 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003798#endif
drhd91c68f2010-05-14 14:52:25 +00003799 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003800 pDbFd->pShm = p;
3801 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003802
3803 /* The reference count on pShmNode has already been incremented under
3804 ** the cover of the unixEnterMutex() mutex and the pointer from the
3805 ** new (struct unixShm) object to the pShmNode has been set. All that is
3806 ** left to do is to link the new object into the linked list starting
3807 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3808 ** mutex.
3809 */
3810 sqlite3_mutex_enter(pShmNode->mutex);
3811 p->pNext = pShmNode->pFirst;
3812 pShmNode->pFirst = p;
3813 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003814 return SQLITE_OK;
3815
3816 /* Jump here on any error */
3817shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003818 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003819 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003820 unixLeaveMutex();
3821 return rc;
3822}
3823
3824/*
danda9fe0c2010-07-13 18:44:03 +00003825** This function is called to obtain a pointer to region iRegion of the
3826** shared-memory associated with the database file fd. Shared-memory regions
3827** are numbered starting from zero. Each shared-memory region is szRegion
3828** bytes in size.
3829**
3830** If an error occurs, an error code is returned and *pp is set to NULL.
3831**
3832** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3833** region has not been allocated (by any client, including one running in a
3834** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3835** bExtend is non-zero and the requested shared-memory region has not yet
3836** been allocated, it is allocated by this function.
3837**
3838** If the shared-memory region has already been allocated or is allocated by
3839** this call as described above, then it is mapped into this processes
3840** address space (if it is not already), *pp is set to point to the mapped
3841** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003842*/
danda9fe0c2010-07-13 18:44:03 +00003843static int unixShmMap(
3844 sqlite3_file *fd, /* Handle open on database file */
3845 int iRegion, /* Region to retrieve */
3846 int szRegion, /* Size of regions */
3847 int bExtend, /* True to extend file if necessary */
3848 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003849){
danda9fe0c2010-07-13 18:44:03 +00003850 unixFile *pDbFd = (unixFile*)fd;
3851 unixShm *p;
3852 unixShmNode *pShmNode;
3853 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003854
danda9fe0c2010-07-13 18:44:03 +00003855 /* If the shared-memory file has not yet been opened, open it now. */
3856 if( pDbFd->pShm==0 ){
3857 rc = unixOpenSharedMemory(pDbFd);
3858 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003859 }
drhd9e5c4f2010-05-12 18:01:39 +00003860
danda9fe0c2010-07-13 18:44:03 +00003861 p = pDbFd->pShm;
3862 pShmNode = p->pShmNode;
3863 sqlite3_mutex_enter(pShmNode->mutex);
3864 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003865 assert( pShmNode->pInode==pDbFd->pInode );
3866 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3867 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003868
3869 if( pShmNode->nRegion<=iRegion ){
3870 char **apNew; /* New apRegion[] array */
3871 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3872 struct stat sStat; /* Used by fstat() */
3873
3874 pShmNode->szRegion = szRegion;
3875
drh3cb93392011-03-12 18:10:44 +00003876 if( pShmNode->h>=0 ){
3877 /* The requested region is not mapped into this processes address space.
3878 ** Check to see if it has been allocated (i.e. if the wal-index file is
3879 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003880 */
drh3cb93392011-03-12 18:10:44 +00003881 if( osFstat(pShmNode->h, &sStat) ){
3882 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003883 goto shmpage_out;
3884 }
drh3cb93392011-03-12 18:10:44 +00003885
3886 if( sStat.st_size<nByte ){
3887 /* The requested memory region does not exist. If bExtend is set to
3888 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3889 **
3890 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3891 ** the requested memory region.
3892 */
3893 if( !bExtend ) goto shmpage_out;
3894 if( robust_ftruncate(pShmNode->h, nByte) ){
3895 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3896 pShmNode->zFilename);
3897 goto shmpage_out;
3898 }
3899 }
danda9fe0c2010-07-13 18:44:03 +00003900 }
3901
3902 /* Map the requested memory region into this processes address space. */
3903 apNew = (char **)sqlite3_realloc(
3904 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3905 );
3906 if( !apNew ){
3907 rc = SQLITE_IOERR_NOMEM;
3908 goto shmpage_out;
3909 }
3910 pShmNode->apRegion = apNew;
3911 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003912 void *pMem;
3913 if( pShmNode->h>=0 ){
3914 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3915 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3916 );
3917 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003918 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003919 goto shmpage_out;
3920 }
3921 }else{
3922 pMem = sqlite3_malloc(szRegion);
3923 if( pMem==0 ){
3924 rc = SQLITE_NOMEM;
3925 goto shmpage_out;
3926 }
3927 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003928 }
3929 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3930 pShmNode->nRegion++;
3931 }
3932 }
3933
3934shmpage_out:
3935 if( pShmNode->nRegion>iRegion ){
3936 *pp = pShmNode->apRegion[iRegion];
3937 }else{
3938 *pp = 0;
3939 }
3940 sqlite3_mutex_leave(pShmNode->mutex);
3941 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003942}
3943
3944/*
drhd9e5c4f2010-05-12 18:01:39 +00003945** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003946**
3947** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3948** different here than in posix. In xShmLock(), one can go from unlocked
3949** to shared and back or from unlocked to exclusive and back. But one may
3950** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003951*/
3952static int unixShmLock(
3953 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003954 int ofst, /* First lock to acquire or release */
3955 int n, /* Number of locks to acquire or release */
3956 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003957){
drh73b64e42010-05-30 19:55:15 +00003958 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3959 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3960 unixShm *pX; /* For looping over all siblings */
3961 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3962 int rc = SQLITE_OK; /* Result code */
3963 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003964
drhd91c68f2010-05-14 14:52:25 +00003965 assert( pShmNode==pDbFd->pInode->pShmNode );
3966 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003967 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003968 assert( n>=1 );
3969 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3970 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3971 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3972 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3973 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003974 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3975 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003976
drhc99597c2010-05-31 01:41:15 +00003977 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003978 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003979 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003980 if( flags & SQLITE_SHM_UNLOCK ){
3981 u16 allMask = 0; /* Mask of locks held by siblings */
3982
3983 /* See if any siblings hold this same lock */
3984 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3985 if( pX==p ) continue;
3986 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3987 allMask |= pX->sharedMask;
3988 }
3989
3990 /* Unlock the system-level locks */
3991 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003992 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003993 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003994 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003995 }
drh73b64e42010-05-30 19:55:15 +00003996
3997 /* Undo the local locks */
3998 if( rc==SQLITE_OK ){
3999 p->exclMask &= ~mask;
4000 p->sharedMask &= ~mask;
4001 }
4002 }else if( flags & SQLITE_SHM_SHARED ){
4003 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4004
4005 /* Find out which shared locks are already held by sibling connections.
4006 ** If any sibling already holds an exclusive lock, go ahead and return
4007 ** SQLITE_BUSY.
4008 */
4009 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004010 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004011 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004012 break;
4013 }
4014 allShared |= pX->sharedMask;
4015 }
4016
4017 /* Get shared locks at the system level, if necessary */
4018 if( rc==SQLITE_OK ){
4019 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004020 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004021 }else{
drh73b64e42010-05-30 19:55:15 +00004022 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004023 }
drhd9e5c4f2010-05-12 18:01:39 +00004024 }
drh73b64e42010-05-30 19:55:15 +00004025
4026 /* Get the local shared locks */
4027 if( rc==SQLITE_OK ){
4028 p->sharedMask |= mask;
4029 }
4030 }else{
4031 /* Make sure no sibling connections hold locks that will block this
4032 ** lock. If any do, return SQLITE_BUSY right away.
4033 */
4034 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004035 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4036 rc = SQLITE_BUSY;
4037 break;
4038 }
4039 }
4040
4041 /* Get the exclusive locks at the system level. Then if successful
4042 ** also mark the local connection as being locked.
4043 */
4044 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004045 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004046 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004047 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004048 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004049 }
drhd9e5c4f2010-05-12 18:01:39 +00004050 }
4051 }
drhd91c68f2010-05-14 14:52:25 +00004052 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004053 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4054 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004055 return rc;
4056}
4057
drh286a2882010-05-20 23:51:06 +00004058/*
4059** Implement a memory barrier or memory fence on shared memory.
4060**
4061** All loads and stores begun before the barrier must complete before
4062** any load or store begun after the barrier.
4063*/
4064static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004065 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004066){
drhff828942010-06-26 21:34:06 +00004067 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004068 unixEnterMutex();
4069 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004070}
4071
dan18801912010-06-14 14:07:50 +00004072/*
danda9fe0c2010-07-13 18:44:03 +00004073** Close a connection to shared-memory. Delete the underlying
4074** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004075**
4076** If there is no shared memory associated with the connection then this
4077** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004078*/
danda9fe0c2010-07-13 18:44:03 +00004079static int unixShmUnmap(
4080 sqlite3_file *fd, /* The underlying database file */
4081 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004082){
danda9fe0c2010-07-13 18:44:03 +00004083 unixShm *p; /* The connection to be closed */
4084 unixShmNode *pShmNode; /* The underlying shared-memory file */
4085 unixShm **pp; /* For looping over sibling connections */
4086 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004087
danda9fe0c2010-07-13 18:44:03 +00004088 pDbFd = (unixFile*)fd;
4089 p = pDbFd->pShm;
4090 if( p==0 ) return SQLITE_OK;
4091 pShmNode = p->pShmNode;
4092
4093 assert( pShmNode==pDbFd->pInode->pShmNode );
4094 assert( pShmNode->pInode==pDbFd->pInode );
4095
4096 /* Remove connection p from the set of connections associated
4097 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004098 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004099 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4100 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004101
danda9fe0c2010-07-13 18:44:03 +00004102 /* Free the connection p */
4103 sqlite3_free(p);
4104 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004105 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004106
4107 /* If pShmNode->nRef has reached 0, then close the underlying
4108 ** shared-memory file, too */
4109 unixEnterMutex();
4110 assert( pShmNode->nRef>0 );
4111 pShmNode->nRef--;
4112 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004113 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004114 unixShmPurge(pDbFd);
4115 }
4116 unixLeaveMutex();
4117
4118 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004119}
drh286a2882010-05-20 23:51:06 +00004120
danda9fe0c2010-07-13 18:44:03 +00004121
drhd9e5c4f2010-05-12 18:01:39 +00004122#else
drh6b017cc2010-06-14 18:01:46 +00004123# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004124# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004125# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004126# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004127#endif /* #ifndef SQLITE_OMIT_WAL */
4128
drh734c9862008-11-28 15:37:20 +00004129/*
4130** Here ends the implementation of all sqlite3_file methods.
4131**
4132********************** End sqlite3_file Methods *******************************
4133******************************************************************************/
4134
4135/*
drh6b9d6dd2008-12-03 19:34:47 +00004136** This division contains definitions of sqlite3_io_methods objects that
4137** implement various file locking strategies. It also contains definitions
4138** of "finder" functions. A finder-function is used to locate the appropriate
4139** sqlite3_io_methods object for a particular database file. The pAppData
4140** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4141** the correct finder-function for that VFS.
4142**
4143** Most finder functions return a pointer to a fixed sqlite3_io_methods
4144** object. The only interesting finder-function is autolockIoFinder, which
4145** looks at the filesystem type and tries to guess the best locking
4146** strategy from that.
4147**
drh1875f7a2008-12-08 18:19:17 +00004148** For finder-funtion F, two objects are created:
4149**
4150** (1) The real finder-function named "FImpt()".
4151**
dane946c392009-08-22 11:39:46 +00004152** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004153**
4154**
4155** A pointer to the F pointer is used as the pAppData value for VFS
4156** objects. We have to do this instead of letting pAppData point
4157** directly at the finder-function since C90 rules prevent a void*
4158** from be cast into a function pointer.
4159**
drh6b9d6dd2008-12-03 19:34:47 +00004160**
drh7708e972008-11-29 00:56:52 +00004161** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004162**
drh7708e972008-11-29 00:56:52 +00004163** * A constant sqlite3_io_methods object call METHOD that has locking
4164** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4165**
4166** * An I/O method finder function called FINDER that returns a pointer
4167** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004168*/
drhd9e5c4f2010-05-12 18:01:39 +00004169#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004170static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004171 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004172 CLOSE, /* xClose */ \
4173 unixRead, /* xRead */ \
4174 unixWrite, /* xWrite */ \
4175 unixTruncate, /* xTruncate */ \
4176 unixSync, /* xSync */ \
4177 unixFileSize, /* xFileSize */ \
4178 LOCK, /* xLock */ \
4179 UNLOCK, /* xUnlock */ \
4180 CKLOCK, /* xCheckReservedLock */ \
4181 unixFileControl, /* xFileControl */ \
4182 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004183 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004184 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004185 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004186 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004187 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004188}; \
drh0c2694b2009-09-03 16:23:44 +00004189static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4190 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004191 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004192} \
drh0c2694b2009-09-03 16:23:44 +00004193static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004194 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004195
4196/*
4197** Here are all of the sqlite3_io_methods objects for each of the
4198** locking strategies. Functions that return pointers to these methods
4199** are also created.
4200*/
4201IOMETHODS(
4202 posixIoFinder, /* Finder function name */
4203 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004204 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004205 unixClose, /* xClose method */
4206 unixLock, /* xLock method */
4207 unixUnlock, /* xUnlock method */
4208 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004209)
drh7708e972008-11-29 00:56:52 +00004210IOMETHODS(
4211 nolockIoFinder, /* Finder function name */
4212 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004213 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004214 nolockClose, /* xClose method */
4215 nolockLock, /* xLock method */
4216 nolockUnlock, /* xUnlock method */
4217 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004218)
drh7708e972008-11-29 00:56:52 +00004219IOMETHODS(
4220 dotlockIoFinder, /* Finder function name */
4221 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004222 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004223 dotlockClose, /* xClose method */
4224 dotlockLock, /* xLock method */
4225 dotlockUnlock, /* xUnlock method */
4226 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004227)
drh7708e972008-11-29 00:56:52 +00004228
chw78a13182009-04-07 05:35:03 +00004229#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004230IOMETHODS(
4231 flockIoFinder, /* Finder function name */
4232 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004233 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004234 flockClose, /* xClose method */
4235 flockLock, /* xLock method */
4236 flockUnlock, /* xUnlock method */
4237 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004238)
drh7708e972008-11-29 00:56:52 +00004239#endif
4240
drh6c7d5c52008-11-21 20:32:33 +00004241#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004242IOMETHODS(
4243 semIoFinder, /* Finder function name */
4244 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004245 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004246 semClose, /* xClose method */
4247 semLock, /* xLock method */
4248 semUnlock, /* xUnlock method */
4249 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004250)
aswiftaebf4132008-11-21 00:10:35 +00004251#endif
drh7708e972008-11-29 00:56:52 +00004252
drhd2cb50b2009-01-09 21:41:17 +00004253#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004254IOMETHODS(
4255 afpIoFinder, /* Finder function name */
4256 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004257 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004258 afpClose, /* xClose method */
4259 afpLock, /* xLock method */
4260 afpUnlock, /* xUnlock method */
4261 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004262)
drh715ff302008-12-03 22:32:44 +00004263#endif
4264
4265/*
4266** The proxy locking method is a "super-method" in the sense that it
4267** opens secondary file descriptors for the conch and lock files and
4268** it uses proxy, dot-file, AFP, and flock() locking methods on those
4269** secondary files. For this reason, the division that implements
4270** proxy locking is located much further down in the file. But we need
4271** to go ahead and define the sqlite3_io_methods and finder function
4272** for proxy locking here. So we forward declare the I/O methods.
4273*/
drhd2cb50b2009-01-09 21:41:17 +00004274#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004275static int proxyClose(sqlite3_file*);
4276static int proxyLock(sqlite3_file*, int);
4277static int proxyUnlock(sqlite3_file*, int);
4278static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004279IOMETHODS(
4280 proxyIoFinder, /* Finder function name */
4281 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004282 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004283 proxyClose, /* xClose method */
4284 proxyLock, /* xLock method */
4285 proxyUnlock, /* xUnlock method */
4286 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004287)
aswiftaebf4132008-11-21 00:10:35 +00004288#endif
drh7708e972008-11-29 00:56:52 +00004289
drh7ed97b92010-01-20 13:07:21 +00004290/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4291#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4292IOMETHODS(
4293 nfsIoFinder, /* Finder function name */
4294 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004295 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004296 unixClose, /* xClose method */
4297 unixLock, /* xLock method */
4298 nfsUnlock, /* xUnlock method */
4299 unixCheckReservedLock /* xCheckReservedLock method */
4300)
4301#endif
drh7708e972008-11-29 00:56:52 +00004302
drhd2cb50b2009-01-09 21:41:17 +00004303#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004304/*
drh6b9d6dd2008-12-03 19:34:47 +00004305** This "finder" function attempts to determine the best locking strategy
4306** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004307** object that implements that strategy.
4308**
4309** This is for MacOSX only.
4310*/
drh1875f7a2008-12-08 18:19:17 +00004311static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004312 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004313 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004314){
4315 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004316 const char *zFilesystem; /* Filesystem type name */
4317 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004318 } aMap[] = {
4319 { "hfs", &posixIoMethods },
4320 { "ufs", &posixIoMethods },
4321 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004322 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004323 { "webdav", &nolockIoMethods },
4324 { 0, 0 }
4325 };
4326 int i;
4327 struct statfs fsInfo;
4328 struct flock lockInfo;
4329
4330 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004331 /* If filePath==NULL that means we are dealing with a transient file
4332 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004333 return &nolockIoMethods;
4334 }
4335 if( statfs(filePath, &fsInfo) != -1 ){
4336 if( fsInfo.f_flags & MNT_RDONLY ){
4337 return &nolockIoMethods;
4338 }
4339 for(i=0; aMap[i].zFilesystem; i++){
4340 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4341 return aMap[i].pMethods;
4342 }
4343 }
4344 }
4345
4346 /* Default case. Handles, amongst others, "nfs".
4347 ** Test byte-range lock using fcntl(). If the call succeeds,
4348 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004349 */
drh7708e972008-11-29 00:56:52 +00004350 lockInfo.l_len = 1;
4351 lockInfo.l_start = 0;
4352 lockInfo.l_whence = SEEK_SET;
4353 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004354 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004355 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4356 return &nfsIoMethods;
4357 } else {
4358 return &posixIoMethods;
4359 }
drh7708e972008-11-29 00:56:52 +00004360 }else{
4361 return &dotlockIoMethods;
4362 }
4363}
drh0c2694b2009-09-03 16:23:44 +00004364static const sqlite3_io_methods
4365 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004366
drhd2cb50b2009-01-09 21:41:17 +00004367#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004368
chw78a13182009-04-07 05:35:03 +00004369#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4370/*
4371** This "finder" function attempts to determine the best locking strategy
4372** for the database file "filePath". It then returns the sqlite3_io_methods
4373** object that implements that strategy.
4374**
4375** This is for VXWorks only.
4376*/
4377static const sqlite3_io_methods *autolockIoFinderImpl(
4378 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004379 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004380){
4381 struct flock lockInfo;
4382
4383 if( !filePath ){
4384 /* If filePath==NULL that means we are dealing with a transient file
4385 ** that does not need to be locked. */
4386 return &nolockIoMethods;
4387 }
4388
4389 /* Test if fcntl() is supported and use POSIX style locks.
4390 ** Otherwise fall back to the named semaphore method.
4391 */
4392 lockInfo.l_len = 1;
4393 lockInfo.l_start = 0;
4394 lockInfo.l_whence = SEEK_SET;
4395 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004396 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004397 return &posixIoMethods;
4398 }else{
4399 return &semIoMethods;
4400 }
4401}
drh0c2694b2009-09-03 16:23:44 +00004402static const sqlite3_io_methods
4403 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004404
4405#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4406
drh7708e972008-11-29 00:56:52 +00004407/*
4408** An abstract type for a pointer to a IO method finder function:
4409*/
drh0c2694b2009-09-03 16:23:44 +00004410typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004411
aswiftaebf4132008-11-21 00:10:35 +00004412
drh734c9862008-11-28 15:37:20 +00004413/****************************************************************************
4414**************************** sqlite3_vfs methods ****************************
4415**
4416** This division contains the implementation of methods on the
4417** sqlite3_vfs object.
4418*/
4419
danielk1977a3d4c882007-03-23 10:08:38 +00004420/*
danielk1977e339d652008-06-28 11:23:00 +00004421** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004422*/
4423static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004424 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004425 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004426 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004427 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004428 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004429 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004430 int isDelete, /* Delete on close if true */
4431 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004432){
drh7708e972008-11-29 00:56:52 +00004433 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004434 unixFile *pNew = (unixFile *)pId;
4435 int rc = SQLITE_OK;
4436
drh8af6c222010-05-14 12:43:01 +00004437 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004438
dane946c392009-08-22 11:39:46 +00004439 /* Parameter isDelete is only used on vxworks. Express this explicitly
4440 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004441 */
drh7708e972008-11-29 00:56:52 +00004442 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004443
dan00157392010-10-05 11:33:15 +00004444 /* Usually the path zFilename should not be a relative pathname. The
4445 ** exception is when opening the proxy "conch" file in builds that
4446 ** include the special Apple locking styles.
4447 */
dan00157392010-10-05 11:33:15 +00004448#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004449 assert( zFilename==0 || zFilename[0]=='/'
4450 || pVfs->pAppData==(void*)&autolockIoFinder );
4451#else
4452 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004453#endif
dan00157392010-10-05 11:33:15 +00004454
drh308c2a52010-05-14 11:30:18 +00004455 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004456 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004457 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004458 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004459 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4460 pNew->ctrlFlags = UNIXFILE_EXCL;
4461 }else{
4462 pNew->ctrlFlags = 0;
4463 }
drh77197112011-03-15 19:08:48 +00004464 if( isReadOnly ){
4465 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4466 }
drh339eb0b2008-03-07 15:34:11 +00004467
drh6c7d5c52008-11-21 20:32:33 +00004468#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004469 pNew->pId = vxworksFindFileId(zFilename);
4470 if( pNew->pId==0 ){
4471 noLock = 1;
4472 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004473 }
4474#endif
4475
drhda0e7682008-07-30 15:27:54 +00004476 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004477 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004478 }else{
drh0c2694b2009-09-03 16:23:44 +00004479 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004480#if SQLITE_ENABLE_LOCKING_STYLE
4481 /* Cache zFilename in the locking context (AFP and dotlock override) for
4482 ** proxyLock activation is possible (remote proxy is based on db name)
4483 ** zFilename remains valid until file is closed, to support */
4484 pNew->lockingContext = (void*)zFilename;
4485#endif
drhda0e7682008-07-30 15:27:54 +00004486 }
danielk1977e339d652008-06-28 11:23:00 +00004487
drh7ed97b92010-01-20 13:07:21 +00004488 if( pLockingStyle == &posixIoMethods
4489#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4490 || pLockingStyle == &nfsIoMethods
4491#endif
4492 ){
drh7708e972008-11-29 00:56:52 +00004493 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004494 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004495 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004496 /* If an error occured in findInodeInfo(), close the file descriptor
4497 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004498 ** in two scenarios:
4499 **
4500 ** (a) A call to fstat() failed.
4501 ** (b) A malloc failed.
4502 **
4503 ** Scenario (b) may only occur if the process is holding no other
4504 ** file descriptors open on the same file. If there were other file
4505 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004506 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004507 ** handle h - as it is guaranteed that no posix locks will be released
4508 ** by doing so.
4509 **
4510 ** If scenario (a) caused the error then things are not so safe. The
4511 ** implicit assumption here is that if fstat() fails, things are in
4512 ** such bad shape that dropping a lock or two doesn't matter much.
4513 */
drh0e9365c2011-03-02 02:08:13 +00004514 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004515 h = -1;
4516 }
drh7708e972008-11-29 00:56:52 +00004517 unixLeaveMutex();
4518 }
danielk1977e339d652008-06-28 11:23:00 +00004519
drhd2cb50b2009-01-09 21:41:17 +00004520#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004521 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004522 /* AFP locking uses the file path so it needs to be included in
4523 ** the afpLockingContext.
4524 */
4525 afpLockingContext *pCtx;
4526 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4527 if( pCtx==0 ){
4528 rc = SQLITE_NOMEM;
4529 }else{
4530 /* NB: zFilename exists and remains valid until the file is closed
4531 ** according to requirement F11141. So we do not need to make a
4532 ** copy of the filename. */
4533 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004534 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004535 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004536 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004537 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004538 if( rc!=SQLITE_OK ){
4539 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004540 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004541 h = -1;
4542 }
drh7708e972008-11-29 00:56:52 +00004543 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004544 }
drh7708e972008-11-29 00:56:52 +00004545 }
4546#endif
danielk1977e339d652008-06-28 11:23:00 +00004547
drh7708e972008-11-29 00:56:52 +00004548 else if( pLockingStyle == &dotlockIoMethods ){
4549 /* Dotfile locking uses the file path so it needs to be included in
4550 ** the dotlockLockingContext
4551 */
4552 char *zLockFile;
4553 int nFilename;
drhea678832008-12-10 19:26:22 +00004554 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004555 zLockFile = (char *)sqlite3_malloc(nFilename);
4556 if( zLockFile==0 ){
4557 rc = SQLITE_NOMEM;
4558 }else{
4559 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004560 }
drh7708e972008-11-29 00:56:52 +00004561 pNew->lockingContext = zLockFile;
4562 }
danielk1977e339d652008-06-28 11:23:00 +00004563
drh6c7d5c52008-11-21 20:32:33 +00004564#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004565 else if( pLockingStyle == &semIoMethods ){
4566 /* Named semaphore locking uses the file path so it needs to be
4567 ** included in the semLockingContext
4568 */
4569 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004570 rc = findInodeInfo(pNew, &pNew->pInode);
4571 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4572 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004573 int n;
drh2238dcc2009-08-27 17:56:20 +00004574 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004575 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004576 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004577 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004578 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4579 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004580 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004581 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004582 }
chw97185482008-11-17 08:05:31 +00004583 }
drh7708e972008-11-29 00:56:52 +00004584 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004585 }
drh7708e972008-11-29 00:56:52 +00004586#endif
aswift5b1a2562008-08-22 00:22:35 +00004587
4588 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004589#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004590 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004591 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004592 h = -1;
chw97185482008-11-17 08:05:31 +00004593 unlink(zFilename);
4594 isDelete = 0;
4595 }
4596 pNew->isDelete = isDelete;
4597#endif
danielk1977e339d652008-06-28 11:23:00 +00004598 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004599 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4600 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004601 }else{
drh7708e972008-11-29 00:56:52 +00004602 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004603 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004604 }
danielk1977e339d652008-06-28 11:23:00 +00004605 return rc;
drh054889e2005-11-30 03:20:31 +00004606}
drh9c06c952005-11-26 00:25:00 +00004607
danielk1977ad94b582007-08-20 06:44:22 +00004608/*
4609** Open a file descriptor to the directory containing file zFilename.
4610** If successful, *pFd is set to the opened file descriptor and
4611** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4612** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4613** value.
4614**
4615** If SQLITE_OK is returned, the caller is responsible for closing
4616** the file descriptor *pFd using close().
4617*/
danielk1977fee2d252007-08-18 10:59:19 +00004618static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004619 int ii;
drh777b17a2007-09-20 10:02:54 +00004620 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004621 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004622
drh153c62c2007-08-24 03:51:33 +00004623 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004624 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004625 if( ii>0 ){
4626 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004627 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004628 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004629#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004630 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004631#endif
drh308c2a52010-05-14 11:30:18 +00004632 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004633 }
4634 }
danielk1977fee2d252007-08-18 10:59:19 +00004635 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004636 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004637}
4638
danielk1977b4b47412007-08-17 15:53:36 +00004639/*
drh8b3cf822010-06-01 21:02:51 +00004640** Return the name of a directory in which to put temporary files.
4641** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004642*/
drh7234c6d2010-06-19 15:10:09 +00004643static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004644 static const char *azDirs[] = {
4645 0,
aswiftaebf4132008-11-21 00:10:35 +00004646 0,
danielk197717b90b52008-06-06 11:11:25 +00004647 "/var/tmp",
4648 "/usr/tmp",
4649 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004650 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004651 };
drh8b3cf822010-06-01 21:02:51 +00004652 unsigned int i;
4653 struct stat buf;
4654 const char *zDir = 0;
4655
4656 azDirs[0] = sqlite3_temp_directory;
4657 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004658 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004659 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004660 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004661 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004662 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004663 break;
4664 }
4665 return zDir;
4666}
4667
4668/*
4669** Create a temporary file name in zBuf. zBuf must be allocated
4670** by the calling process and must be big enough to hold at least
4671** pVfs->mxPathname bytes.
4672*/
4673static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004674 static const unsigned char zChars[] =
4675 "abcdefghijklmnopqrstuvwxyz"
4676 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4677 "0123456789";
drh41022642008-11-21 00:24:42 +00004678 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004679 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004680
4681 /* It's odd to simulate an io-error here, but really this is just
4682 ** using the io-error infrastructure to test that SQLite handles this
4683 ** function failing.
4684 */
4685 SimulateIOError( return SQLITE_IOERR );
4686
drh7234c6d2010-06-19 15:10:09 +00004687 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004688 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004689
4690 /* Check that the output buffer is large enough for the temporary file
4691 ** name. If it is not, return SQLITE_ERROR.
4692 */
danielk197700e13612008-11-17 19:18:54 +00004693 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004694 return SQLITE_ERROR;
4695 }
4696
4697 do{
4698 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004699 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004700 sqlite3_randomness(15, &zBuf[j]);
4701 for(i=0; i<15; i++, j++){
4702 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4703 }
4704 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004705 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004706 return SQLITE_OK;
4707}
4708
drhd2cb50b2009-01-09 21:41:17 +00004709#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004710/*
4711** Routine to transform a unixFile into a proxy-locking unixFile.
4712** Implementation in the proxy-lock division, but used by unixOpen()
4713** if SQLITE_PREFER_PROXY_LOCKING is defined.
4714*/
4715static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004716#endif
drhc66d5b62008-12-03 22:48:32 +00004717
dan08da86a2009-08-21 17:18:03 +00004718/*
4719** Search for an unused file descriptor that was opened on the database
4720** file (not a journal or master-journal file) identified by pathname
4721** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4722** argument to this function.
4723**
4724** Such a file descriptor may exist if a database connection was closed
4725** but the associated file descriptor could not be closed because some
4726** other file descriptor open on the same file is holding a file-lock.
4727** Refer to comments in the unixClose() function and the lengthy comment
4728** describing "Posix Advisory Locking" at the start of this file for
4729** further details. Also, ticket #4018.
4730**
4731** If a suitable file descriptor is found, then it is returned. If no
4732** such file descriptor is located, -1 is returned.
4733*/
dane946c392009-08-22 11:39:46 +00004734static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4735 UnixUnusedFd *pUnused = 0;
4736
4737 /* Do not search for an unused file descriptor on vxworks. Not because
4738 ** vxworks would not benefit from the change (it might, we're not sure),
4739 ** but because no way to test it is currently available. It is better
4740 ** not to risk breaking vxworks support for the sake of such an obscure
4741 ** feature. */
4742#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004743 struct stat sStat; /* Results of stat() call */
4744
4745 /* A stat() call may fail for various reasons. If this happens, it is
4746 ** almost certain that an open() call on the same path will also fail.
4747 ** For this reason, if an error occurs in the stat() call here, it is
4748 ** ignored and -1 is returned. The caller will try to open a new file
4749 ** descriptor on the same path, fail, and return an error to SQLite.
4750 **
4751 ** Even if a subsequent open() call does succeed, the consequences of
4752 ** not searching for a resusable file descriptor are not dire. */
4753 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004754 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004755
4756 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004757 pInode = inodeList;
4758 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4759 || pInode->fileId.ino!=sStat.st_ino) ){
4760 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004761 }
drh8af6c222010-05-14 12:43:01 +00004762 if( pInode ){
dane946c392009-08-22 11:39:46 +00004763 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004764 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004765 pUnused = *pp;
4766 if( pUnused ){
4767 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004768 }
4769 }
4770 unixLeaveMutex();
4771 }
dane946c392009-08-22 11:39:46 +00004772#endif /* if !OS_VXWORKS */
4773 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004774}
danielk197717b90b52008-06-06 11:11:25 +00004775
4776/*
danddb0ac42010-07-14 14:48:58 +00004777** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004778** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004779** and a value suitable for passing as the third argument to open(2) is
4780** written to *pMode. If an IO error occurs, an SQLite error code is
4781** returned and the value of *pMode is not modified.
4782**
4783** If the file being opened is a temporary file, it is always created with
4784** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004785** is a database or master journal file, it is created with the permissions
4786** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004787**
drh8ab58662010-07-15 18:38:39 +00004788** Finally, if the file being opened is a WAL or regular journal file, then
4789** this function queries the file-system for the permissions on the
4790** corresponding database file and sets *pMode to this value. Whenever
4791** possible, WAL and journal files are created using the same permissions
4792** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004793*/
4794static int findCreateFileMode(
4795 const char *zPath, /* Path of file (possibly) being created */
4796 int flags, /* Flags passed as 4th argument to xOpen() */
4797 mode_t *pMode /* OUT: Permissions to open file with */
4798){
4799 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004800 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004801 char zDb[MAX_PATHNAME+1]; /* Database file path */
4802 int nDb; /* Number of valid bytes in zDb */
4803 struct stat sStat; /* Output of stat() on database file */
4804
dana0c989d2010-11-05 18:07:37 +00004805 /* zPath is a path to a WAL or journal file. The following block derives
4806 ** the path to the associated database file from zPath. This block handles
4807 ** the following naming conventions:
4808 **
4809 ** "<path to db>-journal"
4810 ** "<path to db>-wal"
4811 ** "<path to db>-journal-NNNN"
4812 ** "<path to db>-wal-NNNN"
4813 **
4814 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4815 ** used by the test_multiplex.c module.
4816 */
4817 nDb = sqlite3Strlen30(zPath) - 1;
4818 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4819 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004820 memcpy(zDb, zPath, nDb);
4821 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004822
danddb0ac42010-07-14 14:48:58 +00004823 if( 0==stat(zDb, &sStat) ){
4824 *pMode = sStat.st_mode & 0777;
4825 }else{
4826 rc = SQLITE_IOERR_FSTAT;
4827 }
4828 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4829 *pMode = 0600;
4830 }else{
4831 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4832 }
4833 return rc;
4834}
4835
4836/*
danielk1977ad94b582007-08-20 06:44:22 +00004837** Open the file zPath.
4838**
danielk1977b4b47412007-08-17 15:53:36 +00004839** Previously, the SQLite OS layer used three functions in place of this
4840** one:
4841**
4842** sqlite3OsOpenReadWrite();
4843** sqlite3OsOpenReadOnly();
4844** sqlite3OsOpenExclusive();
4845**
4846** These calls correspond to the following combinations of flags:
4847**
4848** ReadWrite() -> (READWRITE | CREATE)
4849** ReadOnly() -> (READONLY)
4850** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4851**
4852** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4853** true, the file was configured to be automatically deleted when the
4854** file handle closed. To achieve the same effect using this new
4855** interface, add the DELETEONCLOSE flag to those specified above for
4856** OpenExclusive().
4857*/
4858static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004859 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4860 const char *zPath, /* Pathname of file to be opened */
4861 sqlite3_file *pFile, /* The file descriptor to be filled in */
4862 int flags, /* Input flags to control the opening */
4863 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004864){
dan08da86a2009-08-21 17:18:03 +00004865 unixFile *p = (unixFile *)pFile;
4866 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004867 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004868 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004869 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004870 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004871 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004872
4873 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4874 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4875 int isCreate = (flags & SQLITE_OPEN_CREATE);
4876 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4877 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004878#if SQLITE_ENABLE_LOCKING_STYLE
4879 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4880#endif
danielk1977b4b47412007-08-17 15:53:36 +00004881
danielk1977fee2d252007-08-18 10:59:19 +00004882 /* If creating a master or main-file journal, this function will open
4883 ** a file-descriptor on the directory too. The first time unixSync()
4884 ** is called the directory file descriptor will be fsync()ed and close()d.
4885 */
danddb0ac42010-07-14 14:48:58 +00004886 int isOpenDirectory = (isCreate && (
4887 eType==SQLITE_OPEN_MASTER_JOURNAL
4888 || eType==SQLITE_OPEN_MAIN_JOURNAL
4889 || eType==SQLITE_OPEN_WAL
4890 ));
danielk1977fee2d252007-08-18 10:59:19 +00004891
danielk197717b90b52008-06-06 11:11:25 +00004892 /* If argument zPath is a NULL pointer, this function is required to open
4893 ** a temporary file. Use this buffer to store the file name in.
4894 */
4895 char zTmpname[MAX_PATHNAME+1];
4896 const char *zName = zPath;
4897
danielk1977fee2d252007-08-18 10:59:19 +00004898 /* Check the following statements are true:
4899 **
4900 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4901 ** (b) if CREATE is set, then READWRITE must also be set, and
4902 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004903 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004904 */
danielk1977b4b47412007-08-17 15:53:36 +00004905 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004906 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004907 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004908 assert(isDelete==0 || isCreate);
4909
danddb0ac42010-07-14 14:48:58 +00004910 /* The main DB, main journal, WAL file and master journal are never
4911 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004912 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4913 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4914 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004915 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004916
danielk1977fee2d252007-08-18 10:59:19 +00004917 /* Assert that the upper layer has set one of the "file-type" flags. */
4918 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4919 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4920 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004921 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004922 );
4923
dan08da86a2009-08-21 17:18:03 +00004924 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004925
dan08da86a2009-08-21 17:18:03 +00004926 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004927 UnixUnusedFd *pUnused;
4928 pUnused = findReusableFd(zName, flags);
4929 if( pUnused ){
4930 fd = pUnused->fd;
4931 }else{
dan6aa657f2009-08-24 18:57:58 +00004932 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004933 if( !pUnused ){
4934 return SQLITE_NOMEM;
4935 }
4936 }
4937 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004938 }else if( !zName ){
4939 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004940 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004941 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004942 if( rc!=SQLITE_OK ){
4943 return rc;
4944 }
4945 zName = zTmpname;
4946 }
4947
dan08da86a2009-08-21 17:18:03 +00004948 /* Determine the value of the flags parameter passed to POSIX function
4949 ** open(). These must be calculated even if open() is not called, as
4950 ** they may be stored as part of the file handle and used by the
4951 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004952 if( isReadonly ) openFlags |= O_RDONLY;
4953 if( isReadWrite ) openFlags |= O_RDWR;
4954 if( isCreate ) openFlags |= O_CREAT;
4955 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4956 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004957
danielk1977b4b47412007-08-17 15:53:36 +00004958 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004959 mode_t openMode; /* Permissions to create file with */
4960 rc = findCreateFileMode(zName, flags, &openMode);
4961 if( rc!=SQLITE_OK ){
4962 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004963 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004964 return rc;
4965 }
drhad4f1e52011-03-04 15:43:57 +00004966 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004967 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004968 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4969 /* Failed to open the file for read/write access. Try read-only. */
4970 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004971 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004972 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004973 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00004974 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00004975 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004976 }
4977 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004978 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004979 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004980 }
danielk1977b4b47412007-08-17 15:53:36 +00004981 }
dan08da86a2009-08-21 17:18:03 +00004982 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004983 if( pOutFlags ){
4984 *pOutFlags = flags;
4985 }
4986
dane946c392009-08-22 11:39:46 +00004987 if( p->pUnused ){
4988 p->pUnused->fd = fd;
4989 p->pUnused->flags = flags;
4990 }
4991
danielk1977b4b47412007-08-17 15:53:36 +00004992 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004993#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004994 zPath = zName;
4995#else
danielk197717b90b52008-06-06 11:11:25 +00004996 unlink(zName);
chw97185482008-11-17 08:05:31 +00004997#endif
danielk1977b4b47412007-08-17 15:53:36 +00004998 }
drh41022642008-11-21 00:24:42 +00004999#if SQLITE_ENABLE_LOCKING_STYLE
5000 else{
dan08da86a2009-08-21 17:18:03 +00005001 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005002 }
5003#endif
5004
danielk1977fee2d252007-08-18 10:59:19 +00005005 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005006 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005007 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005008 /* It is safe to close fd at this point, because it is guaranteed not
5009 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005010 ** it would not be safe to close as this would release any locks held
5011 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005012 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005013 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005014 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005015 }
5016 }
danielk1977e339d652008-06-28 11:23:00 +00005017
5018#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005019 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005020#endif
5021
drhda0e7682008-07-30 15:27:54 +00005022 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005023
drh7ed97b92010-01-20 13:07:21 +00005024
5025#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5026 struct statfs fsInfo;
5027 if( fstatfs(fd, &fsInfo) == -1 ){
5028 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005029 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5030 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005031 return SQLITE_IOERR_ACCESS;
5032 }
5033 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5034 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5035 }
5036#endif
5037
5038#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005039#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005040 isAutoProxy = 1;
5041#endif
5042 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005043 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5044 int useProxy = 0;
5045
dan08da86a2009-08-21 17:18:03 +00005046 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5047 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005048 if( envforce!=NULL ){
5049 useProxy = atoi(envforce)>0;
5050 }else{
5051 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005052 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005053 /* In theory, the close(fd) call is sub-optimal. If the file opened
5054 ** with fd is a database file, and there are other connections open
5055 ** on that file that are currently holding advisory locks on it,
5056 ** then the call to close() will cancel those locks. In practice,
5057 ** we're assuming that statfs() doesn't fail very often. At least
5058 ** not while other file descriptors opened by the same process on
5059 ** the same file are working. */
5060 p->lastErrno = errno;
5061 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005062 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005063 }
drh0e9365c2011-03-02 02:08:13 +00005064 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005065 rc = SQLITE_IOERR_ACCESS;
5066 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005067 }
5068 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5069 }
5070 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005071 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5072 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005073 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005074 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005075 if( rc!=SQLITE_OK ){
5076 /* Use unixClose to clean up the resources added in fillInUnixFile
5077 ** and clear all the structure's references. Specifically,
5078 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5079 */
5080 unixClose(pFile);
5081 return rc;
5082 }
aswiftaebf4132008-11-21 00:10:35 +00005083 }
dane946c392009-08-22 11:39:46 +00005084 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005085 }
5086 }
5087#endif
5088
drh77197112011-03-15 19:08:48 +00005089 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5090 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005091open_finished:
5092 if( rc!=SQLITE_OK ){
5093 sqlite3_free(p->pUnused);
5094 }
5095 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005096}
5097
dane946c392009-08-22 11:39:46 +00005098
danielk1977b4b47412007-08-17 15:53:36 +00005099/*
danielk1977fee2d252007-08-18 10:59:19 +00005100** Delete the file at zPath. If the dirSync argument is true, fsync()
5101** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005102*/
drh6b9d6dd2008-12-03 19:34:47 +00005103static int unixDelete(
5104 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5105 const char *zPath, /* Name of file to be deleted */
5106 int dirSync /* If true, fsync() directory after deleting file */
5107){
danielk1977fee2d252007-08-18 10:59:19 +00005108 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005109 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005110 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005111 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005112 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005113 }
danielk1977d39fa702008-10-16 13:27:40 +00005114#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005115 if( dirSync ){
5116 int fd;
5117 rc = openDirectory(zPath, &fd);
5118 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005119#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005120 if( fsync(fd)==-1 )
5121#else
5122 if( fsync(fd) )
5123#endif
5124 {
dane18d4952011-02-21 11:46:24 +00005125 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005126 }
drh0e9365c2011-03-02 02:08:13 +00005127 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005128 }
5129 }
danielk1977d138dd82008-10-15 16:02:48 +00005130#endif
danielk1977fee2d252007-08-18 10:59:19 +00005131 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005132}
5133
danielk197790949c22007-08-17 16:50:38 +00005134/*
5135** Test the existance of or access permissions of file zPath. The
5136** test performed depends on the value of flags:
5137**
5138** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5139** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5140** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5141**
5142** Otherwise return 0.
5143*/
danielk1977861f7452008-06-05 11:39:11 +00005144static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005145 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5146 const char *zPath, /* Path of the file to examine */
5147 int flags, /* What do we want to learn about the zPath file? */
5148 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005149){
rse25c0d1a2007-09-20 08:38:14 +00005150 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005151 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005152 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005153 switch( flags ){
5154 case SQLITE_ACCESS_EXISTS:
5155 amode = F_OK;
5156 break;
5157 case SQLITE_ACCESS_READWRITE:
5158 amode = W_OK|R_OK;
5159 break;
drh50d3f902007-08-27 21:10:36 +00005160 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005161 amode = R_OK;
5162 break;
5163
5164 default:
5165 assert(!"Invalid flags argument");
5166 }
drh99ab3b12011-03-02 15:09:07 +00005167 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005168 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5169 struct stat buf;
5170 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5171 *pResOut = 0;
5172 }
5173 }
danielk1977861f7452008-06-05 11:39:11 +00005174 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005175}
5176
danielk1977b4b47412007-08-17 15:53:36 +00005177
5178/*
5179** Turn a relative pathname into a full pathname. The relative path
5180** is stored as a nul-terminated string in the buffer pointed to by
5181** zPath.
5182**
5183** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5184** (in this case, MAX_PATHNAME bytes). The full-path is written to
5185** this buffer before returning.
5186*/
danielk1977adfb9b02007-09-17 07:02:56 +00005187static int unixFullPathname(
5188 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5189 const char *zPath, /* Possibly relative input path */
5190 int nOut, /* Size of output buffer in bytes */
5191 char *zOut /* Output buffer */
5192){
danielk1977843e65f2007-09-01 16:16:15 +00005193
5194 /* It's odd to simulate an io-error here, but really this is just
5195 ** using the io-error infrastructure to test that SQLite handles this
5196 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005197 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005198 */
5199 SimulateIOError( return SQLITE_ERROR );
5200
drh153c62c2007-08-24 03:51:33 +00005201 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005202 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005203
drh3c7f2dc2007-12-06 13:26:20 +00005204 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005205 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005206 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005207 }else{
5208 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005209 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005210 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005211 }
drhea678832008-12-10 19:26:22 +00005212 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005213 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005214 }
5215 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005216}
5217
drh0ccebe72005-06-07 22:22:50 +00005218
drh761df872006-12-21 01:29:22 +00005219#ifndef SQLITE_OMIT_LOAD_EXTENSION
5220/*
5221** Interfaces for opening a shared library, finding entry points
5222** within the shared library, and closing the shared library.
5223*/
5224#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005225static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5226 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005227 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5228}
danielk197795c8a542007-09-01 06:51:27 +00005229
5230/*
5231** SQLite calls this function immediately after a call to unixDlSym() or
5232** unixDlOpen() fails (returns a null pointer). If a more detailed error
5233** message is available, it is written to zBufOut. If no error message
5234** is available, zBufOut is left unmodified and SQLite uses a default
5235** error message.
5236*/
danielk1977397d65f2008-11-19 11:35:39 +00005237static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005238 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005239 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005240 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005241 zErr = dlerror();
5242 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005243 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005244 }
drh6c7d5c52008-11-21 20:32:33 +00005245 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005246}
drh1875f7a2008-12-08 18:19:17 +00005247static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5248 /*
5249 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5250 ** cast into a pointer to a function. And yet the library dlsym() routine
5251 ** returns a void* which is really a pointer to a function. So how do we
5252 ** use dlsym() with -pedantic-errors?
5253 **
5254 ** Variable x below is defined to be a pointer to a function taking
5255 ** parameters void* and const char* and returning a pointer to a function.
5256 ** We initialize x by assigning it a pointer to the dlsym() function.
5257 ** (That assignment requires a cast.) Then we call the function that
5258 ** x points to.
5259 **
5260 ** This work-around is unlikely to work correctly on any system where
5261 ** you really cannot cast a function pointer into void*. But then, on the
5262 ** other hand, dlsym() will not work on such a system either, so we have
5263 ** not really lost anything.
5264 */
5265 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005266 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005267 x = (void(*(*)(void*,const char*))(void))dlsym;
5268 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005269}
danielk1977397d65f2008-11-19 11:35:39 +00005270static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5271 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005272 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005273}
danielk1977b4b47412007-08-17 15:53:36 +00005274#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5275 #define unixDlOpen 0
5276 #define unixDlError 0
5277 #define unixDlSym 0
5278 #define unixDlClose 0
5279#endif
5280
5281/*
danielk197790949c22007-08-17 16:50:38 +00005282** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005283*/
danielk1977397d65f2008-11-19 11:35:39 +00005284static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5285 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005286 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005287
drhbbd42a62004-05-22 17:41:58 +00005288 /* We have to initialize zBuf to prevent valgrind from reporting
5289 ** errors. The reports issued by valgrind are incorrect - we would
5290 ** prefer that the randomness be increased by making use of the
5291 ** uninitialized space in zBuf - but valgrind errors tend to worry
5292 ** some users. Rather than argue, it seems easier just to initialize
5293 ** the whole array and silence valgrind, even if that means less randomness
5294 ** in the random seed.
5295 **
5296 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005297 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005298 ** tests repeatable.
5299 */
danielk1977b4b47412007-08-17 15:53:36 +00005300 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005301#if !defined(SQLITE_TEST)
5302 {
drh842b8642005-01-21 17:53:17 +00005303 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005304 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005305 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005306 time_t t;
5307 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005308 memcpy(zBuf, &t, sizeof(t));
5309 pid = getpid();
5310 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005311 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005312 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005313 }else{
drhe562be52011-03-02 18:01:10 +00005314 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005315 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005316 }
drhbbd42a62004-05-22 17:41:58 +00005317 }
5318#endif
drh72cbd072008-10-14 17:58:38 +00005319 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005320}
5321
danielk1977b4b47412007-08-17 15:53:36 +00005322
drhbbd42a62004-05-22 17:41:58 +00005323/*
5324** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005325** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005326** The return value is the number of microseconds of sleep actually
5327** requested from the underlying operating system, a number which
5328** might be greater than or equal to the argument, but not less
5329** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005330*/
danielk1977397d65f2008-11-19 11:35:39 +00005331static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005332#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005333 struct timespec sp;
5334
5335 sp.tv_sec = microseconds / 1000000;
5336 sp.tv_nsec = (microseconds % 1000000) * 1000;
5337 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005338 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005339 return microseconds;
5340#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005341 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005342 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005343 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005344#else
danielk1977b4b47412007-08-17 15:53:36 +00005345 int seconds = (microseconds+999999)/1000000;
5346 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005347 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005348 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005349#endif
drh88f474a2006-01-02 20:00:12 +00005350}
5351
5352/*
drh6b9d6dd2008-12-03 19:34:47 +00005353** The following variable, if set to a non-zero value, is interpreted as
5354** the number of seconds since 1970 and is used to set the result of
5355** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005356*/
5357#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005358int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005359#endif
5360
5361/*
drhb7e8ea22010-05-03 14:32:30 +00005362** Find the current time (in Universal Coordinated Time). Write into *piNow
5363** the current time and date as a Julian Day number times 86_400_000. In
5364** other words, write into *piNow the number of milliseconds since the Julian
5365** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5366** proleptic Gregorian calendar.
5367**
5368** On success, return 0. Return 1 if the time and date cannot be found.
5369*/
5370static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5371 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5372#if defined(NO_GETTOD)
5373 time_t t;
5374 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005375 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005376#elif OS_VXWORKS
5377 struct timespec sNow;
5378 clock_gettime(CLOCK_REALTIME, &sNow);
5379 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5380#else
5381 struct timeval sNow;
5382 gettimeofday(&sNow, 0);
5383 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5384#endif
5385
5386#ifdef SQLITE_TEST
5387 if( sqlite3_current_time ){
5388 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5389 }
5390#endif
5391 UNUSED_PARAMETER(NotUsed);
5392 return 0;
5393}
5394
5395/*
drhbbd42a62004-05-22 17:41:58 +00005396** Find the current time (in Universal Coordinated Time). Write the
5397** current time and date as a Julian Day number into *prNow and
5398** return 0. Return 1 if the time and date cannot be found.
5399*/
danielk1977397d65f2008-11-19 11:35:39 +00005400static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005401 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005402 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005403 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005404 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005405 return 0;
5406}
danielk1977b4b47412007-08-17 15:53:36 +00005407
drh6b9d6dd2008-12-03 19:34:47 +00005408/*
5409** We added the xGetLastError() method with the intention of providing
5410** better low-level error messages when operating-system problems come up
5411** during SQLite operation. But so far, none of that has been implemented
5412** in the core. So this routine is never called. For now, it is merely
5413** a place-holder.
5414*/
danielk1977397d65f2008-11-19 11:35:39 +00005415static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5416 UNUSED_PARAMETER(NotUsed);
5417 UNUSED_PARAMETER(NotUsed2);
5418 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005419 return 0;
5420}
5421
drhf2424c52010-04-26 00:04:55 +00005422
5423/*
drh734c9862008-11-28 15:37:20 +00005424************************ End of sqlite3_vfs methods ***************************
5425******************************************************************************/
5426
drh715ff302008-12-03 22:32:44 +00005427/******************************************************************************
5428************************** Begin Proxy Locking ********************************
5429**
5430** Proxy locking is a "uber-locking-method" in this sense: It uses the
5431** other locking methods on secondary lock files. Proxy locking is a
5432** meta-layer over top of the primitive locking implemented above. For
5433** this reason, the division that implements of proxy locking is deferred
5434** until late in the file (here) after all of the other I/O methods have
5435** been defined - so that the primitive locking methods are available
5436** as services to help with the implementation of proxy locking.
5437**
5438****
5439**
5440** The default locking schemes in SQLite use byte-range locks on the
5441** database file to coordinate safe, concurrent access by multiple readers
5442** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5443** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5444** as POSIX read & write locks over fixed set of locations (via fsctl),
5445** on AFP and SMB only exclusive byte-range locks are available via fsctl
5446** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5447** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5448** address in the shared range is taken for a SHARED lock, the entire
5449** shared range is taken for an EXCLUSIVE lock):
5450**
5451** PENDING_BYTE 0x40000000
5452** RESERVED_BYTE 0x40000001
5453** SHARED_RANGE 0x40000002 -> 0x40000200
5454**
5455** This works well on the local file system, but shows a nearly 100x
5456** slowdown in read performance on AFP because the AFP client disables
5457** the read cache when byte-range locks are present. Enabling the read
5458** cache exposes a cache coherency problem that is present on all OS X
5459** supported network file systems. NFS and AFP both observe the
5460** close-to-open semantics for ensuring cache coherency
5461** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5462** address the requirements for concurrent database access by multiple
5463** readers and writers
5464** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5465**
5466** To address the performance and cache coherency issues, proxy file locking
5467** changes the way database access is controlled by limiting access to a
5468** single host at a time and moving file locks off of the database file
5469** and onto a proxy file on the local file system.
5470**
5471**
5472** Using proxy locks
5473** -----------------
5474**
5475** C APIs
5476**
5477** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5478** <proxy_path> | ":auto:");
5479** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5480**
5481**
5482** SQL pragmas
5483**
5484** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5485** PRAGMA [database.]lock_proxy_file
5486**
5487** Specifying ":auto:" means that if there is a conch file with a matching
5488** host ID in it, the proxy path in the conch file will be used, otherwise
5489** a proxy path based on the user's temp dir
5490** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5491** actual proxy file name is generated from the name and path of the
5492** database file. For example:
5493**
5494** For database path "/Users/me/foo.db"
5495** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5496**
5497** Once a lock proxy is configured for a database connection, it can not
5498** be removed, however it may be switched to a different proxy path via
5499** the above APIs (assuming the conch file is not being held by another
5500** connection or process).
5501**
5502**
5503** How proxy locking works
5504** -----------------------
5505**
5506** Proxy file locking relies primarily on two new supporting files:
5507**
5508** * conch file to limit access to the database file to a single host
5509** at a time
5510**
5511** * proxy file to act as a proxy for the advisory locks normally
5512** taken on the database
5513**
5514** The conch file - to use a proxy file, sqlite must first "hold the conch"
5515** by taking an sqlite-style shared lock on the conch file, reading the
5516** contents and comparing the host's unique host ID (see below) and lock
5517** proxy path against the values stored in the conch. The conch file is
5518** stored in the same directory as the database file and the file name
5519** is patterned after the database file name as ".<databasename>-conch".
5520** If the conch file does not exist, or it's contents do not match the
5521** host ID and/or proxy path, then the lock is escalated to an exclusive
5522** lock and the conch file contents is updated with the host ID and proxy
5523** path and the lock is downgraded to a shared lock again. If the conch
5524** is held by another process (with a shared lock), the exclusive lock
5525** will fail and SQLITE_BUSY is returned.
5526**
5527** The proxy file - a single-byte file used for all advisory file locks
5528** normally taken on the database file. This allows for safe sharing
5529** of the database file for multiple readers and writers on the same
5530** host (the conch ensures that they all use the same local lock file).
5531**
drh715ff302008-12-03 22:32:44 +00005532** Requesting the lock proxy does not immediately take the conch, it is
5533** only taken when the first request to lock database file is made.
5534** This matches the semantics of the traditional locking behavior, where
5535** opening a connection to a database file does not take a lock on it.
5536** The shared lock and an open file descriptor are maintained until
5537** the connection to the database is closed.
5538**
5539** The proxy file and the lock file are never deleted so they only need
5540** to be created the first time they are used.
5541**
5542** Configuration options
5543** ---------------------
5544**
5545** SQLITE_PREFER_PROXY_LOCKING
5546**
5547** Database files accessed on non-local file systems are
5548** automatically configured for proxy locking, lock files are
5549** named automatically using the same logic as
5550** PRAGMA lock_proxy_file=":auto:"
5551**
5552** SQLITE_PROXY_DEBUG
5553**
5554** Enables the logging of error messages during host id file
5555** retrieval and creation
5556**
drh715ff302008-12-03 22:32:44 +00005557** LOCKPROXYDIR
5558**
5559** Overrides the default directory used for lock proxy files that
5560** are named automatically via the ":auto:" setting
5561**
5562** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5563**
5564** Permissions to use when creating a directory for storing the
5565** lock proxy files, only used when LOCKPROXYDIR is not set.
5566**
5567**
5568** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5569** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5570** force proxy locking to be used for every database file opened, and 0
5571** will force automatic proxy locking to be disabled for all database
5572** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5573** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5574*/
5575
5576/*
5577** Proxy locking is only available on MacOSX
5578*/
drhd2cb50b2009-01-09 21:41:17 +00005579#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005580
drh715ff302008-12-03 22:32:44 +00005581/*
5582** The proxyLockingContext has the path and file structures for the remote
5583** and local proxy files in it
5584*/
5585typedef struct proxyLockingContext proxyLockingContext;
5586struct proxyLockingContext {
5587 unixFile *conchFile; /* Open conch file */
5588 char *conchFilePath; /* Name of the conch file */
5589 unixFile *lockProxy; /* Open proxy lock file */
5590 char *lockProxyPath; /* Name of the proxy lock file */
5591 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005592 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005593 void *oldLockingContext; /* Original lockingcontext to restore on close */
5594 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5595};
5596
drh7ed97b92010-01-20 13:07:21 +00005597/*
5598** The proxy lock file path for the database at dbPath is written into lPath,
5599** which must point to valid, writable memory large enough for a maxLen length
5600** file path.
drh715ff302008-12-03 22:32:44 +00005601*/
drh715ff302008-12-03 22:32:44 +00005602static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5603 int len;
5604 int dbLen;
5605 int i;
5606
5607#ifdef LOCKPROXYDIR
5608 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5609#else
5610# ifdef _CS_DARWIN_USER_TEMP_DIR
5611 {
drh7ed97b92010-01-20 13:07:21 +00005612 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005613 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5614 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005615 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005616 }
drh7ed97b92010-01-20 13:07:21 +00005617 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005618 }
5619# else
5620 len = strlcpy(lPath, "/tmp/", maxLen);
5621# endif
5622#endif
5623
5624 if( lPath[len-1]!='/' ){
5625 len = strlcat(lPath, "/", maxLen);
5626 }
5627
5628 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005629 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005630 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005631 char c = dbPath[i];
5632 lPath[i+len] = (c=='/')?'_':c;
5633 }
5634 lPath[i+len]='\0';
5635 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005636 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005637 return SQLITE_OK;
5638}
5639
drh7ed97b92010-01-20 13:07:21 +00005640/*
5641 ** Creates the lock file and any missing directories in lockPath
5642 */
5643static int proxyCreateLockPath(const char *lockPath){
5644 int i, len;
5645 char buf[MAXPATHLEN];
5646 int start = 0;
5647
5648 assert(lockPath!=NULL);
5649 /* try to create all the intermediate directories */
5650 len = (int)strlen(lockPath);
5651 buf[0] = lockPath[0];
5652 for( i=1; i<len; i++ ){
5653 if( lockPath[i] == '/' && (i - start > 0) ){
5654 /* only mkdir if leaf dir != "." or "/" or ".." */
5655 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5656 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5657 buf[i]='\0';
5658 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5659 int err=errno;
5660 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005661 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005662 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005663 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005664 return err;
5665 }
5666 }
5667 }
5668 start=i+1;
5669 }
5670 buf[i] = lockPath[i];
5671 }
drh308c2a52010-05-14 11:30:18 +00005672 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005673 return 0;
5674}
5675
drh715ff302008-12-03 22:32:44 +00005676/*
5677** Create a new VFS file descriptor (stored in memory obtained from
5678** sqlite3_malloc) and open the file named "path" in the file descriptor.
5679**
5680** The caller is responsible not only for closing the file descriptor
5681** but also for freeing the memory associated with the file descriptor.
5682*/
drh7ed97b92010-01-20 13:07:21 +00005683static int proxyCreateUnixFile(
5684 const char *path, /* path for the new unixFile */
5685 unixFile **ppFile, /* unixFile created and returned by ref */
5686 int islockfile /* if non zero missing dirs will be created */
5687) {
5688 int fd = -1;
5689 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005690 unixFile *pNew;
5691 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005692 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005693 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005694 int terrno = 0;
5695 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005696
drh7ed97b92010-01-20 13:07:21 +00005697 /* 1. first try to open/create the file
5698 ** 2. if that fails, and this is a lock file (not-conch), try creating
5699 ** the parent directories and then try again.
5700 ** 3. if that fails, try to open the file read-only
5701 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5702 */
5703 pUnused = findReusableFd(path, openFlags);
5704 if( pUnused ){
5705 fd = pUnused->fd;
5706 }else{
5707 pUnused = sqlite3_malloc(sizeof(*pUnused));
5708 if( !pUnused ){
5709 return SQLITE_NOMEM;
5710 }
5711 }
5712 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005713 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005714 terrno = errno;
5715 if( fd<0 && errno==ENOENT && islockfile ){
5716 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005717 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005718 }
5719 }
5720 }
5721 if( fd<0 ){
5722 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005723 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005724 terrno = errno;
5725 }
5726 if( fd<0 ){
5727 if( islockfile ){
5728 return SQLITE_BUSY;
5729 }
5730 switch (terrno) {
5731 case EACCES:
5732 return SQLITE_PERM;
5733 case EIO:
5734 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5735 default:
drh9978c972010-02-23 17:36:32 +00005736 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005737 }
5738 }
5739
5740 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5741 if( pNew==NULL ){
5742 rc = SQLITE_NOMEM;
5743 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005744 }
5745 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005746 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005747 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005748 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005749 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005750 pUnused->fd = fd;
5751 pUnused->flags = openFlags;
5752 pNew->pUnused = pUnused;
5753
drh77197112011-03-15 19:08:48 +00005754 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005755 if( rc==SQLITE_OK ){
5756 *ppFile = pNew;
5757 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005758 }
drh7ed97b92010-01-20 13:07:21 +00005759end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005760 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005761 sqlite3_free(pNew);
5762 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005763 return rc;
5764}
5765
drh7ed97b92010-01-20 13:07:21 +00005766#ifdef SQLITE_TEST
5767/* simulate multiple hosts by creating unique hostid file paths */
5768int sqlite3_hostid_num = 0;
5769#endif
5770
5771#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5772
drh0ab216a2010-07-02 17:10:40 +00005773/* Not always defined in the headers as it ought to be */
5774extern int gethostuuid(uuid_t id, const struct timespec *wait);
5775
drh7ed97b92010-01-20 13:07:21 +00005776/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5777** bytes of writable memory.
5778*/
5779static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005780 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5781 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005782#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5783 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005784 {
5785 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5786 if( gethostuuid(pHostID, &timeout) ){
5787 int err = errno;
5788 if( pError ){
5789 *pError = err;
5790 }
5791 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005792 }
drh7ed97b92010-01-20 13:07:21 +00005793 }
drhe8b0c9b2010-09-25 14:13:17 +00005794#endif
drh7ed97b92010-01-20 13:07:21 +00005795#ifdef SQLITE_TEST
5796 /* simulate multiple hosts by creating unique hostid file paths */
5797 if( sqlite3_hostid_num != 0){
5798 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5799 }
5800#endif
5801
5802 return SQLITE_OK;
5803}
5804
5805/* The conch file contains the header, host id and lock file path
5806 */
5807#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5808#define PROXY_HEADERLEN 1 /* conch file header length */
5809#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5810#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5811
5812/*
5813** Takes an open conch file, copies the contents to a new path and then moves
5814** it back. The newly created file's file descriptor is assigned to the
5815** conch file structure and finally the original conch file descriptor is
5816** closed. Returns zero if successful.
5817*/
5818static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5819 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5820 unixFile *conchFile = pCtx->conchFile;
5821 char tPath[MAXPATHLEN];
5822 char buf[PROXY_MAXCONCHLEN];
5823 char *cPath = pCtx->conchFilePath;
5824 size_t readLen = 0;
5825 size_t pathLen = 0;
5826 char errmsg[64] = "";
5827 int fd = -1;
5828 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005829 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005830
5831 /* create a new path by replace the trailing '-conch' with '-break' */
5832 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5833 if( pathLen>MAXPATHLEN || pathLen<6 ||
5834 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005835 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005836 goto end_breaklock;
5837 }
5838 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005839 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005840 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005841 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005842 goto end_breaklock;
5843 }
5844 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005845 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5846 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005847 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005848 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005849 goto end_breaklock;
5850 }
drhe562be52011-03-02 18:01:10 +00005851 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005852 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005853 goto end_breaklock;
5854 }
5855 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005856 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005857 goto end_breaklock;
5858 }
5859 rc = 0;
5860 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005861 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005862 conchFile->h = fd;
5863 conchFile->openFlags = O_RDWR | O_CREAT;
5864
5865end_breaklock:
5866 if( rc ){
5867 if( fd>=0 ){
5868 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005869 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005870 }
5871 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5872 }
5873 return rc;
5874}
5875
5876/* Take the requested lock on the conch file and break a stale lock if the
5877** host id matches.
5878*/
5879static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5880 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5881 unixFile *conchFile = pCtx->conchFile;
5882 int rc = SQLITE_OK;
5883 int nTries = 0;
5884 struct timespec conchModTime;
5885
5886 do {
5887 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5888 nTries ++;
5889 if( rc==SQLITE_BUSY ){
5890 /* If the lock failed (busy):
5891 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5892 * 2nd try: fail if the mod time changed or host id is different, wait
5893 * 10 sec and try again
5894 * 3rd try: break the lock unless the mod time has changed.
5895 */
5896 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005897 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005898 pFile->lastErrno = errno;
5899 return SQLITE_IOERR_LOCK;
5900 }
5901
5902 if( nTries==1 ){
5903 conchModTime = buf.st_mtimespec;
5904 usleep(500000); /* wait 0.5 sec and try the lock again*/
5905 continue;
5906 }
5907
5908 assert( nTries>1 );
5909 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5910 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5911 return SQLITE_BUSY;
5912 }
5913
5914 if( nTries==2 ){
5915 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005916 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005917 if( len<0 ){
5918 pFile->lastErrno = errno;
5919 return SQLITE_IOERR_LOCK;
5920 }
5921 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5922 /* don't break the lock if the host id doesn't match */
5923 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5924 return SQLITE_BUSY;
5925 }
5926 }else{
5927 /* don't break the lock on short read or a version mismatch */
5928 return SQLITE_BUSY;
5929 }
5930 usleep(10000000); /* wait 10 sec and try the lock again */
5931 continue;
5932 }
5933
5934 assert( nTries==3 );
5935 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5936 rc = SQLITE_OK;
5937 if( lockType==EXCLUSIVE_LOCK ){
5938 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5939 }
5940 if( !rc ){
5941 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5942 }
5943 }
5944 }
5945 } while( rc==SQLITE_BUSY && nTries<3 );
5946
5947 return rc;
5948}
5949
5950/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005951** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5952** lockPath means that the lockPath in the conch file will be used if the
5953** host IDs match, or a new lock path will be generated automatically
5954** and written to the conch file.
5955*/
5956static int proxyTakeConch(unixFile *pFile){
5957 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5958
drh7ed97b92010-01-20 13:07:21 +00005959 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005960 return SQLITE_OK;
5961 }else{
5962 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005963 uuid_t myHostID;
5964 int pError = 0;
5965 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005966 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005967 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005968 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005969 int createConch = 0;
5970 int hostIdMatch = 0;
5971 int readLen = 0;
5972 int tryOldLockPath = 0;
5973 int forceNewLockPath = 0;
5974
drh308c2a52010-05-14 11:30:18 +00005975 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5976 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005977
drh7ed97b92010-01-20 13:07:21 +00005978 rc = proxyGetHostID(myHostID, &pError);
5979 if( (rc&0xff)==SQLITE_IOERR ){
5980 pFile->lastErrno = pError;
5981 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005982 }
drh7ed97b92010-01-20 13:07:21 +00005983 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005984 if( rc!=SQLITE_OK ){
5985 goto end_takeconch;
5986 }
drh7ed97b92010-01-20 13:07:21 +00005987 /* read the existing conch file */
5988 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5989 if( readLen<0 ){
5990 /* I/O error: lastErrno set by seekAndRead */
5991 pFile->lastErrno = conchFile->lastErrno;
5992 rc = SQLITE_IOERR_READ;
5993 goto end_takeconch;
5994 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5995 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5996 /* a short read or version format mismatch means we need to create a new
5997 ** conch file.
5998 */
5999 createConch = 1;
6000 }
6001 /* if the host id matches and the lock path already exists in the conch
6002 ** we'll try to use the path there, if we can't open that path, we'll
6003 ** retry with a new auto-generated path
6004 */
6005 do { /* in case we need to try again for an :auto: named lock file */
6006
6007 if( !createConch && !forceNewLockPath ){
6008 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6009 PROXY_HOSTIDLEN);
6010 /* if the conch has data compare the contents */
6011 if( !pCtx->lockProxyPath ){
6012 /* for auto-named local lock file, just check the host ID and we'll
6013 ** use the local lock file path that's already in there
6014 */
6015 if( hostIdMatch ){
6016 size_t pathLen = (readLen - PROXY_PATHINDEX);
6017
6018 if( pathLen>=MAXPATHLEN ){
6019 pathLen=MAXPATHLEN-1;
6020 }
6021 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6022 lockPath[pathLen] = 0;
6023 tempLockPath = lockPath;
6024 tryOldLockPath = 1;
6025 /* create a copy of the lock path if the conch is taken */
6026 goto end_takeconch;
6027 }
6028 }else if( hostIdMatch
6029 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6030 readLen-PROXY_PATHINDEX)
6031 ){
6032 /* conch host and lock path match */
6033 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006034 }
drh7ed97b92010-01-20 13:07:21 +00006035 }
6036
6037 /* if the conch isn't writable and doesn't match, we can't take it */
6038 if( (conchFile->openFlags&O_RDWR) == 0 ){
6039 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006040 goto end_takeconch;
6041 }
drh7ed97b92010-01-20 13:07:21 +00006042
6043 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006044 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006045 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6046 tempLockPath = lockPath;
6047 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006048 }
drh7ed97b92010-01-20 13:07:21 +00006049
6050 /* update conch with host and path (this will fail if other process
6051 ** has a shared lock already), if the host id matches, use the big
6052 ** stick.
drh715ff302008-12-03 22:32:44 +00006053 */
drh7ed97b92010-01-20 13:07:21 +00006054 futimes(conchFile->h, NULL);
6055 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006056 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006057 /* We are trying for an exclusive lock but another thread in this
6058 ** same process is still holding a shared lock. */
6059 rc = SQLITE_BUSY;
6060 } else {
6061 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006062 }
drh715ff302008-12-03 22:32:44 +00006063 }else{
drh7ed97b92010-01-20 13:07:21 +00006064 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006065 }
drh7ed97b92010-01-20 13:07:21 +00006066 if( rc==SQLITE_OK ){
6067 char writeBuffer[PROXY_MAXCONCHLEN];
6068 int writeSize = 0;
6069
6070 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6071 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6072 if( pCtx->lockProxyPath!=NULL ){
6073 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6074 }else{
6075 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6076 }
6077 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006078 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006079 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6080 fsync(conchFile->h);
6081 /* If we created a new conch file (not just updated the contents of a
6082 ** valid conch file), try to match the permissions of the database
6083 */
6084 if( rc==SQLITE_OK && createConch ){
6085 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006086 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006087 if( err==0 ){
6088 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6089 S_IROTH|S_IWOTH);
6090 /* try to match the database file R/W permissions, ignore failure */
6091#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006092 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006093#else
drhff812312011-02-23 13:33:46 +00006094 do{
drhe562be52011-03-02 18:01:10 +00006095 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006096 }while( rc==(-1) && errno==EINTR );
6097 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006098 int code = errno;
6099 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6100 cmode, code, strerror(code));
6101 } else {
6102 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6103 }
6104 }else{
6105 int code = errno;
6106 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6107 err, code, strerror(code));
6108#endif
6109 }
drh715ff302008-12-03 22:32:44 +00006110 }
6111 }
drh7ed97b92010-01-20 13:07:21 +00006112 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6113
6114 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006115 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006116 if( rc==SQLITE_OK && pFile->openFlags ){
6117 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006118 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006119 }
6120 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006121 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006122 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006123 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006124 if( fd>=0 ){
6125 pFile->h = fd;
6126 }else{
drh9978c972010-02-23 17:36:32 +00006127 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006128 during locking */
6129 }
6130 }
6131 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6132 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6133 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6134 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6135 /* we couldn't create the proxy lock file with the old lock file path
6136 ** so try again via auto-naming
6137 */
6138 forceNewLockPath = 1;
6139 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006140 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006141 }
6142 }
6143 if( rc==SQLITE_OK ){
6144 /* Need to make a copy of path if we extracted the value
6145 ** from the conch file or the path was allocated on the stack
6146 */
6147 if( tempLockPath ){
6148 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6149 if( !pCtx->lockProxyPath ){
6150 rc = SQLITE_NOMEM;
6151 }
6152 }
6153 }
6154 if( rc==SQLITE_OK ){
6155 pCtx->conchHeld = 1;
6156
6157 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6158 afpLockingContext *afpCtx;
6159 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6160 afpCtx->dbPath = pCtx->lockProxyPath;
6161 }
6162 } else {
6163 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6164 }
drh308c2a52010-05-14 11:30:18 +00006165 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6166 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006167 return rc;
drh308c2a52010-05-14 11:30:18 +00006168 } while (1); /* in case we need to retry the :auto: lock file -
6169 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006170 }
6171}
6172
6173/*
6174** If pFile holds a lock on a conch file, then release that lock.
6175*/
6176static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006177 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006178 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6179 unixFile *conchFile; /* Name of the conch file */
6180
6181 pCtx = (proxyLockingContext *)pFile->lockingContext;
6182 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006183 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006184 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006185 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006186 if( pCtx->conchHeld>0 ){
6187 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6188 }
drh715ff302008-12-03 22:32:44 +00006189 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006190 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6191 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006192 return rc;
6193}
6194
6195/*
6196** Given the name of a database file, compute the name of its conch file.
6197** Store the conch filename in memory obtained from sqlite3_malloc().
6198** Make *pConchPath point to the new name. Return SQLITE_OK on success
6199** or SQLITE_NOMEM if unable to obtain memory.
6200**
6201** The caller is responsible for ensuring that the allocated memory
6202** space is eventually freed.
6203**
6204** *pConchPath is set to NULL if a memory allocation error occurs.
6205*/
6206static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6207 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006208 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006209 char *conchPath; /* buffer in which to construct conch name */
6210
6211 /* Allocate space for the conch filename and initialize the name to
6212 ** the name of the original database file. */
6213 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6214 if( conchPath==0 ){
6215 return SQLITE_NOMEM;
6216 }
6217 memcpy(conchPath, dbPath, len+1);
6218
6219 /* now insert a "." before the last / character */
6220 for( i=(len-1); i>=0; i-- ){
6221 if( conchPath[i]=='/' ){
6222 i++;
6223 break;
6224 }
6225 }
6226 conchPath[i]='.';
6227 while ( i<len ){
6228 conchPath[i+1]=dbPath[i];
6229 i++;
6230 }
6231
6232 /* append the "-conch" suffix to the file */
6233 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006234 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006235
6236 return SQLITE_OK;
6237}
6238
6239
6240/* Takes a fully configured proxy locking-style unix file and switches
6241** the local lock file path
6242*/
6243static int switchLockProxyPath(unixFile *pFile, const char *path) {
6244 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6245 char *oldPath = pCtx->lockProxyPath;
6246 int rc = SQLITE_OK;
6247
drh308c2a52010-05-14 11:30:18 +00006248 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006249 return SQLITE_BUSY;
6250 }
6251
6252 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6253 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6254 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6255 return SQLITE_OK;
6256 }else{
6257 unixFile *lockProxy = pCtx->lockProxy;
6258 pCtx->lockProxy=NULL;
6259 pCtx->conchHeld = 0;
6260 if( lockProxy!=NULL ){
6261 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6262 if( rc ) return rc;
6263 sqlite3_free(lockProxy);
6264 }
6265 sqlite3_free(oldPath);
6266 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6267 }
6268
6269 return rc;
6270}
6271
6272/*
6273** pFile is a file that has been opened by a prior xOpen call. dbPath
6274** is a string buffer at least MAXPATHLEN+1 characters in size.
6275**
6276** This routine find the filename associated with pFile and writes it
6277** int dbPath.
6278*/
6279static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006280#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006281 if( pFile->pMethod == &afpIoMethods ){
6282 /* afp style keeps a reference to the db path in the filePath field
6283 ** of the struct */
drhea678832008-12-10 19:26:22 +00006284 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006285 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6286 } else
drh715ff302008-12-03 22:32:44 +00006287#endif
6288 if( pFile->pMethod == &dotlockIoMethods ){
6289 /* dot lock style uses the locking context to store the dot lock
6290 ** file path */
6291 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6292 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6293 }else{
6294 /* all other styles use the locking context to store the db file path */
6295 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006296 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006297 }
6298 return SQLITE_OK;
6299}
6300
6301/*
6302** Takes an already filled in unix file and alters it so all file locking
6303** will be performed on the local proxy lock file. The following fields
6304** are preserved in the locking context so that they can be restored and
6305** the unix structure properly cleaned up at close time:
6306** ->lockingContext
6307** ->pMethod
6308*/
6309static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6310 proxyLockingContext *pCtx;
6311 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6312 char *lockPath=NULL;
6313 int rc = SQLITE_OK;
6314
drh308c2a52010-05-14 11:30:18 +00006315 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006316 return SQLITE_BUSY;
6317 }
6318 proxyGetDbPathForUnixFile(pFile, dbPath);
6319 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6320 lockPath=NULL;
6321 }else{
6322 lockPath=(char *)path;
6323 }
6324
drh308c2a52010-05-14 11:30:18 +00006325 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6326 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006327
6328 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6329 if( pCtx==0 ){
6330 return SQLITE_NOMEM;
6331 }
6332 memset(pCtx, 0, sizeof(*pCtx));
6333
6334 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6335 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006336 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6337 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6338 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6339 ** (c) the file system is read-only, then enable no-locking access.
6340 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6341 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6342 */
6343 struct statfs fsInfo;
6344 struct stat conchInfo;
6345 int goLockless = 0;
6346
drh99ab3b12011-03-02 15:09:07 +00006347 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006348 int err = errno;
6349 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6350 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6351 }
6352 }
6353 if( goLockless ){
6354 pCtx->conchHeld = -1; /* read only FS/ lockless */
6355 rc = SQLITE_OK;
6356 }
6357 }
drh715ff302008-12-03 22:32:44 +00006358 }
6359 if( rc==SQLITE_OK && lockPath ){
6360 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6361 }
6362
6363 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006364 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6365 if( pCtx->dbPath==NULL ){
6366 rc = SQLITE_NOMEM;
6367 }
6368 }
6369 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006370 /* all memory is allocated, proxys are created and assigned,
6371 ** switch the locking context and pMethod then return.
6372 */
drh715ff302008-12-03 22:32:44 +00006373 pCtx->oldLockingContext = pFile->lockingContext;
6374 pFile->lockingContext = pCtx;
6375 pCtx->pOldMethod = pFile->pMethod;
6376 pFile->pMethod = &proxyIoMethods;
6377 }else{
6378 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006379 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006380 sqlite3_free(pCtx->conchFile);
6381 }
drhd56b1212010-08-11 06:14:15 +00006382 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006383 sqlite3_free(pCtx->conchFilePath);
6384 sqlite3_free(pCtx);
6385 }
drh308c2a52010-05-14 11:30:18 +00006386 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6387 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006388 return rc;
6389}
6390
6391
6392/*
6393** This routine handles sqlite3_file_control() calls that are specific
6394** to proxy locking.
6395*/
6396static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6397 switch( op ){
6398 case SQLITE_GET_LOCKPROXYFILE: {
6399 unixFile *pFile = (unixFile*)id;
6400 if( pFile->pMethod == &proxyIoMethods ){
6401 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6402 proxyTakeConch(pFile);
6403 if( pCtx->lockProxyPath ){
6404 *(const char **)pArg = pCtx->lockProxyPath;
6405 }else{
6406 *(const char **)pArg = ":auto: (not held)";
6407 }
6408 } else {
6409 *(const char **)pArg = NULL;
6410 }
6411 return SQLITE_OK;
6412 }
6413 case SQLITE_SET_LOCKPROXYFILE: {
6414 unixFile *pFile = (unixFile*)id;
6415 int rc = SQLITE_OK;
6416 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6417 if( pArg==NULL || (const char *)pArg==0 ){
6418 if( isProxyStyle ){
6419 /* turn off proxy locking - not supported */
6420 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6421 }else{
6422 /* turn off proxy locking - already off - NOOP */
6423 rc = SQLITE_OK;
6424 }
6425 }else{
6426 const char *proxyPath = (const char *)pArg;
6427 if( isProxyStyle ){
6428 proxyLockingContext *pCtx =
6429 (proxyLockingContext*)pFile->lockingContext;
6430 if( !strcmp(pArg, ":auto:")
6431 || (pCtx->lockProxyPath &&
6432 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6433 ){
6434 rc = SQLITE_OK;
6435 }else{
6436 rc = switchLockProxyPath(pFile, proxyPath);
6437 }
6438 }else{
6439 /* turn on proxy file locking */
6440 rc = proxyTransformUnixFile(pFile, proxyPath);
6441 }
6442 }
6443 return rc;
6444 }
6445 default: {
6446 assert( 0 ); /* The call assures that only valid opcodes are sent */
6447 }
6448 }
6449 /*NOTREACHED*/
6450 return SQLITE_ERROR;
6451}
6452
6453/*
6454** Within this division (the proxying locking implementation) the procedures
6455** above this point are all utilities. The lock-related methods of the
6456** proxy-locking sqlite3_io_method object follow.
6457*/
6458
6459
6460/*
6461** This routine checks if there is a RESERVED lock held on the specified
6462** file by this or any other process. If such a lock is held, set *pResOut
6463** to a non-zero value otherwise *pResOut is set to zero. The return value
6464** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6465*/
6466static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6467 unixFile *pFile = (unixFile*)id;
6468 int rc = proxyTakeConch(pFile);
6469 if( rc==SQLITE_OK ){
6470 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006471 if( pCtx->conchHeld>0 ){
6472 unixFile *proxy = pCtx->lockProxy;
6473 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6474 }else{ /* conchHeld < 0 is lockless */
6475 pResOut=0;
6476 }
drh715ff302008-12-03 22:32:44 +00006477 }
6478 return rc;
6479}
6480
6481/*
drh308c2a52010-05-14 11:30:18 +00006482** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006483** of the following:
6484**
6485** (1) SHARED_LOCK
6486** (2) RESERVED_LOCK
6487** (3) PENDING_LOCK
6488** (4) EXCLUSIVE_LOCK
6489**
6490** Sometimes when requesting one lock state, additional lock states
6491** are inserted in between. The locking might fail on one of the later
6492** transitions leaving the lock state different from what it started but
6493** still short of its goal. The following chart shows the allowed
6494** transitions and the inserted intermediate states:
6495**
6496** UNLOCKED -> SHARED
6497** SHARED -> RESERVED
6498** SHARED -> (PENDING) -> EXCLUSIVE
6499** RESERVED -> (PENDING) -> EXCLUSIVE
6500** PENDING -> EXCLUSIVE
6501**
6502** This routine will only increase a lock. Use the sqlite3OsUnlock()
6503** routine to lower a locking level.
6504*/
drh308c2a52010-05-14 11:30:18 +00006505static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006506 unixFile *pFile = (unixFile*)id;
6507 int rc = proxyTakeConch(pFile);
6508 if( rc==SQLITE_OK ){
6509 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006510 if( pCtx->conchHeld>0 ){
6511 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006512 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6513 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006514 }else{
6515 /* conchHeld < 0 is lockless */
6516 }
drh715ff302008-12-03 22:32:44 +00006517 }
6518 return rc;
6519}
6520
6521
6522/*
drh308c2a52010-05-14 11:30:18 +00006523** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006524** must be either NO_LOCK or SHARED_LOCK.
6525**
6526** If the locking level of the file descriptor is already at or below
6527** the requested locking level, this routine is a no-op.
6528*/
drh308c2a52010-05-14 11:30:18 +00006529static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006530 unixFile *pFile = (unixFile*)id;
6531 int rc = proxyTakeConch(pFile);
6532 if( rc==SQLITE_OK ){
6533 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006534 if( pCtx->conchHeld>0 ){
6535 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006536 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6537 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006538 }else{
6539 /* conchHeld < 0 is lockless */
6540 }
drh715ff302008-12-03 22:32:44 +00006541 }
6542 return rc;
6543}
6544
6545/*
6546** Close a file that uses proxy locks.
6547*/
6548static int proxyClose(sqlite3_file *id) {
6549 if( id ){
6550 unixFile *pFile = (unixFile*)id;
6551 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6552 unixFile *lockProxy = pCtx->lockProxy;
6553 unixFile *conchFile = pCtx->conchFile;
6554 int rc = SQLITE_OK;
6555
6556 if( lockProxy ){
6557 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6558 if( rc ) return rc;
6559 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6560 if( rc ) return rc;
6561 sqlite3_free(lockProxy);
6562 pCtx->lockProxy = 0;
6563 }
6564 if( conchFile ){
6565 if( pCtx->conchHeld ){
6566 rc = proxyReleaseConch(pFile);
6567 if( rc ) return rc;
6568 }
6569 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6570 if( rc ) return rc;
6571 sqlite3_free(conchFile);
6572 }
drhd56b1212010-08-11 06:14:15 +00006573 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006574 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006575 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006576 /* restore the original locking context and pMethod then close it */
6577 pFile->lockingContext = pCtx->oldLockingContext;
6578 pFile->pMethod = pCtx->pOldMethod;
6579 sqlite3_free(pCtx);
6580 return pFile->pMethod->xClose(id);
6581 }
6582 return SQLITE_OK;
6583}
6584
6585
6586
drhd2cb50b2009-01-09 21:41:17 +00006587#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006588/*
6589** The proxy locking style is intended for use with AFP filesystems.
6590** And since AFP is only supported on MacOSX, the proxy locking is also
6591** restricted to MacOSX.
6592**
6593**
6594******************* End of the proxy lock implementation **********************
6595******************************************************************************/
6596
drh734c9862008-11-28 15:37:20 +00006597/*
danielk1977e339d652008-06-28 11:23:00 +00006598** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006599**
6600** This routine registers all VFS implementations for unix-like operating
6601** systems. This routine, and the sqlite3_os_end() routine that follows,
6602** should be the only routines in this file that are visible from other
6603** files.
drh6b9d6dd2008-12-03 19:34:47 +00006604**
6605** This routine is called once during SQLite initialization and by a
6606** single thread. The memory allocation and mutex subsystems have not
6607** necessarily been initialized when this routine is called, and so they
6608** should not be used.
drh153c62c2007-08-24 03:51:33 +00006609*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006610int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006611 /*
6612 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006613 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6614 ** to the "finder" function. (pAppData is a pointer to a pointer because
6615 ** silly C90 rules prohibit a void* from being cast to a function pointer
6616 ** and so we have to go through the intermediate pointer to avoid problems
6617 ** when compiling with -pedantic-errors on GCC.)
6618 **
6619 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006620 ** finder-function. The finder-function returns a pointer to the
6621 ** sqlite_io_methods object that implements the desired locking
6622 ** behaviors. See the division above that contains the IOMETHODS
6623 ** macro for addition information on finder-functions.
6624 **
6625 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6626 ** object. But the "autolockIoFinder" available on MacOSX does a little
6627 ** more than that; it looks at the filesystem type that hosts the
6628 ** database file and tries to choose an locking method appropriate for
6629 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006630 */
drh7708e972008-11-29 00:56:52 +00006631 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006632 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006633 sizeof(unixFile), /* szOsFile */ \
6634 MAX_PATHNAME, /* mxPathname */ \
6635 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006636 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006637 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006638 unixOpen, /* xOpen */ \
6639 unixDelete, /* xDelete */ \
6640 unixAccess, /* xAccess */ \
6641 unixFullPathname, /* xFullPathname */ \
6642 unixDlOpen, /* xDlOpen */ \
6643 unixDlError, /* xDlError */ \
6644 unixDlSym, /* xDlSym */ \
6645 unixDlClose, /* xDlClose */ \
6646 unixRandomness, /* xRandomness */ \
6647 unixSleep, /* xSleep */ \
6648 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006649 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006650 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006651 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006652 unixGetSystemCall, /* xGetSystemCall */ \
6653 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006654 }
6655
drh6b9d6dd2008-12-03 19:34:47 +00006656 /*
6657 ** All default VFSes for unix are contained in the following array.
6658 **
6659 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6660 ** by the SQLite core when the VFS is registered. So the following
6661 ** array cannot be const.
6662 */
danielk1977e339d652008-06-28 11:23:00 +00006663 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006664#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006665 UNIXVFS("unix", autolockIoFinder ),
6666#else
6667 UNIXVFS("unix", posixIoFinder ),
6668#endif
6669 UNIXVFS("unix-none", nolockIoFinder ),
6670 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006671 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006672#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006673 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006674#endif
6675#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006676 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006677#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006678 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006679#endif
chw78a13182009-04-07 05:35:03 +00006680#endif
drhd2cb50b2009-01-09 21:41:17 +00006681#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006682 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006683 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006684 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006685#endif
drh153c62c2007-08-24 03:51:33 +00006686 };
drh6b9d6dd2008-12-03 19:34:47 +00006687 unsigned int i; /* Loop counter */
6688
drh2aa5a002011-04-13 13:42:25 +00006689 /* Double-check that the aSyscall[] array has been constructed
6690 ** correctly. See ticket [bb3a86e890c8e96ab] */
6691 assert( ArraySize(aSyscall)==16 );
6692
drh6b9d6dd2008-12-03 19:34:47 +00006693 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006694 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006695 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006696 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006697 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006698}
danielk1977e339d652008-06-28 11:23:00 +00006699
6700/*
drh6b9d6dd2008-12-03 19:34:47 +00006701** Shutdown the operating system interface.
6702**
6703** Some operating systems might need to do some cleanup in this routine,
6704** to release dynamically allocated objects. But not on unix.
6705** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006706*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006707int sqlite3_os_end(void){
6708 return SQLITE_OK;
6709}
drhdce8bdb2007-08-16 13:01:44 +00006710
danielk197729bafea2008-06-26 10:41:19 +00006711#endif /* SQLITE_OS_UNIX */