blob: f04b6af273b9d0d573b19138b5fad95c4a54de52 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000209 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000210 int lastErrno; /* The unix errno from last I/O error */
211 void *lockingContext; /* Locking style specific state */
212 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
drh77197112011-03-15 19:08:48 +0000250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
drha7e61d82011-03-12 17:02:57 +0000251
252/*
drh198bf392006-01-06 21:52:49 +0000253** Include code that is common to all os_*.c files
254*/
255#include "os_common.h"
256
257/*
drh0ccebe72005-06-07 22:22:50 +0000258** Define various macros that are missing from some systems.
259*/
drhbbd42a62004-05-22 17:41:58 +0000260#ifndef O_LARGEFILE
261# define O_LARGEFILE 0
262#endif
263#ifdef SQLITE_DISABLE_LFS
264# undef O_LARGEFILE
265# define O_LARGEFILE 0
266#endif
267#ifndef O_NOFOLLOW
268# define O_NOFOLLOW 0
269#endif
270#ifndef O_BINARY
271# define O_BINARY 0
272#endif
273
274/*
drh2b4b5962005-06-15 17:47:55 +0000275** The threadid macro resolves to the thread-id or to 0. Used for
276** testing and debugging only.
277*/
drhd677b3d2007-08-20 22:48:41 +0000278#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000279#define threadid pthread_self()
280#else
281#define threadid 0
282#endif
283
drh99ab3b12011-03-02 15:09:07 +0000284/*
285** Many system calls are accessed through pointer-to-functions so that
286** they may be overridden at runtime to facilitate fault injection during
287** testing and sandboxing. The following array holds the names and pointers
288** to all overrideable system calls.
289*/
290static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000291 const char *zName; /* Name of the sytem call */
292 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
293 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000294} aSyscall[] = {
drh58ad5802011-03-23 22:02:23 +0000295 { "open", (sqlite3_syscall_ptr)open, 0 },
drh99ab3b12011-03-02 15:09:07 +0000296#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
297
drh58ad5802011-03-23 22:02:23 +0000298 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000299#define osClose ((int(*)(int))aSyscall[1].pCurrent)
300
drh58ad5802011-03-23 22:02:23 +0000301 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000302#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
303
drh58ad5802011-03-23 22:02:23 +0000304 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000305#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
306
drh58ad5802011-03-23 22:02:23 +0000307 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000308#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
309
310/*
311** The DJGPP compiler environment looks mostly like Unix, but it
312** lacks the fcntl() system call. So redefine fcntl() to be something
313** that always succeeds. This means that locking does not occur under
314** DJGPP. But it is DOS - what did you expect?
315*/
316#ifdef __DJGPP__
317 { "fstat", 0, 0 },
318#define osFstat(a,b,c) 0
319#else
drh58ad5802011-03-23 22:02:23 +0000320 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000321#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
322#endif
323
drh58ad5802011-03-23 22:02:23 +0000324 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
326
drh58ad5802011-03-23 22:02:23 +0000327 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000328#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000329
drh58ad5802011-03-23 22:02:23 +0000330 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000331#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
332
333#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
drh58ad5802011-03-23 22:02:23 +0000334 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000335#else
drh58ad5802011-03-23 22:02:23 +0000336 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000337#endif
338#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
339
340#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000341 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000342#else
drh58ad5802011-03-23 22:02:23 +0000343 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000344#endif
345#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000348#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
349
350#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
drh58ad5802011-03-23 22:02:23 +0000351 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000352#else
drh58ad5802011-03-23 22:02:23 +0000353 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000354#endif
355#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
356 aSyscall[12].pCurrent)
357
358#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000359 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000360#else
drh58ad5802011-03-23 22:02:23 +0000361 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000362#endif
363#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
364 aSyscall[13].pCurrent)
365
drh58ad5802011-03-23 22:02:23 +0000366 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drhe562be52011-03-02 18:01:10 +0000367#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
368
369#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000370 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000371#else
drh58ad5802011-03-23 22:02:23 +0000372 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000373#endif
dan0fd7d862011-03-29 10:04:23 +0000374#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000375
376}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000377
378/*
379** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000380** "unix" VFSes. Return SQLITE_OK opon successfully updating the
381** system call pointer, or SQLITE_NOTFOUND if there is no configurable
382** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000383*/
384static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000385 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
386 const char *zName, /* Name of system call to override */
387 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000388){
drh58ad5802011-03-23 22:02:23 +0000389 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000390 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000391
392 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000393 if( zName==0 ){
394 /* If no zName is given, restore all system calls to their default
395 ** settings and return NULL
396 */
397 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
398 if( aSyscall[i].pDefault ){
399 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh1df30962011-03-02 19:06:42 +0000400 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000401 }
402 }
403 }else{
404 /* If zName is specified, operate on only the one system call
405 ** specified.
406 */
407 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
408 if( strcmp(zName, aSyscall[i].zName)==0 ){
409 if( aSyscall[i].pDefault==0 ){
410 aSyscall[i].pDefault = aSyscall[i].pCurrent;
411 }
drh1df30962011-03-02 19:06:42 +0000412 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000413 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
414 aSyscall[i].pCurrent = pNewFunc;
415 break;
416 }
417 }
418 }
419 return rc;
420}
421
drh1df30962011-03-02 19:06:42 +0000422/*
423** Return the value of a system call. Return NULL if zName is not a
424** recognized system call name. NULL is also returned if the system call
425** is currently undefined.
426*/
drh58ad5802011-03-23 22:02:23 +0000427static sqlite3_syscall_ptr unixGetSystemCall(
428 sqlite3_vfs *pNotUsed,
429 const char *zName
430){
431 unsigned int i;
432
433 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000434 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
435 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
436 }
437 return 0;
438}
439
440/*
441** Return the name of the first system call after zName. If zName==NULL
442** then return the name of the first system call. Return NULL if zName
443** is the last system call or if zName is not the name of a valid
444** system call.
445*/
446static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000447 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000448
449 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000450 if( zName ){
451 for(i=0; i<ArraySize(aSyscall)-1; i++){
452 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000453 }
454 }
dan0fd7d862011-03-29 10:04:23 +0000455 for(i++; i<ArraySize(aSyscall); i++){
456 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000457 }
458 return 0;
459}
460
drhad4f1e52011-03-04 15:43:57 +0000461/*
462** Retry open() calls that fail due to EINTR
463*/
464static int robust_open(const char *z, int f, int m){
465 int rc;
466 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
467 return rc;
468}
danielk197713adf8a2004-06-03 16:08:41 +0000469
drh107886a2008-11-21 22:21:50 +0000470/*
dan9359c7b2009-08-21 08:29:10 +0000471** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000472** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000473** vxworksFileId objects used by this file, all of which may be
474** shared by multiple threads.
475**
476** Function unixMutexHeld() is used to assert() that the global mutex
477** is held when required. This function is only used as part of assert()
478** statements. e.g.
479**
480** unixEnterMutex()
481** assert( unixMutexHeld() );
482** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000483*/
484static void unixEnterMutex(void){
485 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
486}
487static void unixLeaveMutex(void){
488 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
489}
dan9359c7b2009-08-21 08:29:10 +0000490#ifdef SQLITE_DEBUG
491static int unixMutexHeld(void) {
492 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
493}
494#endif
drh107886a2008-11-21 22:21:50 +0000495
drh734c9862008-11-28 15:37:20 +0000496
497#ifdef SQLITE_DEBUG
498/*
499** Helper function for printing out trace information from debugging
500** binaries. This returns the string represetation of the supplied
501** integer lock-type.
502*/
drh308c2a52010-05-14 11:30:18 +0000503static const char *azFileLock(int eFileLock){
504 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000505 case NO_LOCK: return "NONE";
506 case SHARED_LOCK: return "SHARED";
507 case RESERVED_LOCK: return "RESERVED";
508 case PENDING_LOCK: return "PENDING";
509 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000510 }
511 return "ERROR";
512}
513#endif
514
515#ifdef SQLITE_LOCK_TRACE
516/*
517** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000518**
drh734c9862008-11-28 15:37:20 +0000519** This routine is used for troubleshooting locks on multithreaded
520** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
521** command-line option on the compiler. This code is normally
522** turned off.
523*/
524static int lockTrace(int fd, int op, struct flock *p){
525 char *zOpName, *zType;
526 int s;
527 int savedErrno;
528 if( op==F_GETLK ){
529 zOpName = "GETLK";
530 }else if( op==F_SETLK ){
531 zOpName = "SETLK";
532 }else{
drh99ab3b12011-03-02 15:09:07 +0000533 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000534 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
535 return s;
536 }
537 if( p->l_type==F_RDLCK ){
538 zType = "RDLCK";
539 }else if( p->l_type==F_WRLCK ){
540 zType = "WRLCK";
541 }else if( p->l_type==F_UNLCK ){
542 zType = "UNLCK";
543 }else{
544 assert( 0 );
545 }
546 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000547 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000548 savedErrno = errno;
549 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
550 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
551 (int)p->l_pid, s);
552 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
553 struct flock l2;
554 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000555 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000556 if( l2.l_type==F_RDLCK ){
557 zType = "RDLCK";
558 }else if( l2.l_type==F_WRLCK ){
559 zType = "WRLCK";
560 }else if( l2.l_type==F_UNLCK ){
561 zType = "UNLCK";
562 }else{
563 assert( 0 );
564 }
565 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
566 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
567 }
568 errno = savedErrno;
569 return s;
570}
drh99ab3b12011-03-02 15:09:07 +0000571#undef osFcntl
572#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000573#endif /* SQLITE_LOCK_TRACE */
574
drhff812312011-02-23 13:33:46 +0000575/*
576** Retry ftruncate() calls that fail due to EINTR
577*/
drhff812312011-02-23 13:33:46 +0000578static int robust_ftruncate(int h, sqlite3_int64 sz){
579 int rc;
drh99ab3b12011-03-02 15:09:07 +0000580 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000581 return rc;
582}
drh734c9862008-11-28 15:37:20 +0000583
584/*
585** This routine translates a standard POSIX errno code into something
586** useful to the clients of the sqlite3 functions. Specifically, it is
587** intended to translate a variety of "try again" errors into SQLITE_BUSY
588** and a variety of "please close the file descriptor NOW" errors into
589** SQLITE_IOERR
590**
591** Errors during initialization of locks, or file system support for locks,
592** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
593*/
594static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
595 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000596#if 0
597 /* At one point this code was not commented out. In theory, this branch
598 ** should never be hit, as this function should only be called after
599 ** a locking-related function (i.e. fcntl()) has returned non-zero with
600 ** the value of errno as the first argument. Since a system call has failed,
601 ** errno should be non-zero.
602 **
603 ** Despite this, if errno really is zero, we still don't want to return
604 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
605 ** propagated back to the caller. Commenting this branch out means errno==0
606 ** will be handled by the "default:" case below.
607 */
drh734c9862008-11-28 15:37:20 +0000608 case 0:
609 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000610#endif
611
drh734c9862008-11-28 15:37:20 +0000612 case EAGAIN:
613 case ETIMEDOUT:
614 case EBUSY:
615 case EINTR:
616 case ENOLCK:
617 /* random NFS retry error, unless during file system support
618 * introspection, in which it actually means what it says */
619 return SQLITE_BUSY;
620
621 case EACCES:
622 /* EACCES is like EAGAIN during locking operations, but not any other time*/
623 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
624 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
625 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
626 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
627 return SQLITE_BUSY;
628 }
629 /* else fall through */
630 case EPERM:
631 return SQLITE_PERM;
632
danea83bc62011-04-01 11:56:32 +0000633 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
634 ** this module never makes such a call. And the code in SQLite itself
635 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
636 ** this case is also commented out. If the system does set errno to EDEADLK,
637 ** the default SQLITE_IOERR_XXX code will be returned. */
638#if 0
drh734c9862008-11-28 15:37:20 +0000639 case EDEADLK:
640 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000641#endif
drh734c9862008-11-28 15:37:20 +0000642
643#if EOPNOTSUPP!=ENOTSUP
644 case EOPNOTSUPP:
645 /* something went terribly awry, unless during file system support
646 * introspection, in which it actually means what it says */
647#endif
648#ifdef ENOTSUP
649 case ENOTSUP:
650 /* invalid fd, unless during file system support introspection, in which
651 * it actually means what it says */
652#endif
653 case EIO:
654 case EBADF:
655 case EINVAL:
656 case ENOTCONN:
657 case ENODEV:
658 case ENXIO:
659 case ENOENT:
660 case ESTALE:
661 case ENOSYS:
662 /* these should force the client to close the file and reconnect */
663
664 default:
665 return sqliteIOErr;
666 }
667}
668
669
670
671/******************************************************************************
672****************** Begin Unique File ID Utility Used By VxWorks ***************
673**
674** On most versions of unix, we can get a unique ID for a file by concatenating
675** the device number and the inode number. But this does not work on VxWorks.
676** On VxWorks, a unique file id must be based on the canonical filename.
677**
678** A pointer to an instance of the following structure can be used as a
679** unique file ID in VxWorks. Each instance of this structure contains
680** a copy of the canonical filename. There is also a reference count.
681** The structure is reclaimed when the number of pointers to it drops to
682** zero.
683**
684** There are never very many files open at one time and lookups are not
685** a performance-critical path, so it is sufficient to put these
686** structures on a linked list.
687*/
688struct vxworksFileId {
689 struct vxworksFileId *pNext; /* Next in a list of them all */
690 int nRef; /* Number of references to this one */
691 int nName; /* Length of the zCanonicalName[] string */
692 char *zCanonicalName; /* Canonical filename */
693};
694
695#if OS_VXWORKS
696/*
drh9b35ea62008-11-29 02:20:26 +0000697** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000698** variable:
699*/
700static struct vxworksFileId *vxworksFileList = 0;
701
702/*
703** Simplify a filename into its canonical form
704** by making the following changes:
705**
706** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000707** * convert /./ into just /
708** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000709**
710** Changes are made in-place. Return the new name length.
711**
712** The original filename is in z[0..n-1]. Return the number of
713** characters in the simplified name.
714*/
715static int vxworksSimplifyName(char *z, int n){
716 int i, j;
717 while( n>1 && z[n-1]=='/' ){ n--; }
718 for(i=j=0; i<n; i++){
719 if( z[i]=='/' ){
720 if( z[i+1]=='/' ) continue;
721 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
722 i += 1;
723 continue;
724 }
725 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
726 while( j>0 && z[j-1]!='/' ){ j--; }
727 if( j>0 ){ j--; }
728 i += 2;
729 continue;
730 }
731 }
732 z[j++] = z[i];
733 }
734 z[j] = 0;
735 return j;
736}
737
738/*
739** Find a unique file ID for the given absolute pathname. Return
740** a pointer to the vxworksFileId object. This pointer is the unique
741** file ID.
742**
743** The nRef field of the vxworksFileId object is incremented before
744** the object is returned. A new vxworksFileId object is created
745** and added to the global list if necessary.
746**
747** If a memory allocation error occurs, return NULL.
748*/
749static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
750 struct vxworksFileId *pNew; /* search key and new file ID */
751 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
752 int n; /* Length of zAbsoluteName string */
753
754 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000755 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000756 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
757 if( pNew==0 ) return 0;
758 pNew->zCanonicalName = (char*)&pNew[1];
759 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
760 n = vxworksSimplifyName(pNew->zCanonicalName, n);
761
762 /* Search for an existing entry that matching the canonical name.
763 ** If found, increment the reference count and return a pointer to
764 ** the existing file ID.
765 */
766 unixEnterMutex();
767 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
768 if( pCandidate->nName==n
769 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
770 ){
771 sqlite3_free(pNew);
772 pCandidate->nRef++;
773 unixLeaveMutex();
774 return pCandidate;
775 }
776 }
777
778 /* No match was found. We will make a new file ID */
779 pNew->nRef = 1;
780 pNew->nName = n;
781 pNew->pNext = vxworksFileList;
782 vxworksFileList = pNew;
783 unixLeaveMutex();
784 return pNew;
785}
786
787/*
788** Decrement the reference count on a vxworksFileId object. Free
789** the object when the reference count reaches zero.
790*/
791static void vxworksReleaseFileId(struct vxworksFileId *pId){
792 unixEnterMutex();
793 assert( pId->nRef>0 );
794 pId->nRef--;
795 if( pId->nRef==0 ){
796 struct vxworksFileId **pp;
797 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
798 assert( *pp==pId );
799 *pp = pId->pNext;
800 sqlite3_free(pId);
801 }
802 unixLeaveMutex();
803}
804#endif /* OS_VXWORKS */
805/*************** End of Unique File ID Utility Used By VxWorks ****************
806******************************************************************************/
807
808
809/******************************************************************************
810*************************** Posix Advisory Locking ****************************
811**
drh9b35ea62008-11-29 02:20:26 +0000812** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000813** section 6.5.2.2 lines 483 through 490 specify that when a process
814** sets or clears a lock, that operation overrides any prior locks set
815** by the same process. It does not explicitly say so, but this implies
816** that it overrides locks set by the same process using a different
817** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000818**
819** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000820** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
821**
822** Suppose ./file1 and ./file2 are really the same file (because
823** one is a hard or symbolic link to the other) then if you set
824** an exclusive lock on fd1, then try to get an exclusive lock
825** on fd2, it works. I would have expected the second lock to
826** fail since there was already a lock on the file due to fd1.
827** But not so. Since both locks came from the same process, the
828** second overrides the first, even though they were on different
829** file descriptors opened on different file names.
830**
drh734c9862008-11-28 15:37:20 +0000831** This means that we cannot use POSIX locks to synchronize file access
832** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000833** to synchronize access for threads in separate processes, but not
834** threads within the same process.
835**
836** To work around the problem, SQLite has to manage file locks internally
837** on its own. Whenever a new database is opened, we have to find the
838** specific inode of the database file (the inode is determined by the
839** st_dev and st_ino fields of the stat structure that fstat() fills in)
840** and check for locks already existing on that inode. When locks are
841** created or removed, we have to look at our own internal record of the
842** locks to see if another thread has previously set a lock on that same
843** inode.
844**
drh9b35ea62008-11-29 02:20:26 +0000845** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
846** For VxWorks, we have to use the alternative unique ID system based on
847** canonical filename and implemented in the previous division.)
848**
danielk1977ad94b582007-08-20 06:44:22 +0000849** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000850** descriptor. It is now a structure that holds the integer file
851** descriptor and a pointer to a structure that describes the internal
852** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000853** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000854** point to the same locking structure. The locking structure keeps
855** a reference count (so we will know when to delete it) and a "cnt"
856** field that tells us its internal lock status. cnt==0 means the
857** file is unlocked. cnt==-1 means the file has an exclusive lock.
858** cnt>0 means there are cnt shared locks on the file.
859**
860** Any attempt to lock or unlock a file first checks the locking
861** structure. The fcntl() system call is only invoked to set a
862** POSIX lock if the internal lock structure transitions between
863** a locked and an unlocked state.
864**
drh734c9862008-11-28 15:37:20 +0000865** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000866**
867** If you close a file descriptor that points to a file that has locks,
868** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000869** released. To work around this problem, each unixInodeInfo object
870** maintains a count of the number of pending locks on tha inode.
871** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000872** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000873** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000874** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000875** be closed and that list is walked (and cleared) when the last lock
876** clears.
877**
drh9b35ea62008-11-29 02:20:26 +0000878** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000879**
drh9b35ea62008-11-29 02:20:26 +0000880** Many older versions of linux use the LinuxThreads library which is
881** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000882** A cannot be modified or overridden by a different thread B.
883** Only thread A can modify the lock. Locking behavior is correct
884** if the appliation uses the newer Native Posix Thread Library (NPTL)
885** on linux - with NPTL a lock created by thread A can override locks
886** in thread B. But there is no way to know at compile-time which
887** threading library is being used. So there is no way to know at
888** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000889** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000890** current process.
drh5fdae772004-06-29 03:29:00 +0000891**
drh8af6c222010-05-14 12:43:01 +0000892** SQLite used to support LinuxThreads. But support for LinuxThreads
893** was dropped beginning with version 3.7.0. SQLite will still work with
894** LinuxThreads provided that (1) there is no more than one connection
895** per database file in the same process and (2) database connections
896** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000897*/
898
899/*
900** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000901** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000902*/
903struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000904 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000905#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000906 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000907#else
drh107886a2008-11-21 22:21:50 +0000908 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000909#endif
910};
911
912/*
drhbbd42a62004-05-22 17:41:58 +0000913** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000914** inode. Or, on LinuxThreads, there is one of these structures for
915** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000916**
danielk1977ad94b582007-08-20 06:44:22 +0000917** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000918** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000919** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000920*/
drh8af6c222010-05-14 12:43:01 +0000921struct unixInodeInfo {
922 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000923 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000924 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
925 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000926 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000927 unixShmNode *pShmNode; /* Shared memory associated with this inode */
928 int nLock; /* Number of outstanding file locks */
929 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
930 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
931 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000932#if defined(SQLITE_ENABLE_LOCKING_STYLE)
933 unsigned long long sharedByte; /* for AFP simulated shared lock */
934#endif
drh6c7d5c52008-11-21 20:32:33 +0000935#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000936 sem_t *pSem; /* Named POSIX semaphore */
937 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000938#endif
drhbbd42a62004-05-22 17:41:58 +0000939};
940
drhda0e7682008-07-30 15:27:54 +0000941/*
drh8af6c222010-05-14 12:43:01 +0000942** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000943*/
drhd91c68f2010-05-14 14:52:25 +0000944static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000945
drh5fdae772004-06-29 03:29:00 +0000946/*
dane18d4952011-02-21 11:46:24 +0000947**
948** This function - unixLogError_x(), is only ever called via the macro
949** unixLogError().
950**
951** It is invoked after an error occurs in an OS function and errno has been
952** set. It logs a message using sqlite3_log() containing the current value of
953** errno and, if possible, the human-readable equivalent from strerror() or
954** strerror_r().
955**
956** The first argument passed to the macro should be the error code that
957** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
958** The two subsequent arguments should be the name of the OS function that
959** failed (e.g. "unlink", "open") and the the associated file-system path,
960** if any.
961*/
drh0e9365c2011-03-02 02:08:13 +0000962#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
963static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000964 int errcode, /* SQLite error code */
965 const char *zFunc, /* Name of OS function that failed */
966 const char *zPath, /* File path associated with error */
967 int iLine /* Source line number where error occurred */
968){
969 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000970 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000971
972 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
973 ** the strerror() function to obtain the human-readable error message
974 ** equivalent to errno. Otherwise, use strerror_r().
975 */
976#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
977 char aErr[80];
978 memset(aErr, 0, sizeof(aErr));
979 zErr = aErr;
980
981 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
982 ** assume that the system provides the the GNU version of strerror_r() that
983 ** returns a pointer to a buffer containing the error message. That pointer
984 ** may point to aErr[], or it may point to some static storage somewhere.
985 ** Otherwise, assume that the system provides the POSIX version of
986 ** strerror_r(), which always writes an error message into aErr[].
987 **
988 ** If the code incorrectly assumes that it is the POSIX version that is
989 ** available, the error message will often be an empty string. Not a
990 ** huge problem. Incorrectly concluding that the GNU version is available
991 ** could lead to a segfault though.
992 */
993#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
994 zErr =
995# endif
drh0e9365c2011-03-02 02:08:13 +0000996 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000997
998#elif SQLITE_THREADSAFE
999 /* This is a threadsafe build, but strerror_r() is not available. */
1000 zErr = "";
1001#else
1002 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001003 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001004#endif
1005
1006 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001007 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001008 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001009 "os_unix.c:%d: (%d) %s(%s) - %s",
1010 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001011 );
1012
1013 return errcode;
1014}
1015
drh0e9365c2011-03-02 02:08:13 +00001016/*
1017** Close a file descriptor.
1018**
1019** We assume that close() almost always works, since it is only in a
1020** very sick application or on a very sick platform that it might fail.
1021** If it does fail, simply leak the file descriptor, but do log the
1022** error.
1023**
1024** Note that it is not safe to retry close() after EINTR since the
1025** file descriptor might have already been reused by another thread.
1026** So we don't even try to recover from an EINTR. Just log the error
1027** and move on.
1028*/
1029static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001030 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001031 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1032 pFile ? pFile->zPath : 0, lineno);
1033 }
1034}
dane18d4952011-02-21 11:46:24 +00001035
1036/*
danb0ac3e32010-06-16 10:55:42 +00001037** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001038*/
drh0e9365c2011-03-02 02:08:13 +00001039static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001040 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001041 UnixUnusedFd *p;
1042 UnixUnusedFd *pNext;
1043 for(p=pInode->pUnused; p; p=pNext){
1044 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001045 robust_close(pFile, p->fd, __LINE__);
1046 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001047 }
drh0e9365c2011-03-02 02:08:13 +00001048 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001049}
1050
1051/*
drh8af6c222010-05-14 12:43:01 +00001052** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001053**
1054** The mutex entered using the unixEnterMutex() function must be held
1055** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001056*/
danb0ac3e32010-06-16 10:55:42 +00001057static void releaseInodeInfo(unixFile *pFile){
1058 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001059 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001060 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001061 pInode->nRef--;
1062 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001063 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001064 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001065 if( pInode->pPrev ){
1066 assert( pInode->pPrev->pNext==pInode );
1067 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001068 }else{
drh8af6c222010-05-14 12:43:01 +00001069 assert( inodeList==pInode );
1070 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001071 }
drh8af6c222010-05-14 12:43:01 +00001072 if( pInode->pNext ){
1073 assert( pInode->pNext->pPrev==pInode );
1074 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001075 }
drh8af6c222010-05-14 12:43:01 +00001076 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001077 }
drhbbd42a62004-05-22 17:41:58 +00001078 }
1079}
1080
1081/*
drh8af6c222010-05-14 12:43:01 +00001082** Given a file descriptor, locate the unixInodeInfo object that
1083** describes that file descriptor. Create a new one if necessary. The
1084** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001085**
dan9359c7b2009-08-21 08:29:10 +00001086** The mutex entered using the unixEnterMutex() function must be held
1087** when this function is called.
1088**
drh6c7d5c52008-11-21 20:32:33 +00001089** Return an appropriate error code.
1090*/
drh8af6c222010-05-14 12:43:01 +00001091static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001092 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001093 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001094){
1095 int rc; /* System call return code */
1096 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001097 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1098 struct stat statbuf; /* Low-level file information */
1099 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001100
dan9359c7b2009-08-21 08:29:10 +00001101 assert( unixMutexHeld() );
1102
drh6c7d5c52008-11-21 20:32:33 +00001103 /* Get low-level information about the file that we can used to
1104 ** create a unique name for the file.
1105 */
1106 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001107 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001108 if( rc!=0 ){
1109 pFile->lastErrno = errno;
1110#ifdef EOVERFLOW
1111 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1112#endif
1113 return SQLITE_IOERR;
1114 }
1115
drheb0d74f2009-02-03 15:27:02 +00001116#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001117 /* On OS X on an msdos filesystem, the inode number is reported
1118 ** incorrectly for zero-size files. See ticket #3260. To work
1119 ** around this problem (we consider it a bug in OS X, not SQLite)
1120 ** we always increase the file size to 1 by writing a single byte
1121 ** prior to accessing the inode number. The one byte written is
1122 ** an ASCII 'S' character which also happens to be the first byte
1123 ** in the header of every SQLite database. In this way, if there
1124 ** is a race condition such that another thread has already populated
1125 ** the first page of the database, no damage is done.
1126 */
drh7ed97b92010-01-20 13:07:21 +00001127 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001128 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001129 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001130 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001131 return SQLITE_IOERR;
1132 }
drh99ab3b12011-03-02 15:09:07 +00001133 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001134 if( rc!=0 ){
1135 pFile->lastErrno = errno;
1136 return SQLITE_IOERR;
1137 }
1138 }
drheb0d74f2009-02-03 15:27:02 +00001139#endif
drh6c7d5c52008-11-21 20:32:33 +00001140
drh8af6c222010-05-14 12:43:01 +00001141 memset(&fileId, 0, sizeof(fileId));
1142 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001143#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001144 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001145#else
drh8af6c222010-05-14 12:43:01 +00001146 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001147#endif
drh8af6c222010-05-14 12:43:01 +00001148 pInode = inodeList;
1149 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1150 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001151 }
drh8af6c222010-05-14 12:43:01 +00001152 if( pInode==0 ){
1153 pInode = sqlite3_malloc( sizeof(*pInode) );
1154 if( pInode==0 ){
1155 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001156 }
drh8af6c222010-05-14 12:43:01 +00001157 memset(pInode, 0, sizeof(*pInode));
1158 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1159 pInode->nRef = 1;
1160 pInode->pNext = inodeList;
1161 pInode->pPrev = 0;
1162 if( inodeList ) inodeList->pPrev = pInode;
1163 inodeList = pInode;
1164 }else{
1165 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001166 }
drh8af6c222010-05-14 12:43:01 +00001167 *ppInode = pInode;
1168 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001169}
drh6c7d5c52008-11-21 20:32:33 +00001170
aswift5b1a2562008-08-22 00:22:35 +00001171
1172/*
danielk197713adf8a2004-06-03 16:08:41 +00001173** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001174** file by this or any other process. If such a lock is held, set *pResOut
1175** to a non-zero value otherwise *pResOut is set to zero. The return value
1176** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001177*/
danielk1977861f7452008-06-05 11:39:11 +00001178static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001179 int rc = SQLITE_OK;
1180 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001181 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001182
danielk1977861f7452008-06-05 11:39:11 +00001183 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1184
drh054889e2005-11-30 03:20:31 +00001185 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001186 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001187
1188 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001189 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001190 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001191 }
1192
drh2ac3ee92004-06-07 16:27:46 +00001193 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001194 */
danielk197709480a92009-02-09 05:32:32 +00001195#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001196 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001197 struct flock lock;
1198 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001199 lock.l_start = RESERVED_BYTE;
1200 lock.l_len = 1;
1201 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001202 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1203 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1204 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001205 } else if( lock.l_type!=F_UNLCK ){
1206 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001207 }
1208 }
danielk197709480a92009-02-09 05:32:32 +00001209#endif
danielk197713adf8a2004-06-03 16:08:41 +00001210
drh6c7d5c52008-11-21 20:32:33 +00001211 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001212 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001213
aswift5b1a2562008-08-22 00:22:35 +00001214 *pResOut = reserved;
1215 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001216}
1217
1218/*
drha7e61d82011-03-12 17:02:57 +00001219** Attempt to set a system-lock on the file pFile. The lock is
1220** described by pLock.
1221**
drh77197112011-03-15 19:08:48 +00001222** If the pFile was opened read/write from unix-excl, then the only lock
1223** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001224** the first time any lock is attempted. All subsequent system locking
1225** operations become no-ops. Locking operations still happen internally,
1226** in order to coordinate access between separate database connections
1227** within this process, but all of that is handled in memory and the
1228** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001229**
1230** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1231** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1232** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001233**
1234** Zero is returned if the call completes successfully, or -1 if a call
1235** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001236*/
1237static int unixFileLock(unixFile *pFile, struct flock *pLock){
1238 int rc;
drh3cb93392011-03-12 18:10:44 +00001239 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001240 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001241 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001242 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1243 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1244 ){
drh3cb93392011-03-12 18:10:44 +00001245 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001246 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001247 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001248 lock.l_whence = SEEK_SET;
1249 lock.l_start = SHARED_FIRST;
1250 lock.l_len = SHARED_SIZE;
1251 lock.l_type = F_WRLCK;
1252 rc = osFcntl(pFile->h, F_SETLK, &lock);
1253 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001254 pInode->bProcessLock = 1;
1255 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001256 }else{
1257 rc = 0;
1258 }
1259 }else{
1260 rc = osFcntl(pFile->h, F_SETLK, pLock);
1261 }
1262 return rc;
1263}
1264
1265/*
drh308c2a52010-05-14 11:30:18 +00001266** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001267** of the following:
1268**
drh2ac3ee92004-06-07 16:27:46 +00001269** (1) SHARED_LOCK
1270** (2) RESERVED_LOCK
1271** (3) PENDING_LOCK
1272** (4) EXCLUSIVE_LOCK
1273**
drhb3e04342004-06-08 00:47:47 +00001274** Sometimes when requesting one lock state, additional lock states
1275** are inserted in between. The locking might fail on one of the later
1276** transitions leaving the lock state different from what it started but
1277** still short of its goal. The following chart shows the allowed
1278** transitions and the inserted intermediate states:
1279**
1280** UNLOCKED -> SHARED
1281** SHARED -> RESERVED
1282** SHARED -> (PENDING) -> EXCLUSIVE
1283** RESERVED -> (PENDING) -> EXCLUSIVE
1284** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001285**
drha6abd042004-06-09 17:37:22 +00001286** This routine will only increase a lock. Use the sqlite3OsUnlock()
1287** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001288*/
drh308c2a52010-05-14 11:30:18 +00001289static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001290 /* The following describes the implementation of the various locks and
1291 ** lock transitions in terms of the POSIX advisory shared and exclusive
1292 ** lock primitives (called read-locks and write-locks below, to avoid
1293 ** confusion with SQLite lock names). The algorithms are complicated
1294 ** slightly in order to be compatible with windows systems simultaneously
1295 ** accessing the same database file, in case that is ever required.
1296 **
1297 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1298 ** byte', each single bytes at well known offsets, and the 'shared byte
1299 ** range', a range of 510 bytes at a well known offset.
1300 **
1301 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1302 ** byte'. If this is successful, a random byte from the 'shared byte
1303 ** range' is read-locked and the lock on the 'pending byte' released.
1304 **
danielk197790ba3bd2004-06-25 08:32:25 +00001305 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1306 ** A RESERVED lock is implemented by grabbing a write-lock on the
1307 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001308 **
1309 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001310 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1311 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1312 ** obtained, but existing SHARED locks are allowed to persist. A process
1313 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1314 ** This property is used by the algorithm for rolling back a journal file
1315 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001316 **
danielk197790ba3bd2004-06-25 08:32:25 +00001317 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1318 ** implemented by obtaining a write-lock on the entire 'shared byte
1319 ** range'. Since all other locks require a read-lock on one of the bytes
1320 ** within this range, this ensures that no other locks are held on the
1321 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001322 **
1323 ** The reason a single byte cannot be used instead of the 'shared byte
1324 ** range' is that some versions of windows do not support read-locks. By
1325 ** locking a random byte from a range, concurrent SHARED locks may exist
1326 ** even if the locking primitive used is always a write-lock.
1327 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001328 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001329 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001330 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001331 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001332 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001333
drh054889e2005-11-30 03:20:31 +00001334 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001335 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1336 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001337 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001338
1339 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001340 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001341 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001342 */
drh308c2a52010-05-14 11:30:18 +00001343 if( pFile->eFileLock>=eFileLock ){
1344 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1345 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001346 return SQLITE_OK;
1347 }
1348
drh0c2694b2009-09-03 16:23:44 +00001349 /* Make sure the locking sequence is correct.
1350 ** (1) We never move from unlocked to anything higher than shared lock.
1351 ** (2) SQLite never explicitly requests a pendig lock.
1352 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001353 */
drh308c2a52010-05-14 11:30:18 +00001354 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1355 assert( eFileLock!=PENDING_LOCK );
1356 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001357
drh8af6c222010-05-14 12:43:01 +00001358 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001359 */
drh6c7d5c52008-11-21 20:32:33 +00001360 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001361 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001362
danielk1977ad94b582007-08-20 06:44:22 +00001363 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001364 ** handle that precludes the requested lock, return BUSY.
1365 */
drh8af6c222010-05-14 12:43:01 +00001366 if( (pFile->eFileLock!=pInode->eFileLock &&
1367 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001368 ){
1369 rc = SQLITE_BUSY;
1370 goto end_lock;
1371 }
1372
1373 /* If a SHARED lock is requested, and some thread using this PID already
1374 ** has a SHARED or RESERVED lock, then increment reference counts and
1375 ** return SQLITE_OK.
1376 */
drh308c2a52010-05-14 11:30:18 +00001377 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001378 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001379 assert( eFileLock==SHARED_LOCK );
1380 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001381 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001382 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001383 pInode->nShared++;
1384 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001385 goto end_lock;
1386 }
1387
danielk19779a1d0ab2004-06-01 14:09:28 +00001388
drh3cde3bb2004-06-12 02:17:14 +00001389 /* A PENDING lock is needed before acquiring a SHARED lock and before
1390 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1391 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001392 */
drh0c2694b2009-09-03 16:23:44 +00001393 lock.l_len = 1L;
1394 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001395 if( eFileLock==SHARED_LOCK
1396 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001397 ){
drh308c2a52010-05-14 11:30:18 +00001398 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001399 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001400 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001401 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001402 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001403 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001404 pFile->lastErrno = tErrno;
1405 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001406 goto end_lock;
1407 }
drh3cde3bb2004-06-12 02:17:14 +00001408 }
1409
1410
1411 /* If control gets to this point, then actually go ahead and make
1412 ** operating system calls for the specified lock.
1413 */
drh308c2a52010-05-14 11:30:18 +00001414 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001415 assert( pInode->nShared==0 );
1416 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001417 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001418
drh2ac3ee92004-06-07 16:27:46 +00001419 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001420 lock.l_start = SHARED_FIRST;
1421 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001422 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001423 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001424 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001425 }
dan661d71a2011-03-30 19:08:03 +00001426
drh2ac3ee92004-06-07 16:27:46 +00001427 /* Drop the temporary PENDING lock */
1428 lock.l_start = PENDING_BYTE;
1429 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001430 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001431 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1432 /* This could happen with a network mount */
1433 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001434 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001435 }
dan661d71a2011-03-30 19:08:03 +00001436
1437 if( rc ){
1438 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001439 pFile->lastErrno = tErrno;
1440 }
dan661d71a2011-03-30 19:08:03 +00001441 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001442 }else{
drh308c2a52010-05-14 11:30:18 +00001443 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001444 pInode->nLock++;
1445 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001446 }
drh8af6c222010-05-14 12:43:01 +00001447 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001448 /* We are trying for an exclusive lock but another thread in this
1449 ** same process is still holding a shared lock. */
1450 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001451 }else{
drh3cde3bb2004-06-12 02:17:14 +00001452 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001453 ** assumed that there is a SHARED or greater lock on the file
1454 ** already.
1455 */
drh308c2a52010-05-14 11:30:18 +00001456 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001457 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001458
1459 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1460 if( eFileLock==RESERVED_LOCK ){
1461 lock.l_start = RESERVED_BYTE;
1462 lock.l_len = 1L;
1463 }else{
1464 lock.l_start = SHARED_FIRST;
1465 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001466 }
dan661d71a2011-03-30 19:08:03 +00001467
1468 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001469 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001470 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001471 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001472 pFile->lastErrno = tErrno;
1473 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001474 }
drhbbd42a62004-05-22 17:41:58 +00001475 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001476
drh8f941bc2009-01-14 23:03:40 +00001477
1478#ifndef NDEBUG
1479 /* Set up the transaction-counter change checking flags when
1480 ** transitioning from a SHARED to a RESERVED lock. The change
1481 ** from SHARED to RESERVED marks the beginning of a normal
1482 ** write operation (not a hot journal rollback).
1483 */
1484 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001485 && pFile->eFileLock<=SHARED_LOCK
1486 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001487 ){
1488 pFile->transCntrChng = 0;
1489 pFile->dbUpdate = 0;
1490 pFile->inNormalWrite = 1;
1491 }
1492#endif
1493
1494
danielk1977ecb2a962004-06-02 06:30:16 +00001495 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001496 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001497 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001498 }else if( eFileLock==EXCLUSIVE_LOCK ){
1499 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001500 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001501 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001502
1503end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001504 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001505 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1506 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001507 return rc;
1508}
1509
1510/*
dan08da86a2009-08-21 17:18:03 +00001511** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001512** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001513*/
1514static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001515 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001516 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001517 p->pNext = pInode->pUnused;
1518 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001519 pFile->h = -1;
1520 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001521}
1522
1523/*
drh308c2a52010-05-14 11:30:18 +00001524** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001525** must be either NO_LOCK or SHARED_LOCK.
1526**
1527** If the locking level of the file descriptor is already at or below
1528** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001529**
1530** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1531** the byte range is divided into 2 parts and the first part is unlocked then
1532** set to a read lock, then the other part is simply unlocked. This works
1533** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1534** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001535*/
drha7e61d82011-03-12 17:02:57 +00001536static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001537 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001538 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001539 struct flock lock;
1540 int rc = SQLITE_OK;
1541 int h;
drha6abd042004-06-09 17:37:22 +00001542
drh054889e2005-11-30 03:20:31 +00001543 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001544 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001545 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001546 getpid()));
drha6abd042004-06-09 17:37:22 +00001547
drh308c2a52010-05-14 11:30:18 +00001548 assert( eFileLock<=SHARED_LOCK );
1549 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001550 return SQLITE_OK;
1551 }
drh6c7d5c52008-11-21 20:32:33 +00001552 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001553 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001554 pInode = pFile->pInode;
1555 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001556 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001557 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001558 SimulateIOErrorBenign(1);
1559 SimulateIOError( h=(-1) )
1560 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001561
1562#ifndef NDEBUG
1563 /* When reducing a lock such that other processes can start
1564 ** reading the database file again, make sure that the
1565 ** transaction counter was updated if any part of the database
1566 ** file changed. If the transaction counter is not updated,
1567 ** other connections to the same file might not realize that
1568 ** the file has changed and hence might not know to flush their
1569 ** cache. The use of a stale cache can lead to database corruption.
1570 */
dan7c246102010-04-12 19:00:29 +00001571#if 0
drh8f941bc2009-01-14 23:03:40 +00001572 assert( pFile->inNormalWrite==0
1573 || pFile->dbUpdate==0
1574 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001575#endif
drh8f941bc2009-01-14 23:03:40 +00001576 pFile->inNormalWrite = 0;
1577#endif
1578
drh7ed97b92010-01-20 13:07:21 +00001579 /* downgrading to a shared lock on NFS involves clearing the write lock
1580 ** before establishing the readlock - to avoid a race condition we downgrade
1581 ** the lock in 2 blocks, so that part of the range will be covered by a
1582 ** write lock until the rest is covered by a read lock:
1583 ** 1: [WWWWW]
1584 ** 2: [....W]
1585 ** 3: [RRRRW]
1586 ** 4: [RRRR.]
1587 */
drh308c2a52010-05-14 11:30:18 +00001588 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001589
1590#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001591 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001592 assert( handleNFSUnlock==0 );
1593#endif
1594#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001595 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001596 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001597 off_t divSize = SHARED_SIZE - 1;
1598
1599 lock.l_type = F_UNLCK;
1600 lock.l_whence = SEEK_SET;
1601 lock.l_start = SHARED_FIRST;
1602 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001603 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001604 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001605 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001606 if( IS_LOCK_ERROR(rc) ){
1607 pFile->lastErrno = tErrno;
1608 }
1609 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001610 }
drh7ed97b92010-01-20 13:07:21 +00001611 lock.l_type = F_RDLCK;
1612 lock.l_whence = SEEK_SET;
1613 lock.l_start = SHARED_FIRST;
1614 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001615 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001616 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001617 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1618 if( IS_LOCK_ERROR(rc) ){
1619 pFile->lastErrno = tErrno;
1620 }
1621 goto end_unlock;
1622 }
1623 lock.l_type = F_UNLCK;
1624 lock.l_whence = SEEK_SET;
1625 lock.l_start = SHARED_FIRST+divSize;
1626 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001627 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001628 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001629 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001630 if( IS_LOCK_ERROR(rc) ){
1631 pFile->lastErrno = tErrno;
1632 }
1633 goto end_unlock;
1634 }
drh30f776f2011-02-25 03:25:07 +00001635 }else
1636#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1637 {
drh7ed97b92010-01-20 13:07:21 +00001638 lock.l_type = F_RDLCK;
1639 lock.l_whence = SEEK_SET;
1640 lock.l_start = SHARED_FIRST;
1641 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001642 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001643 /* In theory, the call to unixFileLock() cannot fail because another
1644 ** process is holding an incompatible lock. If it does, this
1645 ** indicates that the other process is not following the locking
1646 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1647 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1648 ** an assert to fail). */
1649 rc = SQLITE_IOERR_RDLOCK;
1650 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001651 goto end_unlock;
1652 }
drh9c105bb2004-10-02 20:38:28 +00001653 }
1654 }
drhbbd42a62004-05-22 17:41:58 +00001655 lock.l_type = F_UNLCK;
1656 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001657 lock.l_start = PENDING_BYTE;
1658 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001659 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001660 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001661 }else{
danea83bc62011-04-01 11:56:32 +00001662 rc = SQLITE_IOERR_UNLOCK;
1663 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001664 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001665 }
drhbbd42a62004-05-22 17:41:58 +00001666 }
drh308c2a52010-05-14 11:30:18 +00001667 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001668 /* Decrement the shared lock counter. Release the lock using an
1669 ** OS call only when all threads in this same process have released
1670 ** the lock.
1671 */
drh8af6c222010-05-14 12:43:01 +00001672 pInode->nShared--;
1673 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001674 lock.l_type = F_UNLCK;
1675 lock.l_whence = SEEK_SET;
1676 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001677 SimulateIOErrorBenign(1);
1678 SimulateIOError( h=(-1) )
1679 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001680 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001681 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001682 }else{
danea83bc62011-04-01 11:56:32 +00001683 rc = SQLITE_IOERR_UNLOCK;
1684 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001685 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001686 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001687 }
drha6abd042004-06-09 17:37:22 +00001688 }
1689
drhbbd42a62004-05-22 17:41:58 +00001690 /* Decrement the count of locks against this same file. When the
1691 ** count reaches zero, close any other file descriptors whose close
1692 ** was deferred because of outstanding locks.
1693 */
drh8af6c222010-05-14 12:43:01 +00001694 pInode->nLock--;
1695 assert( pInode->nLock>=0 );
1696 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001697 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001698 }
1699 }
aswift5b1a2562008-08-22 00:22:35 +00001700
1701end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001702 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001703 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001704 return rc;
drhbbd42a62004-05-22 17:41:58 +00001705}
1706
1707/*
drh308c2a52010-05-14 11:30:18 +00001708** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001709** must be either NO_LOCK or SHARED_LOCK.
1710**
1711** If the locking level of the file descriptor is already at or below
1712** the requested locking level, this routine is a no-op.
1713*/
drh308c2a52010-05-14 11:30:18 +00001714static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001715 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001716}
1717
1718/*
danielk1977e339d652008-06-28 11:23:00 +00001719** This function performs the parts of the "close file" operation
1720** common to all locking schemes. It closes the directory and file
1721** handles, if they are valid, and sets all fields of the unixFile
1722** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001723**
1724** It is *not* necessary to hold the mutex when this routine is called,
1725** even on VxWorks. A mutex will be acquired on VxWorks by the
1726** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001727*/
1728static int closeUnixFile(sqlite3_file *id){
1729 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001730 if( pFile->dirfd>=0 ){
1731 robust_close(pFile, pFile->dirfd, __LINE__);
1732 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001733 }
dan661d71a2011-03-30 19:08:03 +00001734 if( pFile->h>=0 ){
1735 robust_close(pFile, pFile->h, __LINE__);
1736 pFile->h = -1;
1737 }
1738#if OS_VXWORKS
1739 if( pFile->pId ){
1740 if( pFile->isDelete ){
1741 unlink(pFile->pId->zCanonicalName);
1742 }
1743 vxworksReleaseFileId(pFile->pId);
1744 pFile->pId = 0;
1745 }
1746#endif
1747 OSTRACE(("CLOSE %-3d\n", pFile->h));
1748 OpenCounter(-1);
1749 sqlite3_free(pFile->pUnused);
1750 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001751 return SQLITE_OK;
1752}
1753
1754/*
danielk1977e3026632004-06-22 11:29:02 +00001755** Close a file.
1756*/
danielk197762079062007-08-15 17:08:46 +00001757static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001758 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001759 unixFile *pFile = (unixFile *)id;
1760 unixUnlock(id, NO_LOCK);
1761 unixEnterMutex();
1762
1763 /* unixFile.pInode is always valid here. Otherwise, a different close
1764 ** routine (e.g. nolockClose()) would be called instead.
1765 */
1766 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1767 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1768 /* If there are outstanding locks, do not actually close the file just
1769 ** yet because that would clear those locks. Instead, add the file
1770 ** descriptor to pInode->pUnused list. It will be automatically closed
1771 ** when the last lock is cleared.
1772 */
1773 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001774 }
dan661d71a2011-03-30 19:08:03 +00001775 releaseInodeInfo(pFile);
1776 rc = closeUnixFile(id);
1777 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001778 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001779}
1780
drh734c9862008-11-28 15:37:20 +00001781/************** End of the posix advisory lock implementation *****************
1782******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001783
drh734c9862008-11-28 15:37:20 +00001784/******************************************************************************
1785****************************** No-op Locking **********************************
1786**
1787** Of the various locking implementations available, this is by far the
1788** simplest: locking is ignored. No attempt is made to lock the database
1789** file for reading or writing.
1790**
1791** This locking mode is appropriate for use on read-only databases
1792** (ex: databases that are burned into CD-ROM, for example.) It can
1793** also be used if the application employs some external mechanism to
1794** prevent simultaneous access of the same database by two or more
1795** database connections. But there is a serious risk of database
1796** corruption if this locking mode is used in situations where multiple
1797** database connections are accessing the same database file at the same
1798** time and one or more of those connections are writing.
1799*/
drhbfe66312006-10-03 17:40:40 +00001800
drh734c9862008-11-28 15:37:20 +00001801static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1802 UNUSED_PARAMETER(NotUsed);
1803 *pResOut = 0;
1804 return SQLITE_OK;
1805}
drh734c9862008-11-28 15:37:20 +00001806static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1807 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1808 return SQLITE_OK;
1809}
drh734c9862008-11-28 15:37:20 +00001810static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1811 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1812 return SQLITE_OK;
1813}
1814
1815/*
drh9b35ea62008-11-29 02:20:26 +00001816** Close the file.
drh734c9862008-11-28 15:37:20 +00001817*/
1818static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001819 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001820}
1821
1822/******************* End of the no-op lock implementation *********************
1823******************************************************************************/
1824
1825/******************************************************************************
1826************************* Begin dot-file Locking ******************************
1827**
drh0c2694b2009-09-03 16:23:44 +00001828** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001829** files in order to control access to the database. This works on just
1830** about every filesystem imaginable. But there are serious downsides:
1831**
1832** (1) There is zero concurrency. A single reader blocks all other
1833** connections from reading or writing the database.
1834**
1835** (2) An application crash or power loss can leave stale lock files
1836** sitting around that need to be cleared manually.
1837**
1838** Nevertheless, a dotlock is an appropriate locking mode for use if no
1839** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001840**
1841** Dotfile locking works by creating a file in the same directory as the
1842** database and with the same name but with a ".lock" extension added.
1843** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1844** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001845*/
1846
1847/*
1848** The file suffix added to the data base filename in order to create the
1849** lock file.
1850*/
1851#define DOTLOCK_SUFFIX ".lock"
1852
drh7708e972008-11-29 00:56:52 +00001853/*
1854** This routine checks if there is a RESERVED lock held on the specified
1855** file by this or any other process. If such a lock is held, set *pResOut
1856** to a non-zero value otherwise *pResOut is set to zero. The return value
1857** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1858**
1859** In dotfile locking, either a lock exists or it does not. So in this
1860** variation of CheckReservedLock(), *pResOut is set to true if any lock
1861** is held on the file and false if the file is unlocked.
1862*/
drh734c9862008-11-28 15:37:20 +00001863static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1864 int rc = SQLITE_OK;
1865 int reserved = 0;
1866 unixFile *pFile = (unixFile*)id;
1867
1868 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1869
1870 assert( pFile );
1871
1872 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001873 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001874 /* Either this connection or some other connection in the same process
1875 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001876 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001877 }else{
1878 /* The lock is held if and only if the lockfile exists */
1879 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001880 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001881 }
drh308c2a52010-05-14 11:30:18 +00001882 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001883 *pResOut = reserved;
1884 return rc;
1885}
1886
drh7708e972008-11-29 00:56:52 +00001887/*
drh308c2a52010-05-14 11:30:18 +00001888** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001889** of the following:
1890**
1891** (1) SHARED_LOCK
1892** (2) RESERVED_LOCK
1893** (3) PENDING_LOCK
1894** (4) EXCLUSIVE_LOCK
1895**
1896** Sometimes when requesting one lock state, additional lock states
1897** are inserted in between. The locking might fail on one of the later
1898** transitions leaving the lock state different from what it started but
1899** still short of its goal. The following chart shows the allowed
1900** transitions and the inserted intermediate states:
1901**
1902** UNLOCKED -> SHARED
1903** SHARED -> RESERVED
1904** SHARED -> (PENDING) -> EXCLUSIVE
1905** RESERVED -> (PENDING) -> EXCLUSIVE
1906** PENDING -> EXCLUSIVE
1907**
1908** This routine will only increase a lock. Use the sqlite3OsUnlock()
1909** routine to lower a locking level.
1910**
1911** With dotfile locking, we really only support state (4): EXCLUSIVE.
1912** But we track the other locking levels internally.
1913*/
drh308c2a52010-05-14 11:30:18 +00001914static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001915 unixFile *pFile = (unixFile*)id;
1916 int fd;
1917 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001918 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001919
drh7708e972008-11-29 00:56:52 +00001920
1921 /* If we have any lock, then the lock file already exists. All we have
1922 ** to do is adjust our internal record of the lock level.
1923 */
drh308c2a52010-05-14 11:30:18 +00001924 if( pFile->eFileLock > NO_LOCK ){
1925 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001926#if !OS_VXWORKS
1927 /* Always update the timestamp on the old file */
1928 utimes(zLockFile, NULL);
1929#endif
drh7708e972008-11-29 00:56:52 +00001930 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001931 }
1932
1933 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001934 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001935 if( fd<0 ){
1936 /* failed to open/create the file, someone else may have stolen the lock */
1937 int tErrno = errno;
1938 if( EEXIST == tErrno ){
1939 rc = SQLITE_BUSY;
1940 } else {
1941 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1942 if( IS_LOCK_ERROR(rc) ){
1943 pFile->lastErrno = tErrno;
1944 }
1945 }
drh7708e972008-11-29 00:56:52 +00001946 return rc;
drh734c9862008-11-28 15:37:20 +00001947 }
drh0e9365c2011-03-02 02:08:13 +00001948 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001949
1950 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001951 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001952 return rc;
1953}
1954
drh7708e972008-11-29 00:56:52 +00001955/*
drh308c2a52010-05-14 11:30:18 +00001956** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001957** must be either NO_LOCK or SHARED_LOCK.
1958**
1959** If the locking level of the file descriptor is already at or below
1960** the requested locking level, this routine is a no-op.
1961**
1962** When the locking level reaches NO_LOCK, delete the lock file.
1963*/
drh308c2a52010-05-14 11:30:18 +00001964static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001965 unixFile *pFile = (unixFile*)id;
1966 char *zLockFile = (char *)pFile->lockingContext;
1967
1968 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001969 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1970 pFile->eFileLock, getpid()));
1971 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001972
1973 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001974 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001975 return SQLITE_OK;
1976 }
drh7708e972008-11-29 00:56:52 +00001977
1978 /* To downgrade to shared, simply update our internal notion of the
1979 ** lock state. No need to mess with the file on disk.
1980 */
drh308c2a52010-05-14 11:30:18 +00001981 if( eFileLock==SHARED_LOCK ){
1982 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001983 return SQLITE_OK;
1984 }
1985
drh7708e972008-11-29 00:56:52 +00001986 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001987 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001988 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001989 int rc = 0;
1990 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001991 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00001992 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00001993 }
1994 if( IS_LOCK_ERROR(rc) ){
1995 pFile->lastErrno = tErrno;
1996 }
1997 return rc;
1998 }
drh308c2a52010-05-14 11:30:18 +00001999 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002000 return SQLITE_OK;
2001}
2002
2003/*
drh9b35ea62008-11-29 02:20:26 +00002004** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002005*/
2006static int dotlockClose(sqlite3_file *id) {
2007 int rc;
2008 if( id ){
2009 unixFile *pFile = (unixFile*)id;
2010 dotlockUnlock(id, NO_LOCK);
2011 sqlite3_free(pFile->lockingContext);
2012 }
drh734c9862008-11-28 15:37:20 +00002013 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002014 return rc;
2015}
2016/****************** End of the dot-file lock implementation *******************
2017******************************************************************************/
2018
2019/******************************************************************************
2020************************** Begin flock Locking ********************************
2021**
2022** Use the flock() system call to do file locking.
2023**
drh6b9d6dd2008-12-03 19:34:47 +00002024** flock() locking is like dot-file locking in that the various
2025** fine-grain locking levels supported by SQLite are collapsed into
2026** a single exclusive lock. In other words, SHARED, RESERVED, and
2027** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2028** still works when you do this, but concurrency is reduced since
2029** only a single process can be reading the database at a time.
2030**
drh734c9862008-11-28 15:37:20 +00002031** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2032** compiling for VXWORKS.
2033*/
2034#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002035
drh6b9d6dd2008-12-03 19:34:47 +00002036/*
drhff812312011-02-23 13:33:46 +00002037** Retry flock() calls that fail with EINTR
2038*/
2039#ifdef EINTR
2040static int robust_flock(int fd, int op){
2041 int rc;
2042 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2043 return rc;
2044}
2045#else
drh5c819272011-02-23 14:00:12 +00002046# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002047#endif
2048
2049
2050/*
drh6b9d6dd2008-12-03 19:34:47 +00002051** This routine checks if there is a RESERVED lock held on the specified
2052** file by this or any other process. If such a lock is held, set *pResOut
2053** to a non-zero value otherwise *pResOut is set to zero. The return value
2054** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2055*/
drh734c9862008-11-28 15:37:20 +00002056static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2057 int rc = SQLITE_OK;
2058 int reserved = 0;
2059 unixFile *pFile = (unixFile*)id;
2060
2061 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2062
2063 assert( pFile );
2064
2065 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002066 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002067 reserved = 1;
2068 }
2069
2070 /* Otherwise see if some other process holds it. */
2071 if( !reserved ){
2072 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002073 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002074 if( !lrc ){
2075 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002076 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002077 if ( lrc ) {
2078 int tErrno = errno;
2079 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002080 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002081 if( IS_LOCK_ERROR(lrc) ){
2082 pFile->lastErrno = tErrno;
2083 rc = lrc;
2084 }
2085 }
2086 } else {
2087 int tErrno = errno;
2088 reserved = 1;
2089 /* someone else might have it reserved */
2090 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2091 if( IS_LOCK_ERROR(lrc) ){
2092 pFile->lastErrno = tErrno;
2093 rc = lrc;
2094 }
2095 }
2096 }
drh308c2a52010-05-14 11:30:18 +00002097 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002098
2099#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2100 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2101 rc = SQLITE_OK;
2102 reserved=1;
2103 }
2104#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2105 *pResOut = reserved;
2106 return rc;
2107}
2108
drh6b9d6dd2008-12-03 19:34:47 +00002109/*
drh308c2a52010-05-14 11:30:18 +00002110** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002111** of the following:
2112**
2113** (1) SHARED_LOCK
2114** (2) RESERVED_LOCK
2115** (3) PENDING_LOCK
2116** (4) EXCLUSIVE_LOCK
2117**
2118** Sometimes when requesting one lock state, additional lock states
2119** are inserted in between. The locking might fail on one of the later
2120** transitions leaving the lock state different from what it started but
2121** still short of its goal. The following chart shows the allowed
2122** transitions and the inserted intermediate states:
2123**
2124** UNLOCKED -> SHARED
2125** SHARED -> RESERVED
2126** SHARED -> (PENDING) -> EXCLUSIVE
2127** RESERVED -> (PENDING) -> EXCLUSIVE
2128** PENDING -> EXCLUSIVE
2129**
2130** flock() only really support EXCLUSIVE locks. We track intermediate
2131** lock states in the sqlite3_file structure, but all locks SHARED or
2132** above are really EXCLUSIVE locks and exclude all other processes from
2133** access the file.
2134**
2135** This routine will only increase a lock. Use the sqlite3OsUnlock()
2136** routine to lower a locking level.
2137*/
drh308c2a52010-05-14 11:30:18 +00002138static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002139 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002140 unixFile *pFile = (unixFile*)id;
2141
2142 assert( pFile );
2143
2144 /* if we already have a lock, it is exclusive.
2145 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002146 if (pFile->eFileLock > NO_LOCK) {
2147 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002148 return SQLITE_OK;
2149 }
2150
2151 /* grab an exclusive lock */
2152
drhff812312011-02-23 13:33:46 +00002153 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002154 int tErrno = errno;
2155 /* didn't get, must be busy */
2156 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2157 if( IS_LOCK_ERROR(rc) ){
2158 pFile->lastErrno = tErrno;
2159 }
2160 } else {
2161 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002162 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002163 }
drh308c2a52010-05-14 11:30:18 +00002164 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2165 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002166#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2167 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2168 rc = SQLITE_BUSY;
2169 }
2170#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2171 return rc;
2172}
2173
drh6b9d6dd2008-12-03 19:34:47 +00002174
2175/*
drh308c2a52010-05-14 11:30:18 +00002176** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002177** must be either NO_LOCK or SHARED_LOCK.
2178**
2179** If the locking level of the file descriptor is already at or below
2180** the requested locking level, this routine is a no-op.
2181*/
drh308c2a52010-05-14 11:30:18 +00002182static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002183 unixFile *pFile = (unixFile*)id;
2184
2185 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002186 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2187 pFile->eFileLock, getpid()));
2188 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002189
2190 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002191 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002192 return SQLITE_OK;
2193 }
2194
2195 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002196 if (eFileLock==SHARED_LOCK) {
2197 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002198 return SQLITE_OK;
2199 }
2200
2201 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002202 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002203#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002204 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002205#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002206 return SQLITE_IOERR_UNLOCK;
2207 }else{
drh308c2a52010-05-14 11:30:18 +00002208 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002209 return SQLITE_OK;
2210 }
2211}
2212
2213/*
2214** Close a file.
2215*/
2216static int flockClose(sqlite3_file *id) {
2217 if( id ){
2218 flockUnlock(id, NO_LOCK);
2219 }
2220 return closeUnixFile(id);
2221}
2222
2223#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2224
2225/******************* End of the flock lock implementation *********************
2226******************************************************************************/
2227
2228/******************************************************************************
2229************************ Begin Named Semaphore Locking ************************
2230**
2231** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002232**
2233** Semaphore locking is like dot-lock and flock in that it really only
2234** supports EXCLUSIVE locking. Only a single process can read or write
2235** the database file at a time. This reduces potential concurrency, but
2236** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002237*/
2238#if OS_VXWORKS
2239
drh6b9d6dd2008-12-03 19:34:47 +00002240/*
2241** This routine checks if there is a RESERVED lock held on the specified
2242** file by this or any other process. If such a lock is held, set *pResOut
2243** to a non-zero value otherwise *pResOut is set to zero. The return value
2244** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2245*/
drh734c9862008-11-28 15:37:20 +00002246static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2247 int rc = SQLITE_OK;
2248 int reserved = 0;
2249 unixFile *pFile = (unixFile*)id;
2250
2251 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2252
2253 assert( pFile );
2254
2255 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002256 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002257 reserved = 1;
2258 }
2259
2260 /* Otherwise see if some other process holds it. */
2261 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002262 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002263 struct stat statBuf;
2264
2265 if( sem_trywait(pSem)==-1 ){
2266 int tErrno = errno;
2267 if( EAGAIN != tErrno ){
2268 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2269 pFile->lastErrno = tErrno;
2270 } else {
2271 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002272 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002273 }
2274 }else{
2275 /* we could have it if we want it */
2276 sem_post(pSem);
2277 }
2278 }
drh308c2a52010-05-14 11:30:18 +00002279 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002280
2281 *pResOut = reserved;
2282 return rc;
2283}
2284
drh6b9d6dd2008-12-03 19:34:47 +00002285/*
drh308c2a52010-05-14 11:30:18 +00002286** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002287** of the following:
2288**
2289** (1) SHARED_LOCK
2290** (2) RESERVED_LOCK
2291** (3) PENDING_LOCK
2292** (4) EXCLUSIVE_LOCK
2293**
2294** Sometimes when requesting one lock state, additional lock states
2295** are inserted in between. The locking might fail on one of the later
2296** transitions leaving the lock state different from what it started but
2297** still short of its goal. The following chart shows the allowed
2298** transitions and the inserted intermediate states:
2299**
2300** UNLOCKED -> SHARED
2301** SHARED -> RESERVED
2302** SHARED -> (PENDING) -> EXCLUSIVE
2303** RESERVED -> (PENDING) -> EXCLUSIVE
2304** PENDING -> EXCLUSIVE
2305**
2306** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2307** lock states in the sqlite3_file structure, but all locks SHARED or
2308** above are really EXCLUSIVE locks and exclude all other processes from
2309** access the file.
2310**
2311** This routine will only increase a lock. Use the sqlite3OsUnlock()
2312** routine to lower a locking level.
2313*/
drh308c2a52010-05-14 11:30:18 +00002314static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002315 unixFile *pFile = (unixFile*)id;
2316 int fd;
drh8af6c222010-05-14 12:43:01 +00002317 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002318 int rc = SQLITE_OK;
2319
2320 /* if we already have a lock, it is exclusive.
2321 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002322 if (pFile->eFileLock > NO_LOCK) {
2323 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002324 rc = SQLITE_OK;
2325 goto sem_end_lock;
2326 }
2327
2328 /* lock semaphore now but bail out when already locked. */
2329 if( sem_trywait(pSem)==-1 ){
2330 rc = SQLITE_BUSY;
2331 goto sem_end_lock;
2332 }
2333
2334 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002335 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002336
2337 sem_end_lock:
2338 return rc;
2339}
2340
drh6b9d6dd2008-12-03 19:34:47 +00002341/*
drh308c2a52010-05-14 11:30:18 +00002342** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002343** must be either NO_LOCK or SHARED_LOCK.
2344**
2345** If the locking level of the file descriptor is already at or below
2346** the requested locking level, this routine is a no-op.
2347*/
drh308c2a52010-05-14 11:30:18 +00002348static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002349 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002350 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002351
2352 assert( pFile );
2353 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002354 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2355 pFile->eFileLock, getpid()));
2356 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002357
2358 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002359 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002360 return SQLITE_OK;
2361 }
2362
2363 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002364 if (eFileLock==SHARED_LOCK) {
2365 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002366 return SQLITE_OK;
2367 }
2368
2369 /* no, really unlock. */
2370 if ( sem_post(pSem)==-1 ) {
2371 int rc, tErrno = errno;
2372 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2373 if( IS_LOCK_ERROR(rc) ){
2374 pFile->lastErrno = tErrno;
2375 }
2376 return rc;
2377 }
drh308c2a52010-05-14 11:30:18 +00002378 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002379 return SQLITE_OK;
2380}
2381
2382/*
2383 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002384 */
drh734c9862008-11-28 15:37:20 +00002385static int semClose(sqlite3_file *id) {
2386 if( id ){
2387 unixFile *pFile = (unixFile*)id;
2388 semUnlock(id, NO_LOCK);
2389 assert( pFile );
2390 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002391 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002392 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002393 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002394 }
2395 return SQLITE_OK;
2396}
2397
2398#endif /* OS_VXWORKS */
2399/*
2400** Named semaphore locking is only available on VxWorks.
2401**
2402*************** End of the named semaphore lock implementation ****************
2403******************************************************************************/
2404
2405
2406/******************************************************************************
2407*************************** Begin AFP Locking *********************************
2408**
2409** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2410** on Apple Macintosh computers - both OS9 and OSX.
2411**
2412** Third-party implementations of AFP are available. But this code here
2413** only works on OSX.
2414*/
2415
drhd2cb50b2009-01-09 21:41:17 +00002416#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002417/*
2418** The afpLockingContext structure contains all afp lock specific state
2419*/
drhbfe66312006-10-03 17:40:40 +00002420typedef struct afpLockingContext afpLockingContext;
2421struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002422 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002423 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002424};
2425
2426struct ByteRangeLockPB2
2427{
2428 unsigned long long offset; /* offset to first byte to lock */
2429 unsigned long long length; /* nbr of bytes to lock */
2430 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2431 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2432 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2433 int fd; /* file desc to assoc this lock with */
2434};
2435
drhfd131da2007-08-07 17:13:03 +00002436#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002437
drh6b9d6dd2008-12-03 19:34:47 +00002438/*
2439** This is a utility for setting or clearing a bit-range lock on an
2440** AFP filesystem.
2441**
2442** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2443*/
2444static int afpSetLock(
2445 const char *path, /* Name of the file to be locked or unlocked */
2446 unixFile *pFile, /* Open file descriptor on path */
2447 unsigned long long offset, /* First byte to be locked */
2448 unsigned long long length, /* Number of bytes to lock */
2449 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002450){
drh6b9d6dd2008-12-03 19:34:47 +00002451 struct ByteRangeLockPB2 pb;
2452 int err;
drhbfe66312006-10-03 17:40:40 +00002453
2454 pb.unLockFlag = setLockFlag ? 0 : 1;
2455 pb.startEndFlag = 0;
2456 pb.offset = offset;
2457 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002458 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002459
drh308c2a52010-05-14 11:30:18 +00002460 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002461 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002462 offset, length));
drhbfe66312006-10-03 17:40:40 +00002463 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2464 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002465 int rc;
2466 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002467 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2468 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002469#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2470 rc = SQLITE_BUSY;
2471#else
drh734c9862008-11-28 15:37:20 +00002472 rc = sqliteErrorFromPosixError(tErrno,
2473 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002474#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002475 if( IS_LOCK_ERROR(rc) ){
2476 pFile->lastErrno = tErrno;
2477 }
2478 return rc;
drhbfe66312006-10-03 17:40:40 +00002479 } else {
aswift5b1a2562008-08-22 00:22:35 +00002480 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002481 }
2482}
2483
drh6b9d6dd2008-12-03 19:34:47 +00002484/*
2485** This routine checks if there is a RESERVED lock held on the specified
2486** file by this or any other process. If such a lock is held, set *pResOut
2487** to a non-zero value otherwise *pResOut is set to zero. The return value
2488** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2489*/
danielk1977e339d652008-06-28 11:23:00 +00002490static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002491 int rc = SQLITE_OK;
2492 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002493 unixFile *pFile = (unixFile*)id;
2494
aswift5b1a2562008-08-22 00:22:35 +00002495 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2496
2497 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002498 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002499 if( context->reserved ){
2500 *pResOut = 1;
2501 return SQLITE_OK;
2502 }
drh8af6c222010-05-14 12:43:01 +00002503 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002504
2505 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002506 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002507 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002508 }
2509
2510 /* Otherwise see if some other process holds it.
2511 */
aswift5b1a2562008-08-22 00:22:35 +00002512 if( !reserved ){
2513 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002514 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002515 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002516 /* if we succeeded in taking the reserved lock, unlock it to restore
2517 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002518 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002519 } else {
2520 /* if we failed to get the lock then someone else must have it */
2521 reserved = 1;
2522 }
2523 if( IS_LOCK_ERROR(lrc) ){
2524 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002525 }
2526 }
drhbfe66312006-10-03 17:40:40 +00002527
drh7ed97b92010-01-20 13:07:21 +00002528 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002529 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002530
2531 *pResOut = reserved;
2532 return rc;
drhbfe66312006-10-03 17:40:40 +00002533}
2534
drh6b9d6dd2008-12-03 19:34:47 +00002535/*
drh308c2a52010-05-14 11:30:18 +00002536** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002537** of the following:
2538**
2539** (1) SHARED_LOCK
2540** (2) RESERVED_LOCK
2541** (3) PENDING_LOCK
2542** (4) EXCLUSIVE_LOCK
2543**
2544** Sometimes when requesting one lock state, additional lock states
2545** are inserted in between. The locking might fail on one of the later
2546** transitions leaving the lock state different from what it started but
2547** still short of its goal. The following chart shows the allowed
2548** transitions and the inserted intermediate states:
2549**
2550** UNLOCKED -> SHARED
2551** SHARED -> RESERVED
2552** SHARED -> (PENDING) -> EXCLUSIVE
2553** RESERVED -> (PENDING) -> EXCLUSIVE
2554** PENDING -> EXCLUSIVE
2555**
2556** This routine will only increase a lock. Use the sqlite3OsUnlock()
2557** routine to lower a locking level.
2558*/
drh308c2a52010-05-14 11:30:18 +00002559static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002560 int rc = SQLITE_OK;
2561 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002562 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002563 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002564
2565 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002566 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2567 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002568 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002569
drhbfe66312006-10-03 17:40:40 +00002570 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002571 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002572 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002573 */
drh308c2a52010-05-14 11:30:18 +00002574 if( pFile->eFileLock>=eFileLock ){
2575 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2576 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002577 return SQLITE_OK;
2578 }
2579
2580 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002581 ** (1) We never move from unlocked to anything higher than shared lock.
2582 ** (2) SQLite never explicitly requests a pendig lock.
2583 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002584 */
drh308c2a52010-05-14 11:30:18 +00002585 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2586 assert( eFileLock!=PENDING_LOCK );
2587 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002588
drh8af6c222010-05-14 12:43:01 +00002589 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002590 */
drh6c7d5c52008-11-21 20:32:33 +00002591 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002592 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002593
2594 /* If some thread using this PID has a lock via a different unixFile*
2595 ** handle that precludes the requested lock, return BUSY.
2596 */
drh8af6c222010-05-14 12:43:01 +00002597 if( (pFile->eFileLock!=pInode->eFileLock &&
2598 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002599 ){
2600 rc = SQLITE_BUSY;
2601 goto afp_end_lock;
2602 }
2603
2604 /* If a SHARED lock is requested, and some thread using this PID already
2605 ** has a SHARED or RESERVED lock, then increment reference counts and
2606 ** return SQLITE_OK.
2607 */
drh308c2a52010-05-14 11:30:18 +00002608 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002609 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002610 assert( eFileLock==SHARED_LOCK );
2611 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002612 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002613 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002614 pInode->nShared++;
2615 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002616 goto afp_end_lock;
2617 }
drhbfe66312006-10-03 17:40:40 +00002618
2619 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002620 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2621 ** be released.
2622 */
drh308c2a52010-05-14 11:30:18 +00002623 if( eFileLock==SHARED_LOCK
2624 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002625 ){
2626 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002627 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002628 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002629 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002630 goto afp_end_lock;
2631 }
2632 }
2633
2634 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002635 ** operating system calls for the specified lock.
2636 */
drh308c2a52010-05-14 11:30:18 +00002637 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002638 int lrc1, lrc2, lrc1Errno;
2639 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002640
drh8af6c222010-05-14 12:43:01 +00002641 assert( pInode->nShared==0 );
2642 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002643
2644 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002645 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002646 /* note that the quality of the randomness doesn't matter that much */
2647 lk = random();
drh8af6c222010-05-14 12:43:01 +00002648 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002649 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002650 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002651 if( IS_LOCK_ERROR(lrc1) ){
2652 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002653 }
aswift5b1a2562008-08-22 00:22:35 +00002654 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002655 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002656
aswift5b1a2562008-08-22 00:22:35 +00002657 if( IS_LOCK_ERROR(lrc1) ) {
2658 pFile->lastErrno = lrc1Errno;
2659 rc = lrc1;
2660 goto afp_end_lock;
2661 } else if( IS_LOCK_ERROR(lrc2) ){
2662 rc = lrc2;
2663 goto afp_end_lock;
2664 } else if( lrc1 != SQLITE_OK ) {
2665 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002666 } else {
drh308c2a52010-05-14 11:30:18 +00002667 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002668 pInode->nLock++;
2669 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002670 }
drh8af6c222010-05-14 12:43:01 +00002671 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002672 /* We are trying for an exclusive lock but another thread in this
2673 ** same process is still holding a shared lock. */
2674 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002675 }else{
2676 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2677 ** assumed that there is a SHARED or greater lock on the file
2678 ** already.
2679 */
2680 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002681 assert( 0!=pFile->eFileLock );
2682 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002683 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002684 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002685 if( !failed ){
2686 context->reserved = 1;
2687 }
drhbfe66312006-10-03 17:40:40 +00002688 }
drh308c2a52010-05-14 11:30:18 +00002689 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002690 /* Acquire an EXCLUSIVE lock */
2691
2692 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002693 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002694 */
drh6b9d6dd2008-12-03 19:34:47 +00002695 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002696 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002697 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002698 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002699 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002700 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002701 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002702 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002703 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2704 ** a critical I/O error
2705 */
2706 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2707 SQLITE_IOERR_LOCK;
2708 goto afp_end_lock;
2709 }
2710 }else{
aswift5b1a2562008-08-22 00:22:35 +00002711 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002712 }
2713 }
aswift5b1a2562008-08-22 00:22:35 +00002714 if( failed ){
2715 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002716 }
2717 }
2718
2719 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002720 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002721 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002722 }else if( eFileLock==EXCLUSIVE_LOCK ){
2723 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002724 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002725 }
2726
2727afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002728 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002729 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2730 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002731 return rc;
2732}
2733
2734/*
drh308c2a52010-05-14 11:30:18 +00002735** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002736** must be either NO_LOCK or SHARED_LOCK.
2737**
2738** If the locking level of the file descriptor is already at or below
2739** the requested locking level, this routine is a no-op.
2740*/
drh308c2a52010-05-14 11:30:18 +00002741static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002742 int rc = SQLITE_OK;
2743 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002744 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002745 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2746 int skipShared = 0;
2747#ifdef SQLITE_TEST
2748 int h = pFile->h;
2749#endif
drhbfe66312006-10-03 17:40:40 +00002750
2751 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002752 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002753 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002754 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002755
drh308c2a52010-05-14 11:30:18 +00002756 assert( eFileLock<=SHARED_LOCK );
2757 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002758 return SQLITE_OK;
2759 }
drh6c7d5c52008-11-21 20:32:33 +00002760 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002761 pInode = pFile->pInode;
2762 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002763 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002764 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002765 SimulateIOErrorBenign(1);
2766 SimulateIOError( h=(-1) )
2767 SimulateIOErrorBenign(0);
2768
2769#ifndef NDEBUG
2770 /* When reducing a lock such that other processes can start
2771 ** reading the database file again, make sure that the
2772 ** transaction counter was updated if any part of the database
2773 ** file changed. If the transaction counter is not updated,
2774 ** other connections to the same file might not realize that
2775 ** the file has changed and hence might not know to flush their
2776 ** cache. The use of a stale cache can lead to database corruption.
2777 */
2778 assert( pFile->inNormalWrite==0
2779 || pFile->dbUpdate==0
2780 || pFile->transCntrChng==1 );
2781 pFile->inNormalWrite = 0;
2782#endif
aswiftaebf4132008-11-21 00:10:35 +00002783
drh308c2a52010-05-14 11:30:18 +00002784 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002785 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002786 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002787 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002788 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002789 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2790 } else {
2791 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002792 }
2793 }
drh308c2a52010-05-14 11:30:18 +00002794 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002795 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002796 }
drh308c2a52010-05-14 11:30:18 +00002797 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002798 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2799 if( !rc ){
2800 context->reserved = 0;
2801 }
aswiftaebf4132008-11-21 00:10:35 +00002802 }
drh8af6c222010-05-14 12:43:01 +00002803 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2804 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002805 }
aswiftaebf4132008-11-21 00:10:35 +00002806 }
drh308c2a52010-05-14 11:30:18 +00002807 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002808
drh7ed97b92010-01-20 13:07:21 +00002809 /* Decrement the shared lock counter. Release the lock using an
2810 ** OS call only when all threads in this same process have released
2811 ** the lock.
2812 */
drh8af6c222010-05-14 12:43:01 +00002813 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2814 pInode->nShared--;
2815 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002816 SimulateIOErrorBenign(1);
2817 SimulateIOError( h=(-1) )
2818 SimulateIOErrorBenign(0);
2819 if( !skipShared ){
2820 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2821 }
2822 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002823 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002824 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002825 }
2826 }
2827 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002828 pInode->nLock--;
2829 assert( pInode->nLock>=0 );
2830 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002831 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002832 }
2833 }
drhbfe66312006-10-03 17:40:40 +00002834 }
drh7ed97b92010-01-20 13:07:21 +00002835
drh6c7d5c52008-11-21 20:32:33 +00002836 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002837 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002838 return rc;
2839}
2840
2841/*
drh339eb0b2008-03-07 15:34:11 +00002842** Close a file & cleanup AFP specific locking context
2843*/
danielk1977e339d652008-06-28 11:23:00 +00002844static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002845 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002846 if( id ){
2847 unixFile *pFile = (unixFile*)id;
2848 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002849 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002850 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002851 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002852 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002853 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002854 ** the last lock is cleared.
2855 */
dan08da86a2009-08-21 17:18:03 +00002856 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002857 }
danb0ac3e32010-06-16 10:55:42 +00002858 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002859 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002860 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002861 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002862 }
drh7ed97b92010-01-20 13:07:21 +00002863 return rc;
drhbfe66312006-10-03 17:40:40 +00002864}
2865
drhd2cb50b2009-01-09 21:41:17 +00002866#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002867/*
2868** The code above is the AFP lock implementation. The code is specific
2869** to MacOSX and does not work on other unix platforms. No alternative
2870** is available. If you don't compile for a mac, then the "unix-afp"
2871** VFS is not available.
2872**
2873********************* End of the AFP lock implementation **********************
2874******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002875
drh7ed97b92010-01-20 13:07:21 +00002876/******************************************************************************
2877*************************** Begin NFS Locking ********************************/
2878
2879#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2880/*
drh308c2a52010-05-14 11:30:18 +00002881 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002882 ** must be either NO_LOCK or SHARED_LOCK.
2883 **
2884 ** If the locking level of the file descriptor is already at or below
2885 ** the requested locking level, this routine is a no-op.
2886 */
drh308c2a52010-05-14 11:30:18 +00002887static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002888 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002889}
2890
2891#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2892/*
2893** The code above is the NFS lock implementation. The code is specific
2894** to MacOSX and does not work on other unix platforms. No alternative
2895** is available.
2896**
2897********************* End of the NFS lock implementation **********************
2898******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002899
2900/******************************************************************************
2901**************** Non-locking sqlite3_file methods *****************************
2902**
2903** The next division contains implementations for all methods of the
2904** sqlite3_file object other than the locking methods. The locking
2905** methods were defined in divisions above (one locking method per
2906** division). Those methods that are common to all locking modes
2907** are gather together into this division.
2908*/
drhbfe66312006-10-03 17:40:40 +00002909
2910/*
drh734c9862008-11-28 15:37:20 +00002911** Seek to the offset passed as the second argument, then read cnt
2912** bytes into pBuf. Return the number of bytes actually read.
2913**
2914** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2915** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2916** one system to another. Since SQLite does not define USE_PREAD
2917** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2918** See tickets #2741 and #2681.
2919**
2920** To avoid stomping the errno value on a failed read the lastErrno value
2921** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002922*/
drh734c9862008-11-28 15:37:20 +00002923static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2924 int got;
drh7ed97b92010-01-20 13:07:21 +00002925#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002926 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002927#endif
drh734c9862008-11-28 15:37:20 +00002928 TIMER_START;
2929#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002930 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002931 SimulateIOError( got = -1 );
2932#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002933 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002934 SimulateIOError( got = -1 );
2935#else
2936 newOffset = lseek(id->h, offset, SEEK_SET);
2937 SimulateIOError( newOffset-- );
2938 if( newOffset!=offset ){
2939 if( newOffset == -1 ){
2940 ((unixFile*)id)->lastErrno = errno;
2941 }else{
2942 ((unixFile*)id)->lastErrno = 0;
2943 }
2944 return -1;
2945 }
drhe562be52011-03-02 18:01:10 +00002946 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002947#endif
2948 TIMER_END;
2949 if( got<0 ){
2950 ((unixFile*)id)->lastErrno = errno;
2951 }
drh308c2a52010-05-14 11:30:18 +00002952 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002953 return got;
drhbfe66312006-10-03 17:40:40 +00002954}
2955
2956/*
drh734c9862008-11-28 15:37:20 +00002957** Read data from a file into a buffer. Return SQLITE_OK if all
2958** bytes were read successfully and SQLITE_IOERR if anything goes
2959** wrong.
drh339eb0b2008-03-07 15:34:11 +00002960*/
drh734c9862008-11-28 15:37:20 +00002961static int unixRead(
2962 sqlite3_file *id,
2963 void *pBuf,
2964 int amt,
2965 sqlite3_int64 offset
2966){
dan08da86a2009-08-21 17:18:03 +00002967 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002968 int got;
2969 assert( id );
drh08c6d442009-02-09 17:34:07 +00002970
dan08da86a2009-08-21 17:18:03 +00002971 /* If this is a database file (not a journal, master-journal or temp
2972 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002973#if 0
dane946c392009-08-22 11:39:46 +00002974 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002975 || offset>=PENDING_BYTE+512
2976 || offset+amt<=PENDING_BYTE
2977 );
dan7c246102010-04-12 19:00:29 +00002978#endif
drh08c6d442009-02-09 17:34:07 +00002979
dan08da86a2009-08-21 17:18:03 +00002980 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002981 if( got==amt ){
2982 return SQLITE_OK;
2983 }else if( got<0 ){
2984 /* lastErrno set by seekAndRead */
2985 return SQLITE_IOERR_READ;
2986 }else{
dan08da86a2009-08-21 17:18:03 +00002987 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002988 /* Unread parts of the buffer must be zero-filled */
2989 memset(&((char*)pBuf)[got], 0, amt-got);
2990 return SQLITE_IOERR_SHORT_READ;
2991 }
2992}
2993
2994/*
2995** Seek to the offset in id->offset then read cnt bytes into pBuf.
2996** Return the number of bytes actually read. Update the offset.
2997**
2998** To avoid stomping the errno value on a failed write the lastErrno value
2999** is set before returning.
3000*/
3001static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3002 int got;
drh7ed97b92010-01-20 13:07:21 +00003003#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003004 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003005#endif
drh734c9862008-11-28 15:37:20 +00003006 TIMER_START;
3007#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003008 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003009#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003010 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003011#else
3012 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003013 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003014 if( newOffset!=offset ){
3015 if( newOffset == -1 ){
3016 ((unixFile*)id)->lastErrno = errno;
3017 }else{
3018 ((unixFile*)id)->lastErrno = 0;
3019 }
3020 return -1;
3021 }
drhe562be52011-03-02 18:01:10 +00003022 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003023#endif
3024 TIMER_END;
3025 if( got<0 ){
3026 ((unixFile*)id)->lastErrno = errno;
3027 }
3028
drh308c2a52010-05-14 11:30:18 +00003029 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003030 return got;
3031}
3032
3033
3034/*
3035** Write data from a buffer into a file. Return SQLITE_OK on success
3036** or some other error code on failure.
3037*/
3038static int unixWrite(
3039 sqlite3_file *id,
3040 const void *pBuf,
3041 int amt,
3042 sqlite3_int64 offset
3043){
dan08da86a2009-08-21 17:18:03 +00003044 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003045 int wrote = 0;
3046 assert( id );
3047 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003048
dan08da86a2009-08-21 17:18:03 +00003049 /* If this is a database file (not a journal, master-journal or temp
3050 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003051#if 0
dane946c392009-08-22 11:39:46 +00003052 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003053 || offset>=PENDING_BYTE+512
3054 || offset+amt<=PENDING_BYTE
3055 );
dan7c246102010-04-12 19:00:29 +00003056#endif
drh08c6d442009-02-09 17:34:07 +00003057
drh8f941bc2009-01-14 23:03:40 +00003058#ifndef NDEBUG
3059 /* If we are doing a normal write to a database file (as opposed to
3060 ** doing a hot-journal rollback or a write to some file other than a
3061 ** normal database file) then record the fact that the database
3062 ** has changed. If the transaction counter is modified, record that
3063 ** fact too.
3064 */
dan08da86a2009-08-21 17:18:03 +00003065 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003066 pFile->dbUpdate = 1; /* The database has been modified */
3067 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003068 int rc;
drh8f941bc2009-01-14 23:03:40 +00003069 char oldCntr[4];
3070 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003071 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003072 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003073 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003074 pFile->transCntrChng = 1; /* The transaction counter has changed */
3075 }
3076 }
3077 }
3078#endif
3079
dan08da86a2009-08-21 17:18:03 +00003080 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003081 amt -= wrote;
3082 offset += wrote;
3083 pBuf = &((char*)pBuf)[wrote];
3084 }
3085 SimulateIOError(( wrote=(-1), amt=1 ));
3086 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003087
drh734c9862008-11-28 15:37:20 +00003088 if( amt>0 ){
3089 if( wrote<0 ){
3090 /* lastErrno set by seekAndWrite */
3091 return SQLITE_IOERR_WRITE;
3092 }else{
dan08da86a2009-08-21 17:18:03 +00003093 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003094 return SQLITE_FULL;
3095 }
3096 }
dan6e09d692010-07-27 18:34:15 +00003097
drh734c9862008-11-28 15:37:20 +00003098 return SQLITE_OK;
3099}
3100
3101#ifdef SQLITE_TEST
3102/*
3103** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003104** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003105*/
3106int sqlite3_sync_count = 0;
3107int sqlite3_fullsync_count = 0;
3108#endif
3109
3110/*
drh89240432009-03-25 01:06:01 +00003111** We do not trust systems to provide a working fdatasync(). Some do.
3112** Others do no. To be safe, we will stick with the (slower) fsync().
3113** If you know that your system does support fdatasync() correctly,
3114** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003115*/
drh89240432009-03-25 01:06:01 +00003116#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003117# define fdatasync fsync
3118#endif
3119
3120/*
3121** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3122** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3123** only available on Mac OS X. But that could change.
3124*/
3125#ifdef F_FULLFSYNC
3126# define HAVE_FULLFSYNC 1
3127#else
3128# define HAVE_FULLFSYNC 0
3129#endif
3130
3131
3132/*
3133** The fsync() system call does not work as advertised on many
3134** unix systems. The following procedure is an attempt to make
3135** it work better.
3136**
3137** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3138** for testing when we want to run through the test suite quickly.
3139** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3140** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3141** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003142**
3143** SQLite sets the dataOnly flag if the size of the file is unchanged.
3144** The idea behind dataOnly is that it should only write the file content
3145** to disk, not the inode. We only set dataOnly if the file size is
3146** unchanged since the file size is part of the inode. However,
3147** Ted Ts'o tells us that fdatasync() will also write the inode if the
3148** file size has changed. The only real difference between fdatasync()
3149** and fsync(), Ted tells us, is that fdatasync() will not flush the
3150** inode if the mtime or owner or other inode attributes have changed.
3151** We only care about the file size, not the other file attributes, so
3152** as far as SQLite is concerned, an fdatasync() is always adequate.
3153** So, we always use fdatasync() if it is available, regardless of
3154** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003155*/
3156static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003157 int rc;
drh734c9862008-11-28 15:37:20 +00003158
3159 /* The following "ifdef/elif/else/" block has the same structure as
3160 ** the one below. It is replicated here solely to avoid cluttering
3161 ** up the real code with the UNUSED_PARAMETER() macros.
3162 */
3163#ifdef SQLITE_NO_SYNC
3164 UNUSED_PARAMETER(fd);
3165 UNUSED_PARAMETER(fullSync);
3166 UNUSED_PARAMETER(dataOnly);
3167#elif HAVE_FULLFSYNC
3168 UNUSED_PARAMETER(dataOnly);
3169#else
3170 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003171 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003172#endif
3173
3174 /* Record the number of times that we do a normal fsync() and
3175 ** FULLSYNC. This is used during testing to verify that this procedure
3176 ** gets called with the correct arguments.
3177 */
3178#ifdef SQLITE_TEST
3179 if( fullSync ) sqlite3_fullsync_count++;
3180 sqlite3_sync_count++;
3181#endif
3182
3183 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3184 ** no-op
3185 */
3186#ifdef SQLITE_NO_SYNC
3187 rc = SQLITE_OK;
3188#elif HAVE_FULLFSYNC
3189 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003190 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003191 }else{
3192 rc = 1;
3193 }
3194 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003195 ** It shouldn't be possible for fullfsync to fail on the local
3196 ** file system (on OSX), so failure indicates that FULLFSYNC
3197 ** isn't supported for this file system. So, attempt an fsync
3198 ** and (for now) ignore the overhead of a superfluous fcntl call.
3199 ** It'd be better to detect fullfsync support once and avoid
3200 ** the fcntl call every time sync is called.
3201 */
drh734c9862008-11-28 15:37:20 +00003202 if( rc ) rc = fsync(fd);
3203
drh7ed97b92010-01-20 13:07:21 +00003204#elif defined(__APPLE__)
3205 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3206 ** so currently we default to the macro that redefines fdatasync to fsync
3207 */
3208 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003209#else
drh0b647ff2009-03-21 14:41:04 +00003210 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003211#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003212 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003213 rc = fsync(fd);
3214 }
drh0b647ff2009-03-21 14:41:04 +00003215#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003216#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3217
3218 if( OS_VXWORKS && rc!= -1 ){
3219 rc = 0;
3220 }
chw97185482008-11-17 08:05:31 +00003221 return rc;
drhbfe66312006-10-03 17:40:40 +00003222}
3223
drh734c9862008-11-28 15:37:20 +00003224/*
3225** Make sure all writes to a particular file are committed to disk.
3226**
3227** If dataOnly==0 then both the file itself and its metadata (file
3228** size, access time, etc) are synced. If dataOnly!=0 then only the
3229** file data is synced.
3230**
3231** Under Unix, also make sure that the directory entry for the file
3232** has been created by fsync-ing the directory that contains the file.
3233** If we do not do this and we encounter a power failure, the directory
3234** entry for the journal might not exist after we reboot. The next
3235** SQLite to access the file will not know that the journal exists (because
3236** the directory entry for the journal was never created) and the transaction
3237** will not roll back - possibly leading to database corruption.
3238*/
3239static int unixSync(sqlite3_file *id, int flags){
3240 int rc;
3241 unixFile *pFile = (unixFile*)id;
3242
3243 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3244 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3245
3246 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3247 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3248 || (flags&0x0F)==SQLITE_SYNC_FULL
3249 );
3250
3251 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3252 ** line is to test that doing so does not cause any problems.
3253 */
3254 SimulateDiskfullError( return SQLITE_FULL );
3255
3256 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003257 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003258 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3259 SimulateIOError( rc=1 );
3260 if( rc ){
3261 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003262 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003263 }
3264 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003265 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3266 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003267#ifndef SQLITE_DISABLE_DIRSYNC
3268 /* The directory sync is only attempted if full_fsync is
3269 ** turned off or unavailable. If a full_fsync occurred above,
3270 ** then the directory sync is superfluous.
3271 */
3272 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3273 /*
3274 ** We have received multiple reports of fsync() returning
3275 ** errors when applied to directories on certain file systems.
3276 ** A failed directory sync is not a big deal. So it seems
3277 ** better to ignore the error. Ticket #1657
3278 */
3279 /* pFile->lastErrno = errno; */
3280 /* return SQLITE_IOERR; */
3281 }
3282#endif
drh0e9365c2011-03-02 02:08:13 +00003283 /* Only need to sync once, so close the directory when we are done */
3284 robust_close(pFile, pFile->dirfd, __LINE__);
3285 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003286 }
3287 return rc;
3288}
3289
3290/*
3291** Truncate an open file to a specified size
3292*/
3293static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003294 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003295 int rc;
dan6e09d692010-07-27 18:34:15 +00003296 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003297 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003298
3299 /* If the user has configured a chunk-size for this file, truncate the
3300 ** file so that it consists of an integer number of chunks (i.e. the
3301 ** actual file size after the operation may be larger than the requested
3302 ** size).
3303 */
3304 if( pFile->szChunk ){
3305 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3306 }
3307
drhff812312011-02-23 13:33:46 +00003308 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003309 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003310 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003311 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003312 }else{
drh3313b142009-11-06 04:13:18 +00003313#ifndef NDEBUG
3314 /* If we are doing a normal write to a database file (as opposed to
3315 ** doing a hot-journal rollback or a write to some file other than a
3316 ** normal database file) and we truncate the file to zero length,
3317 ** that effectively updates the change counter. This might happen
3318 ** when restoring a database using the backup API from a zero-length
3319 ** source.
3320 */
dan6e09d692010-07-27 18:34:15 +00003321 if( pFile->inNormalWrite && nByte==0 ){
3322 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003323 }
3324#endif
3325
drh734c9862008-11-28 15:37:20 +00003326 return SQLITE_OK;
3327 }
3328}
3329
3330/*
3331** Determine the current size of a file in bytes
3332*/
3333static int unixFileSize(sqlite3_file *id, i64 *pSize){
3334 int rc;
3335 struct stat buf;
3336 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003337 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003338 SimulateIOError( rc=1 );
3339 if( rc!=0 ){
3340 ((unixFile*)id)->lastErrno = errno;
3341 return SQLITE_IOERR_FSTAT;
3342 }
3343 *pSize = buf.st_size;
3344
drh8af6c222010-05-14 12:43:01 +00003345 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003346 ** writes a single byte into that file in order to work around a bug
3347 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3348 ** layers, we need to report this file size as zero even though it is
3349 ** really 1. Ticket #3260.
3350 */
3351 if( *pSize==1 ) *pSize = 0;
3352
3353
3354 return SQLITE_OK;
3355}
3356
drhd2cb50b2009-01-09 21:41:17 +00003357#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003358/*
3359** Handler for proxy-locking file-control verbs. Defined below in the
3360** proxying locking division.
3361*/
3362static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003363#endif
drh715ff302008-12-03 22:32:44 +00003364
dan502019c2010-07-28 14:26:17 +00003365/*
3366** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3367** file-control operation.
3368**
3369** If the user has configured a chunk-size for this file, it could be
3370** that the file needs to be extended at this point. Otherwise, the
3371** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3372*/
3373static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3374 if( pFile->szChunk ){
3375 i64 nSize; /* Required file size */
3376 struct stat buf; /* Used to hold return values of fstat() */
3377
drh99ab3b12011-03-02 15:09:07 +00003378 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003379
3380 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3381 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003382
dan502019c2010-07-28 14:26:17 +00003383#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003384 /* The code below is handling the return value of osFallocate()
3385 ** correctly. posix_fallocate() is defined to "returns zero on success,
3386 ** or an error number on failure". See the manpage for details. */
3387 int err;
drhff812312011-02-23 13:33:46 +00003388 do{
dan661d71a2011-03-30 19:08:03 +00003389 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3390 }while( err==EINTR );
3391 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003392#else
3393 /* If the OS does not have posix_fallocate(), fake it. First use
3394 ** ftruncate() to set the file size, then write a single byte to
3395 ** the last byte in each block within the extended region. This
3396 ** is the same technique used by glibc to implement posix_fallocate()
3397 ** on systems that do not have a real fallocate() system call.
3398 */
3399 int nBlk = buf.st_blksize; /* File-system block size */
3400 i64 iWrite; /* Next offset to write to */
3401 int nWrite; /* Return value from seekAndWrite() */
3402
drhff812312011-02-23 13:33:46 +00003403 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003404 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003405 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003406 }
3407 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3408 do {
3409 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3410 iWrite += nBlk;
3411 } while( nWrite==1 && iWrite<nSize );
3412 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3413#endif
3414 }
3415 }
3416
3417 return SQLITE_OK;
3418}
danielk1977ad94b582007-08-20 06:44:22 +00003419
danielk1977e3026632004-06-22 11:29:02 +00003420/*
drh9e33c2c2007-08-31 18:34:59 +00003421** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003422*/
drhcc6bb3e2007-08-31 16:11:35 +00003423static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003424 switch( op ){
3425 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003426 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003427 return SQLITE_OK;
3428 }
drh7708e972008-11-29 00:56:52 +00003429 case SQLITE_LAST_ERRNO: {
3430 *(int*)pArg = ((unixFile*)id)->lastErrno;
3431 return SQLITE_OK;
3432 }
dan6e09d692010-07-27 18:34:15 +00003433 case SQLITE_FCNTL_CHUNK_SIZE: {
3434 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003435 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003436 }
drh9ff27ec2010-05-19 19:26:05 +00003437 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003438 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003439 }
drh8f941bc2009-01-14 23:03:40 +00003440#ifndef NDEBUG
3441 /* The pager calls this method to signal that it has done
3442 ** a rollback and that the database is therefore unchanged and
3443 ** it hence it is OK for the transaction change counter to be
3444 ** unchanged.
3445 */
3446 case SQLITE_FCNTL_DB_UNCHANGED: {
3447 ((unixFile*)id)->dbUpdate = 0;
3448 return SQLITE_OK;
3449 }
3450#endif
drhd2cb50b2009-01-09 21:41:17 +00003451#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003452 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003453 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003454 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003455 }
drhd2cb50b2009-01-09 21:41:17 +00003456#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003457 case SQLITE_FCNTL_SYNC_OMITTED: {
3458 return SQLITE_OK; /* A no-op */
3459 }
drh9e33c2c2007-08-31 18:34:59 +00003460 }
drh0b52b7d2011-01-26 19:46:22 +00003461 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003462}
3463
3464/*
danielk1977a3d4c882007-03-23 10:08:38 +00003465** Return the sector size in bytes of the underlying block device for
3466** the specified file. This is almost always 512 bytes, but may be
3467** larger for some devices.
3468**
3469** SQLite code assumes this function cannot fail. It also assumes that
3470** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003471** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003472** same for both.
3473*/
danielk1977397d65f2008-11-19 11:35:39 +00003474static int unixSectorSize(sqlite3_file *NotUsed){
3475 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003476 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003477}
3478
danielk197790949c22007-08-17 16:50:38 +00003479/*
danielk1977397d65f2008-11-19 11:35:39 +00003480** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003481*/
danielk1977397d65f2008-11-19 11:35:39 +00003482static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3483 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003484 return 0;
3485}
3486
drhd9e5c4f2010-05-12 18:01:39 +00003487#ifndef SQLITE_OMIT_WAL
3488
3489
3490/*
drhd91c68f2010-05-14 14:52:25 +00003491** Object used to represent an shared memory buffer.
3492**
3493** When multiple threads all reference the same wal-index, each thread
3494** has its own unixShm object, but they all point to a single instance
3495** of this unixShmNode object. In other words, each wal-index is opened
3496** only once per process.
3497**
3498** Each unixShmNode object is connected to a single unixInodeInfo object.
3499** We could coalesce this object into unixInodeInfo, but that would mean
3500** every open file that does not use shared memory (in other words, most
3501** open files) would have to carry around this extra information. So
3502** the unixInodeInfo object contains a pointer to this unixShmNode object
3503** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003504**
3505** unixMutexHeld() must be true when creating or destroying
3506** this object or while reading or writing the following fields:
3507**
3508** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003509**
3510** The following fields are read-only after the object is created:
3511**
3512** fid
3513** zFilename
3514**
drhd91c68f2010-05-14 14:52:25 +00003515** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003516** unixMutexHeld() is true when reading or writing any other field
3517** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003518*/
drhd91c68f2010-05-14 14:52:25 +00003519struct unixShmNode {
3520 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003521 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003522 char *zFilename; /* Name of the mmapped file */
3523 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003524 int szRegion; /* Size of shared-memory regions */
3525 int nRegion; /* Size of array apRegion */
3526 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003527 int nRef; /* Number of unixShm objects pointing to this */
3528 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003529#ifdef SQLITE_DEBUG
3530 u8 exclMask; /* Mask of exclusive locks held */
3531 u8 sharedMask; /* Mask of shared locks held */
3532 u8 nextShmId; /* Next available unixShm.id value */
3533#endif
3534};
3535
3536/*
drhd9e5c4f2010-05-12 18:01:39 +00003537** Structure used internally by this VFS to record the state of an
3538** open shared memory connection.
3539**
drhd91c68f2010-05-14 14:52:25 +00003540** The following fields are initialized when this object is created and
3541** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003542**
drhd91c68f2010-05-14 14:52:25 +00003543** unixShm.pFile
3544** unixShm.id
3545**
3546** All other fields are read/write. The unixShm.pFile->mutex must be held
3547** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003548*/
3549struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003550 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3551 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003552 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003553 u16 sharedMask; /* Mask of shared locks held */
3554 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003555#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003556 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003557#endif
3558};
3559
3560/*
drhd9e5c4f2010-05-12 18:01:39 +00003561** Constants used for locking
3562*/
drhbd9676c2010-06-23 17:58:38 +00003563#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003564#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003565
drhd9e5c4f2010-05-12 18:01:39 +00003566/*
drh73b64e42010-05-30 19:55:15 +00003567** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003568**
3569** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3570** otherwise.
3571*/
3572static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003573 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3574 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003575 int ofst, /* First byte of the locking range */
3576 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003577){
3578 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003579 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003580
drhd91c68f2010-05-14 14:52:25 +00003581 /* Access to the unixShmNode object is serialized by the caller */
3582 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003583
drh73b64e42010-05-30 19:55:15 +00003584 /* Shared locks never span more than one byte */
3585 assert( n==1 || lockType!=F_RDLCK );
3586
3587 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003588 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003589
drh3cb93392011-03-12 18:10:44 +00003590 if( pShmNode->h>=0 ){
3591 /* Initialize the locking parameters */
3592 memset(&f, 0, sizeof(f));
3593 f.l_type = lockType;
3594 f.l_whence = SEEK_SET;
3595 f.l_start = ofst;
3596 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003597
drh3cb93392011-03-12 18:10:44 +00003598 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3599 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3600 }
drhd9e5c4f2010-05-12 18:01:39 +00003601
3602 /* Update the global lock state and do debug tracing */
3603#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003604 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003605 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003606 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003607 if( rc==SQLITE_OK ){
3608 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003609 OSTRACE(("unlock %d ok", ofst));
3610 pShmNode->exclMask &= ~mask;
3611 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003612 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003613 OSTRACE(("read-lock %d ok", ofst));
3614 pShmNode->exclMask &= ~mask;
3615 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003616 }else{
3617 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003618 OSTRACE(("write-lock %d ok", ofst));
3619 pShmNode->exclMask |= mask;
3620 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003621 }
3622 }else{
3623 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003624 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003625 }else if( lockType==F_RDLCK ){
3626 OSTRACE(("read-lock failed"));
3627 }else{
3628 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003629 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003630 }
3631 }
drh20e1f082010-05-31 16:10:12 +00003632 OSTRACE((" - afterwards %03x,%03x\n",
3633 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003634 }
drhd9e5c4f2010-05-12 18:01:39 +00003635#endif
3636
3637 return rc;
3638}
3639
drhd9e5c4f2010-05-12 18:01:39 +00003640
3641/*
drhd91c68f2010-05-14 14:52:25 +00003642** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003643**
3644** This is not a VFS shared-memory method; it is a utility function called
3645** by VFS shared-memory methods.
3646*/
drhd91c68f2010-05-14 14:52:25 +00003647static void unixShmPurge(unixFile *pFd){
3648 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003649 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003650 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003651 int i;
drhd91c68f2010-05-14 14:52:25 +00003652 assert( p->pInode==pFd->pInode );
3653 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003654 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003655 if( p->h>=0 ){
3656 munmap(p->apRegion[i], p->szRegion);
3657 }else{
3658 sqlite3_free(p->apRegion[i]);
3659 }
dan13a3cb82010-06-11 19:04:21 +00003660 }
dan18801912010-06-14 14:07:50 +00003661 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003662 if( p->h>=0 ){
3663 robust_close(pFd, p->h, __LINE__);
3664 p->h = -1;
3665 }
drhd91c68f2010-05-14 14:52:25 +00003666 p->pInode->pShmNode = 0;
3667 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003668 }
3669}
3670
3671/*
danda9fe0c2010-07-13 18:44:03 +00003672** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003673** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003674**
drh7234c6d2010-06-19 15:10:09 +00003675** The file used to implement shared-memory is in the same directory
3676** as the open database file and has the same name as the open database
3677** file with the "-shm" suffix added. For example, if the database file
3678** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003679** for shared memory will be called "/home/user1/config.db-shm".
3680**
3681** Another approach to is to use files in /dev/shm or /dev/tmp or an
3682** some other tmpfs mount. But if a file in a different directory
3683** from the database file is used, then differing access permissions
3684** or a chroot() might cause two different processes on the same
3685** database to end up using different files for shared memory -
3686** meaning that their memory would not really be shared - resulting
3687** in database corruption. Nevertheless, this tmpfs file usage
3688** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3689** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3690** option results in an incompatible build of SQLite; builds of SQLite
3691** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3692** same database file at the same time, database corruption will likely
3693** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3694** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003695**
3696** When opening a new shared-memory file, if no other instances of that
3697** file are currently open, in this process or in other processes, then
3698** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003699**
3700** If the original database file (pDbFd) is using the "unix-excl" VFS
3701** that means that an exclusive lock is held on the database file and
3702** that no other processes are able to read or write the database. In
3703** that case, we do not really need shared memory. No shared memory
3704** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003705*/
danda9fe0c2010-07-13 18:44:03 +00003706static int unixOpenSharedMemory(unixFile *pDbFd){
3707 struct unixShm *p = 0; /* The connection to be opened */
3708 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3709 int rc; /* Result code */
3710 unixInodeInfo *pInode; /* The inode of fd */
3711 char *zShmFilename; /* Name of the file used for SHM */
3712 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003713
danda9fe0c2010-07-13 18:44:03 +00003714 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003715 p = sqlite3_malloc( sizeof(*p) );
3716 if( p==0 ) return SQLITE_NOMEM;
3717 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003718 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003719
danda9fe0c2010-07-13 18:44:03 +00003720 /* Check to see if a unixShmNode object already exists. Reuse an existing
3721 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003722 */
3723 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003724 pInode = pDbFd->pInode;
3725 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003726 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003727 struct stat sStat; /* fstat() info for database file */
3728
3729 /* Call fstat() to figure out the permissions on the database file. If
3730 ** a new *-shm file is created, an attempt will be made to create it
3731 ** with the same permissions. The actual permissions the file is created
3732 ** with are subject to the current umask setting.
3733 */
drh3cb93392011-03-12 18:10:44 +00003734 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003735 rc = SQLITE_IOERR_FSTAT;
3736 goto shm_open_err;
3737 }
3738
drha4ced192010-07-15 18:32:40 +00003739#ifdef SQLITE_SHM_DIRECTORY
3740 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3741#else
drh7234c6d2010-06-19 15:10:09 +00003742 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003743#endif
drh7234c6d2010-06-19 15:10:09 +00003744 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003745 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003746 rc = SQLITE_NOMEM;
3747 goto shm_open_err;
3748 }
drhd91c68f2010-05-14 14:52:25 +00003749 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003750 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003751#ifdef SQLITE_SHM_DIRECTORY
3752 sqlite3_snprintf(nShmFilename, zShmFilename,
3753 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3754 (u32)sStat.st_ino, (u32)sStat.st_dev);
3755#else
drh7234c6d2010-06-19 15:10:09 +00003756 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003757#endif
drhd91c68f2010-05-14 14:52:25 +00003758 pShmNode->h = -1;
3759 pDbFd->pInode->pShmNode = pShmNode;
3760 pShmNode->pInode = pDbFd->pInode;
3761 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3762 if( pShmNode->mutex==0 ){
3763 rc = SQLITE_NOMEM;
3764 goto shm_open_err;
3765 }
drhd9e5c4f2010-05-12 18:01:39 +00003766
drh3cb93392011-03-12 18:10:44 +00003767 if( pInode->bProcessLock==0 ){
3768 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3769 (sStat.st_mode & 0777));
3770 if( pShmNode->h<0 ){
3771 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3772 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003773 }
drh3cb93392011-03-12 18:10:44 +00003774
3775 /* Check to see if another process is holding the dead-man switch.
3776 ** If not, truncate the file to zero length.
3777 */
3778 rc = SQLITE_OK;
3779 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3780 if( robust_ftruncate(pShmNode->h, 0) ){
3781 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3782 }
3783 }
3784 if( rc==SQLITE_OK ){
3785 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3786 }
3787 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003788 }
drhd9e5c4f2010-05-12 18:01:39 +00003789 }
3790
drhd91c68f2010-05-14 14:52:25 +00003791 /* Make the new connection a child of the unixShmNode */
3792 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003793#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003794 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003795#endif
drhd91c68f2010-05-14 14:52:25 +00003796 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003797 pDbFd->pShm = p;
3798 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003799
3800 /* The reference count on pShmNode has already been incremented under
3801 ** the cover of the unixEnterMutex() mutex and the pointer from the
3802 ** new (struct unixShm) object to the pShmNode has been set. All that is
3803 ** left to do is to link the new object into the linked list starting
3804 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3805 ** mutex.
3806 */
3807 sqlite3_mutex_enter(pShmNode->mutex);
3808 p->pNext = pShmNode->pFirst;
3809 pShmNode->pFirst = p;
3810 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003811 return SQLITE_OK;
3812
3813 /* Jump here on any error */
3814shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003815 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003816 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003817 unixLeaveMutex();
3818 return rc;
3819}
3820
3821/*
danda9fe0c2010-07-13 18:44:03 +00003822** This function is called to obtain a pointer to region iRegion of the
3823** shared-memory associated with the database file fd. Shared-memory regions
3824** are numbered starting from zero. Each shared-memory region is szRegion
3825** bytes in size.
3826**
3827** If an error occurs, an error code is returned and *pp is set to NULL.
3828**
3829** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3830** region has not been allocated (by any client, including one running in a
3831** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3832** bExtend is non-zero and the requested shared-memory region has not yet
3833** been allocated, it is allocated by this function.
3834**
3835** If the shared-memory region has already been allocated or is allocated by
3836** this call as described above, then it is mapped into this processes
3837** address space (if it is not already), *pp is set to point to the mapped
3838** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003839*/
danda9fe0c2010-07-13 18:44:03 +00003840static int unixShmMap(
3841 sqlite3_file *fd, /* Handle open on database file */
3842 int iRegion, /* Region to retrieve */
3843 int szRegion, /* Size of regions */
3844 int bExtend, /* True to extend file if necessary */
3845 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003846){
danda9fe0c2010-07-13 18:44:03 +00003847 unixFile *pDbFd = (unixFile*)fd;
3848 unixShm *p;
3849 unixShmNode *pShmNode;
3850 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003851
danda9fe0c2010-07-13 18:44:03 +00003852 /* If the shared-memory file has not yet been opened, open it now. */
3853 if( pDbFd->pShm==0 ){
3854 rc = unixOpenSharedMemory(pDbFd);
3855 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003856 }
drhd9e5c4f2010-05-12 18:01:39 +00003857
danda9fe0c2010-07-13 18:44:03 +00003858 p = pDbFd->pShm;
3859 pShmNode = p->pShmNode;
3860 sqlite3_mutex_enter(pShmNode->mutex);
3861 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003862 assert( pShmNode->pInode==pDbFd->pInode );
3863 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3864 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003865
3866 if( pShmNode->nRegion<=iRegion ){
3867 char **apNew; /* New apRegion[] array */
3868 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3869 struct stat sStat; /* Used by fstat() */
3870
3871 pShmNode->szRegion = szRegion;
3872
drh3cb93392011-03-12 18:10:44 +00003873 if( pShmNode->h>=0 ){
3874 /* The requested region is not mapped into this processes address space.
3875 ** Check to see if it has been allocated (i.e. if the wal-index file is
3876 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003877 */
drh3cb93392011-03-12 18:10:44 +00003878 if( osFstat(pShmNode->h, &sStat) ){
3879 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003880 goto shmpage_out;
3881 }
drh3cb93392011-03-12 18:10:44 +00003882
3883 if( sStat.st_size<nByte ){
3884 /* The requested memory region does not exist. If bExtend is set to
3885 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3886 **
3887 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3888 ** the requested memory region.
3889 */
3890 if( !bExtend ) goto shmpage_out;
3891 if( robust_ftruncate(pShmNode->h, nByte) ){
3892 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3893 pShmNode->zFilename);
3894 goto shmpage_out;
3895 }
3896 }
danda9fe0c2010-07-13 18:44:03 +00003897 }
3898
3899 /* Map the requested memory region into this processes address space. */
3900 apNew = (char **)sqlite3_realloc(
3901 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3902 );
3903 if( !apNew ){
3904 rc = SQLITE_IOERR_NOMEM;
3905 goto shmpage_out;
3906 }
3907 pShmNode->apRegion = apNew;
3908 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003909 void *pMem;
3910 if( pShmNode->h>=0 ){
3911 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3912 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3913 );
3914 if( pMem==MAP_FAILED ){
3915 rc = SQLITE_IOERR;
3916 goto shmpage_out;
3917 }
3918 }else{
3919 pMem = sqlite3_malloc(szRegion);
3920 if( pMem==0 ){
3921 rc = SQLITE_NOMEM;
3922 goto shmpage_out;
3923 }
3924 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003925 }
3926 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3927 pShmNode->nRegion++;
3928 }
3929 }
3930
3931shmpage_out:
3932 if( pShmNode->nRegion>iRegion ){
3933 *pp = pShmNode->apRegion[iRegion];
3934 }else{
3935 *pp = 0;
3936 }
3937 sqlite3_mutex_leave(pShmNode->mutex);
3938 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003939}
3940
3941/*
drhd9e5c4f2010-05-12 18:01:39 +00003942** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003943**
3944** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3945** different here than in posix. In xShmLock(), one can go from unlocked
3946** to shared and back or from unlocked to exclusive and back. But one may
3947** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003948*/
3949static int unixShmLock(
3950 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003951 int ofst, /* First lock to acquire or release */
3952 int n, /* Number of locks to acquire or release */
3953 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003954){
drh73b64e42010-05-30 19:55:15 +00003955 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3956 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3957 unixShm *pX; /* For looping over all siblings */
3958 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3959 int rc = SQLITE_OK; /* Result code */
3960 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003961
drhd91c68f2010-05-14 14:52:25 +00003962 assert( pShmNode==pDbFd->pInode->pShmNode );
3963 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003964 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003965 assert( n>=1 );
3966 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3967 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3968 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3969 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3970 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003971 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3972 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003973
drhc99597c2010-05-31 01:41:15 +00003974 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003975 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003976 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003977 if( flags & SQLITE_SHM_UNLOCK ){
3978 u16 allMask = 0; /* Mask of locks held by siblings */
3979
3980 /* See if any siblings hold this same lock */
3981 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3982 if( pX==p ) continue;
3983 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3984 allMask |= pX->sharedMask;
3985 }
3986
3987 /* Unlock the system-level locks */
3988 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003989 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003990 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003991 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003992 }
drh73b64e42010-05-30 19:55:15 +00003993
3994 /* Undo the local locks */
3995 if( rc==SQLITE_OK ){
3996 p->exclMask &= ~mask;
3997 p->sharedMask &= ~mask;
3998 }
3999 }else if( flags & SQLITE_SHM_SHARED ){
4000 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4001
4002 /* Find out which shared locks are already held by sibling connections.
4003 ** If any sibling already holds an exclusive lock, go ahead and return
4004 ** SQLITE_BUSY.
4005 */
4006 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004007 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004008 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004009 break;
4010 }
4011 allShared |= pX->sharedMask;
4012 }
4013
4014 /* Get shared locks at the system level, if necessary */
4015 if( rc==SQLITE_OK ){
4016 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004017 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004018 }else{
drh73b64e42010-05-30 19:55:15 +00004019 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004020 }
drhd9e5c4f2010-05-12 18:01:39 +00004021 }
drh73b64e42010-05-30 19:55:15 +00004022
4023 /* Get the local shared locks */
4024 if( rc==SQLITE_OK ){
4025 p->sharedMask |= mask;
4026 }
4027 }else{
4028 /* Make sure no sibling connections hold locks that will block this
4029 ** lock. If any do, return SQLITE_BUSY right away.
4030 */
4031 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004032 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4033 rc = SQLITE_BUSY;
4034 break;
4035 }
4036 }
4037
4038 /* Get the exclusive locks at the system level. Then if successful
4039 ** also mark the local connection as being locked.
4040 */
4041 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004042 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004043 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004044 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004045 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004046 }
drhd9e5c4f2010-05-12 18:01:39 +00004047 }
4048 }
drhd91c68f2010-05-14 14:52:25 +00004049 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004050 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4051 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004052 return rc;
4053}
4054
drh286a2882010-05-20 23:51:06 +00004055/*
4056** Implement a memory barrier or memory fence on shared memory.
4057**
4058** All loads and stores begun before the barrier must complete before
4059** any load or store begun after the barrier.
4060*/
4061static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004062 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004063){
drhff828942010-06-26 21:34:06 +00004064 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004065 unixEnterMutex();
4066 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004067}
4068
dan18801912010-06-14 14:07:50 +00004069/*
danda9fe0c2010-07-13 18:44:03 +00004070** Close a connection to shared-memory. Delete the underlying
4071** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004072**
4073** If there is no shared memory associated with the connection then this
4074** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004075*/
danda9fe0c2010-07-13 18:44:03 +00004076static int unixShmUnmap(
4077 sqlite3_file *fd, /* The underlying database file */
4078 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004079){
danda9fe0c2010-07-13 18:44:03 +00004080 unixShm *p; /* The connection to be closed */
4081 unixShmNode *pShmNode; /* The underlying shared-memory file */
4082 unixShm **pp; /* For looping over sibling connections */
4083 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004084
danda9fe0c2010-07-13 18:44:03 +00004085 pDbFd = (unixFile*)fd;
4086 p = pDbFd->pShm;
4087 if( p==0 ) return SQLITE_OK;
4088 pShmNode = p->pShmNode;
4089
4090 assert( pShmNode==pDbFd->pInode->pShmNode );
4091 assert( pShmNode->pInode==pDbFd->pInode );
4092
4093 /* Remove connection p from the set of connections associated
4094 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004095 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004096 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4097 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004098
danda9fe0c2010-07-13 18:44:03 +00004099 /* Free the connection p */
4100 sqlite3_free(p);
4101 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004102 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004103
4104 /* If pShmNode->nRef has reached 0, then close the underlying
4105 ** shared-memory file, too */
4106 unixEnterMutex();
4107 assert( pShmNode->nRef>0 );
4108 pShmNode->nRef--;
4109 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004110 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004111 unixShmPurge(pDbFd);
4112 }
4113 unixLeaveMutex();
4114
4115 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004116}
drh286a2882010-05-20 23:51:06 +00004117
danda9fe0c2010-07-13 18:44:03 +00004118
drhd9e5c4f2010-05-12 18:01:39 +00004119#else
drh6b017cc2010-06-14 18:01:46 +00004120# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004121# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004122# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004123# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004124#endif /* #ifndef SQLITE_OMIT_WAL */
4125
drh734c9862008-11-28 15:37:20 +00004126/*
4127** Here ends the implementation of all sqlite3_file methods.
4128**
4129********************** End sqlite3_file Methods *******************************
4130******************************************************************************/
4131
4132/*
drh6b9d6dd2008-12-03 19:34:47 +00004133** This division contains definitions of sqlite3_io_methods objects that
4134** implement various file locking strategies. It also contains definitions
4135** of "finder" functions. A finder-function is used to locate the appropriate
4136** sqlite3_io_methods object for a particular database file. The pAppData
4137** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4138** the correct finder-function for that VFS.
4139**
4140** Most finder functions return a pointer to a fixed sqlite3_io_methods
4141** object. The only interesting finder-function is autolockIoFinder, which
4142** looks at the filesystem type and tries to guess the best locking
4143** strategy from that.
4144**
drh1875f7a2008-12-08 18:19:17 +00004145** For finder-funtion F, two objects are created:
4146**
4147** (1) The real finder-function named "FImpt()".
4148**
dane946c392009-08-22 11:39:46 +00004149** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004150**
4151**
4152** A pointer to the F pointer is used as the pAppData value for VFS
4153** objects. We have to do this instead of letting pAppData point
4154** directly at the finder-function since C90 rules prevent a void*
4155** from be cast into a function pointer.
4156**
drh6b9d6dd2008-12-03 19:34:47 +00004157**
drh7708e972008-11-29 00:56:52 +00004158** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004159**
drh7708e972008-11-29 00:56:52 +00004160** * A constant sqlite3_io_methods object call METHOD that has locking
4161** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4162**
4163** * An I/O method finder function called FINDER that returns a pointer
4164** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004165*/
drhd9e5c4f2010-05-12 18:01:39 +00004166#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004167static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004168 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004169 CLOSE, /* xClose */ \
4170 unixRead, /* xRead */ \
4171 unixWrite, /* xWrite */ \
4172 unixTruncate, /* xTruncate */ \
4173 unixSync, /* xSync */ \
4174 unixFileSize, /* xFileSize */ \
4175 LOCK, /* xLock */ \
4176 UNLOCK, /* xUnlock */ \
4177 CKLOCK, /* xCheckReservedLock */ \
4178 unixFileControl, /* xFileControl */ \
4179 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004180 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004181 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004182 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004183 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004184 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004185}; \
drh0c2694b2009-09-03 16:23:44 +00004186static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4187 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004188 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004189} \
drh0c2694b2009-09-03 16:23:44 +00004190static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004191 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004192
4193/*
4194** Here are all of the sqlite3_io_methods objects for each of the
4195** locking strategies. Functions that return pointers to these methods
4196** are also created.
4197*/
4198IOMETHODS(
4199 posixIoFinder, /* Finder function name */
4200 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004201 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004202 unixClose, /* xClose method */
4203 unixLock, /* xLock method */
4204 unixUnlock, /* xUnlock method */
4205 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004206)
drh7708e972008-11-29 00:56:52 +00004207IOMETHODS(
4208 nolockIoFinder, /* Finder function name */
4209 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004210 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004211 nolockClose, /* xClose method */
4212 nolockLock, /* xLock method */
4213 nolockUnlock, /* xUnlock method */
4214 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004215)
drh7708e972008-11-29 00:56:52 +00004216IOMETHODS(
4217 dotlockIoFinder, /* Finder function name */
4218 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004219 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004220 dotlockClose, /* xClose method */
4221 dotlockLock, /* xLock method */
4222 dotlockUnlock, /* xUnlock method */
4223 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004224)
drh7708e972008-11-29 00:56:52 +00004225
chw78a13182009-04-07 05:35:03 +00004226#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004227IOMETHODS(
4228 flockIoFinder, /* Finder function name */
4229 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004230 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004231 flockClose, /* xClose method */
4232 flockLock, /* xLock method */
4233 flockUnlock, /* xUnlock method */
4234 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004235)
drh7708e972008-11-29 00:56:52 +00004236#endif
4237
drh6c7d5c52008-11-21 20:32:33 +00004238#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004239IOMETHODS(
4240 semIoFinder, /* Finder function name */
4241 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004242 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004243 semClose, /* xClose method */
4244 semLock, /* xLock method */
4245 semUnlock, /* xUnlock method */
4246 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004247)
aswiftaebf4132008-11-21 00:10:35 +00004248#endif
drh7708e972008-11-29 00:56:52 +00004249
drhd2cb50b2009-01-09 21:41:17 +00004250#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004251IOMETHODS(
4252 afpIoFinder, /* Finder function name */
4253 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004254 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004255 afpClose, /* xClose method */
4256 afpLock, /* xLock method */
4257 afpUnlock, /* xUnlock method */
4258 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004259)
drh715ff302008-12-03 22:32:44 +00004260#endif
4261
4262/*
4263** The proxy locking method is a "super-method" in the sense that it
4264** opens secondary file descriptors for the conch and lock files and
4265** it uses proxy, dot-file, AFP, and flock() locking methods on those
4266** secondary files. For this reason, the division that implements
4267** proxy locking is located much further down in the file. But we need
4268** to go ahead and define the sqlite3_io_methods and finder function
4269** for proxy locking here. So we forward declare the I/O methods.
4270*/
drhd2cb50b2009-01-09 21:41:17 +00004271#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004272static int proxyClose(sqlite3_file*);
4273static int proxyLock(sqlite3_file*, int);
4274static int proxyUnlock(sqlite3_file*, int);
4275static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004276IOMETHODS(
4277 proxyIoFinder, /* Finder function name */
4278 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004279 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004280 proxyClose, /* xClose method */
4281 proxyLock, /* xLock method */
4282 proxyUnlock, /* xUnlock method */
4283 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004284)
aswiftaebf4132008-11-21 00:10:35 +00004285#endif
drh7708e972008-11-29 00:56:52 +00004286
drh7ed97b92010-01-20 13:07:21 +00004287/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4288#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4289IOMETHODS(
4290 nfsIoFinder, /* Finder function name */
4291 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004292 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004293 unixClose, /* xClose method */
4294 unixLock, /* xLock method */
4295 nfsUnlock, /* xUnlock method */
4296 unixCheckReservedLock /* xCheckReservedLock method */
4297)
4298#endif
drh7708e972008-11-29 00:56:52 +00004299
drhd2cb50b2009-01-09 21:41:17 +00004300#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004301/*
drh6b9d6dd2008-12-03 19:34:47 +00004302** This "finder" function attempts to determine the best locking strategy
4303** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004304** object that implements that strategy.
4305**
4306** This is for MacOSX only.
4307*/
drh1875f7a2008-12-08 18:19:17 +00004308static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004309 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004310 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004311){
4312 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004313 const char *zFilesystem; /* Filesystem type name */
4314 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004315 } aMap[] = {
4316 { "hfs", &posixIoMethods },
4317 { "ufs", &posixIoMethods },
4318 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004319 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004320 { "webdav", &nolockIoMethods },
4321 { 0, 0 }
4322 };
4323 int i;
4324 struct statfs fsInfo;
4325 struct flock lockInfo;
4326
4327 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004328 /* If filePath==NULL that means we are dealing with a transient file
4329 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004330 return &nolockIoMethods;
4331 }
4332 if( statfs(filePath, &fsInfo) != -1 ){
4333 if( fsInfo.f_flags & MNT_RDONLY ){
4334 return &nolockIoMethods;
4335 }
4336 for(i=0; aMap[i].zFilesystem; i++){
4337 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4338 return aMap[i].pMethods;
4339 }
4340 }
4341 }
4342
4343 /* Default case. Handles, amongst others, "nfs".
4344 ** Test byte-range lock using fcntl(). If the call succeeds,
4345 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004346 */
drh7708e972008-11-29 00:56:52 +00004347 lockInfo.l_len = 1;
4348 lockInfo.l_start = 0;
4349 lockInfo.l_whence = SEEK_SET;
4350 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004351 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004352 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4353 return &nfsIoMethods;
4354 } else {
4355 return &posixIoMethods;
4356 }
drh7708e972008-11-29 00:56:52 +00004357 }else{
4358 return &dotlockIoMethods;
4359 }
4360}
drh0c2694b2009-09-03 16:23:44 +00004361static const sqlite3_io_methods
4362 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004363
drhd2cb50b2009-01-09 21:41:17 +00004364#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004365
chw78a13182009-04-07 05:35:03 +00004366#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4367/*
4368** This "finder" function attempts to determine the best locking strategy
4369** for the database file "filePath". It then returns the sqlite3_io_methods
4370** object that implements that strategy.
4371**
4372** This is for VXWorks only.
4373*/
4374static const sqlite3_io_methods *autolockIoFinderImpl(
4375 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004376 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004377){
4378 struct flock lockInfo;
4379
4380 if( !filePath ){
4381 /* If filePath==NULL that means we are dealing with a transient file
4382 ** that does not need to be locked. */
4383 return &nolockIoMethods;
4384 }
4385
4386 /* Test if fcntl() is supported and use POSIX style locks.
4387 ** Otherwise fall back to the named semaphore method.
4388 */
4389 lockInfo.l_len = 1;
4390 lockInfo.l_start = 0;
4391 lockInfo.l_whence = SEEK_SET;
4392 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004393 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004394 return &posixIoMethods;
4395 }else{
4396 return &semIoMethods;
4397 }
4398}
drh0c2694b2009-09-03 16:23:44 +00004399static const sqlite3_io_methods
4400 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004401
4402#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4403
drh7708e972008-11-29 00:56:52 +00004404/*
4405** An abstract type for a pointer to a IO method finder function:
4406*/
drh0c2694b2009-09-03 16:23:44 +00004407typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004408
aswiftaebf4132008-11-21 00:10:35 +00004409
drh734c9862008-11-28 15:37:20 +00004410/****************************************************************************
4411**************************** sqlite3_vfs methods ****************************
4412**
4413** This division contains the implementation of methods on the
4414** sqlite3_vfs object.
4415*/
4416
danielk1977a3d4c882007-03-23 10:08:38 +00004417/*
danielk1977e339d652008-06-28 11:23:00 +00004418** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004419*/
4420static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004421 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004422 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004423 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004424 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004425 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004426 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004427 int isDelete, /* Delete on close if true */
4428 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004429){
drh7708e972008-11-29 00:56:52 +00004430 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004431 unixFile *pNew = (unixFile *)pId;
4432 int rc = SQLITE_OK;
4433
drh8af6c222010-05-14 12:43:01 +00004434 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004435
dane946c392009-08-22 11:39:46 +00004436 /* Parameter isDelete is only used on vxworks. Express this explicitly
4437 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004438 */
drh7708e972008-11-29 00:56:52 +00004439 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004440
dan00157392010-10-05 11:33:15 +00004441 /* Usually the path zFilename should not be a relative pathname. The
4442 ** exception is when opening the proxy "conch" file in builds that
4443 ** include the special Apple locking styles.
4444 */
dan00157392010-10-05 11:33:15 +00004445#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004446 assert( zFilename==0 || zFilename[0]=='/'
4447 || pVfs->pAppData==(void*)&autolockIoFinder );
4448#else
4449 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004450#endif
dan00157392010-10-05 11:33:15 +00004451
drh308c2a52010-05-14 11:30:18 +00004452 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004453 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004454 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004455 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004456 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4457 pNew->ctrlFlags = UNIXFILE_EXCL;
4458 }else{
4459 pNew->ctrlFlags = 0;
4460 }
drh77197112011-03-15 19:08:48 +00004461 if( isReadOnly ){
4462 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4463 }
drh339eb0b2008-03-07 15:34:11 +00004464
drh6c7d5c52008-11-21 20:32:33 +00004465#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004466 pNew->pId = vxworksFindFileId(zFilename);
4467 if( pNew->pId==0 ){
4468 noLock = 1;
4469 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004470 }
4471#endif
4472
drhda0e7682008-07-30 15:27:54 +00004473 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004474 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004475 }else{
drh0c2694b2009-09-03 16:23:44 +00004476 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004477#if SQLITE_ENABLE_LOCKING_STYLE
4478 /* Cache zFilename in the locking context (AFP and dotlock override) for
4479 ** proxyLock activation is possible (remote proxy is based on db name)
4480 ** zFilename remains valid until file is closed, to support */
4481 pNew->lockingContext = (void*)zFilename;
4482#endif
drhda0e7682008-07-30 15:27:54 +00004483 }
danielk1977e339d652008-06-28 11:23:00 +00004484
drh7ed97b92010-01-20 13:07:21 +00004485 if( pLockingStyle == &posixIoMethods
4486#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4487 || pLockingStyle == &nfsIoMethods
4488#endif
4489 ){
drh7708e972008-11-29 00:56:52 +00004490 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004491 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004492 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004493 /* If an error occured in findInodeInfo(), close the file descriptor
4494 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004495 ** in two scenarios:
4496 **
4497 ** (a) A call to fstat() failed.
4498 ** (b) A malloc failed.
4499 **
4500 ** Scenario (b) may only occur if the process is holding no other
4501 ** file descriptors open on the same file. If there were other file
4502 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004503 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004504 ** handle h - as it is guaranteed that no posix locks will be released
4505 ** by doing so.
4506 **
4507 ** If scenario (a) caused the error then things are not so safe. The
4508 ** implicit assumption here is that if fstat() fails, things are in
4509 ** such bad shape that dropping a lock or two doesn't matter much.
4510 */
drh0e9365c2011-03-02 02:08:13 +00004511 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004512 h = -1;
4513 }
drh7708e972008-11-29 00:56:52 +00004514 unixLeaveMutex();
4515 }
danielk1977e339d652008-06-28 11:23:00 +00004516
drhd2cb50b2009-01-09 21:41:17 +00004517#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004518 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004519 /* AFP locking uses the file path so it needs to be included in
4520 ** the afpLockingContext.
4521 */
4522 afpLockingContext *pCtx;
4523 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4524 if( pCtx==0 ){
4525 rc = SQLITE_NOMEM;
4526 }else{
4527 /* NB: zFilename exists and remains valid until the file is closed
4528 ** according to requirement F11141. So we do not need to make a
4529 ** copy of the filename. */
4530 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004531 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004532 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004533 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004534 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004535 if( rc!=SQLITE_OK ){
4536 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004537 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004538 h = -1;
4539 }
drh7708e972008-11-29 00:56:52 +00004540 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004541 }
drh7708e972008-11-29 00:56:52 +00004542 }
4543#endif
danielk1977e339d652008-06-28 11:23:00 +00004544
drh7708e972008-11-29 00:56:52 +00004545 else if( pLockingStyle == &dotlockIoMethods ){
4546 /* Dotfile locking uses the file path so it needs to be included in
4547 ** the dotlockLockingContext
4548 */
4549 char *zLockFile;
4550 int nFilename;
drhea678832008-12-10 19:26:22 +00004551 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004552 zLockFile = (char *)sqlite3_malloc(nFilename);
4553 if( zLockFile==0 ){
4554 rc = SQLITE_NOMEM;
4555 }else{
4556 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004557 }
drh7708e972008-11-29 00:56:52 +00004558 pNew->lockingContext = zLockFile;
4559 }
danielk1977e339d652008-06-28 11:23:00 +00004560
drh6c7d5c52008-11-21 20:32:33 +00004561#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004562 else if( pLockingStyle == &semIoMethods ){
4563 /* Named semaphore locking uses the file path so it needs to be
4564 ** included in the semLockingContext
4565 */
4566 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004567 rc = findInodeInfo(pNew, &pNew->pInode);
4568 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4569 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004570 int n;
drh2238dcc2009-08-27 17:56:20 +00004571 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004572 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004573 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004574 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004575 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4576 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004577 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004578 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004579 }
chw97185482008-11-17 08:05:31 +00004580 }
drh7708e972008-11-29 00:56:52 +00004581 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004582 }
drh7708e972008-11-29 00:56:52 +00004583#endif
aswift5b1a2562008-08-22 00:22:35 +00004584
4585 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004586#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004587 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004588 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004589 h = -1;
chw97185482008-11-17 08:05:31 +00004590 unlink(zFilename);
4591 isDelete = 0;
4592 }
4593 pNew->isDelete = isDelete;
4594#endif
danielk1977e339d652008-06-28 11:23:00 +00004595 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004596 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4597 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004598 }else{
drh7708e972008-11-29 00:56:52 +00004599 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004600 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004601 }
danielk1977e339d652008-06-28 11:23:00 +00004602 return rc;
drh054889e2005-11-30 03:20:31 +00004603}
drh9c06c952005-11-26 00:25:00 +00004604
danielk1977ad94b582007-08-20 06:44:22 +00004605/*
4606** Open a file descriptor to the directory containing file zFilename.
4607** If successful, *pFd is set to the opened file descriptor and
4608** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4609** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4610** value.
4611**
4612** If SQLITE_OK is returned, the caller is responsible for closing
4613** the file descriptor *pFd using close().
4614*/
danielk1977fee2d252007-08-18 10:59:19 +00004615static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004616 int ii;
drh777b17a2007-09-20 10:02:54 +00004617 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004618 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004619
drh153c62c2007-08-24 03:51:33 +00004620 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004621 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004622 if( ii>0 ){
4623 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004624 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004625 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004626#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004627 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004628#endif
drh308c2a52010-05-14 11:30:18 +00004629 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004630 }
4631 }
danielk1977fee2d252007-08-18 10:59:19 +00004632 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004633 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004634}
4635
danielk1977b4b47412007-08-17 15:53:36 +00004636/*
drh8b3cf822010-06-01 21:02:51 +00004637** Return the name of a directory in which to put temporary files.
4638** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004639*/
drh7234c6d2010-06-19 15:10:09 +00004640static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004641 static const char *azDirs[] = {
4642 0,
aswiftaebf4132008-11-21 00:10:35 +00004643 0,
danielk197717b90b52008-06-06 11:11:25 +00004644 "/var/tmp",
4645 "/usr/tmp",
4646 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004647 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004648 };
drh8b3cf822010-06-01 21:02:51 +00004649 unsigned int i;
4650 struct stat buf;
4651 const char *zDir = 0;
4652
4653 azDirs[0] = sqlite3_temp_directory;
4654 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004655 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004656 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004657 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004658 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004659 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004660 break;
4661 }
4662 return zDir;
4663}
4664
4665/*
4666** Create a temporary file name in zBuf. zBuf must be allocated
4667** by the calling process and must be big enough to hold at least
4668** pVfs->mxPathname bytes.
4669*/
4670static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004671 static const unsigned char zChars[] =
4672 "abcdefghijklmnopqrstuvwxyz"
4673 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4674 "0123456789";
drh41022642008-11-21 00:24:42 +00004675 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004676 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004677
4678 /* It's odd to simulate an io-error here, but really this is just
4679 ** using the io-error infrastructure to test that SQLite handles this
4680 ** function failing.
4681 */
4682 SimulateIOError( return SQLITE_IOERR );
4683
drh7234c6d2010-06-19 15:10:09 +00004684 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004685 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004686
4687 /* Check that the output buffer is large enough for the temporary file
4688 ** name. If it is not, return SQLITE_ERROR.
4689 */
danielk197700e13612008-11-17 19:18:54 +00004690 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004691 return SQLITE_ERROR;
4692 }
4693
4694 do{
4695 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004696 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004697 sqlite3_randomness(15, &zBuf[j]);
4698 for(i=0; i<15; i++, j++){
4699 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4700 }
4701 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004702 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004703 return SQLITE_OK;
4704}
4705
drhd2cb50b2009-01-09 21:41:17 +00004706#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004707/*
4708** Routine to transform a unixFile into a proxy-locking unixFile.
4709** Implementation in the proxy-lock division, but used by unixOpen()
4710** if SQLITE_PREFER_PROXY_LOCKING is defined.
4711*/
4712static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004713#endif
drhc66d5b62008-12-03 22:48:32 +00004714
dan08da86a2009-08-21 17:18:03 +00004715/*
4716** Search for an unused file descriptor that was opened on the database
4717** file (not a journal or master-journal file) identified by pathname
4718** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4719** argument to this function.
4720**
4721** Such a file descriptor may exist if a database connection was closed
4722** but the associated file descriptor could not be closed because some
4723** other file descriptor open on the same file is holding a file-lock.
4724** Refer to comments in the unixClose() function and the lengthy comment
4725** describing "Posix Advisory Locking" at the start of this file for
4726** further details. Also, ticket #4018.
4727**
4728** If a suitable file descriptor is found, then it is returned. If no
4729** such file descriptor is located, -1 is returned.
4730*/
dane946c392009-08-22 11:39:46 +00004731static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4732 UnixUnusedFd *pUnused = 0;
4733
4734 /* Do not search for an unused file descriptor on vxworks. Not because
4735 ** vxworks would not benefit from the change (it might, we're not sure),
4736 ** but because no way to test it is currently available. It is better
4737 ** not to risk breaking vxworks support for the sake of such an obscure
4738 ** feature. */
4739#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004740 struct stat sStat; /* Results of stat() call */
4741
4742 /* A stat() call may fail for various reasons. If this happens, it is
4743 ** almost certain that an open() call on the same path will also fail.
4744 ** For this reason, if an error occurs in the stat() call here, it is
4745 ** ignored and -1 is returned. The caller will try to open a new file
4746 ** descriptor on the same path, fail, and return an error to SQLite.
4747 **
4748 ** Even if a subsequent open() call does succeed, the consequences of
4749 ** not searching for a resusable file descriptor are not dire. */
4750 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004751 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004752
4753 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004754 pInode = inodeList;
4755 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4756 || pInode->fileId.ino!=sStat.st_ino) ){
4757 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004758 }
drh8af6c222010-05-14 12:43:01 +00004759 if( pInode ){
dane946c392009-08-22 11:39:46 +00004760 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004761 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004762 pUnused = *pp;
4763 if( pUnused ){
4764 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004765 }
4766 }
4767 unixLeaveMutex();
4768 }
dane946c392009-08-22 11:39:46 +00004769#endif /* if !OS_VXWORKS */
4770 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004771}
danielk197717b90b52008-06-06 11:11:25 +00004772
4773/*
danddb0ac42010-07-14 14:48:58 +00004774** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004775** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004776** and a value suitable for passing as the third argument to open(2) is
4777** written to *pMode. If an IO error occurs, an SQLite error code is
4778** returned and the value of *pMode is not modified.
4779**
4780** If the file being opened is a temporary file, it is always created with
4781** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004782** is a database or master journal file, it is created with the permissions
4783** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004784**
drh8ab58662010-07-15 18:38:39 +00004785** Finally, if the file being opened is a WAL or regular journal file, then
4786** this function queries the file-system for the permissions on the
4787** corresponding database file and sets *pMode to this value. Whenever
4788** possible, WAL and journal files are created using the same permissions
4789** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004790*/
4791static int findCreateFileMode(
4792 const char *zPath, /* Path of file (possibly) being created */
4793 int flags, /* Flags passed as 4th argument to xOpen() */
4794 mode_t *pMode /* OUT: Permissions to open file with */
4795){
4796 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004797 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004798 char zDb[MAX_PATHNAME+1]; /* Database file path */
4799 int nDb; /* Number of valid bytes in zDb */
4800 struct stat sStat; /* Output of stat() on database file */
4801
dana0c989d2010-11-05 18:07:37 +00004802 /* zPath is a path to a WAL or journal file. The following block derives
4803 ** the path to the associated database file from zPath. This block handles
4804 ** the following naming conventions:
4805 **
4806 ** "<path to db>-journal"
4807 ** "<path to db>-wal"
4808 ** "<path to db>-journal-NNNN"
4809 ** "<path to db>-wal-NNNN"
4810 **
4811 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4812 ** used by the test_multiplex.c module.
4813 */
4814 nDb = sqlite3Strlen30(zPath) - 1;
4815 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4816 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004817 memcpy(zDb, zPath, nDb);
4818 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004819
danddb0ac42010-07-14 14:48:58 +00004820 if( 0==stat(zDb, &sStat) ){
4821 *pMode = sStat.st_mode & 0777;
4822 }else{
4823 rc = SQLITE_IOERR_FSTAT;
4824 }
4825 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4826 *pMode = 0600;
4827 }else{
4828 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4829 }
4830 return rc;
4831}
4832
4833/*
danielk1977ad94b582007-08-20 06:44:22 +00004834** Open the file zPath.
4835**
danielk1977b4b47412007-08-17 15:53:36 +00004836** Previously, the SQLite OS layer used three functions in place of this
4837** one:
4838**
4839** sqlite3OsOpenReadWrite();
4840** sqlite3OsOpenReadOnly();
4841** sqlite3OsOpenExclusive();
4842**
4843** These calls correspond to the following combinations of flags:
4844**
4845** ReadWrite() -> (READWRITE | CREATE)
4846** ReadOnly() -> (READONLY)
4847** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4848**
4849** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4850** true, the file was configured to be automatically deleted when the
4851** file handle closed. To achieve the same effect using this new
4852** interface, add the DELETEONCLOSE flag to those specified above for
4853** OpenExclusive().
4854*/
4855static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004856 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4857 const char *zPath, /* Pathname of file to be opened */
4858 sqlite3_file *pFile, /* The file descriptor to be filled in */
4859 int flags, /* Input flags to control the opening */
4860 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004861){
dan08da86a2009-08-21 17:18:03 +00004862 unixFile *p = (unixFile *)pFile;
4863 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004864 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004865 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004866 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004867 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004868 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004869
4870 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4871 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4872 int isCreate = (flags & SQLITE_OPEN_CREATE);
4873 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4874 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004875#if SQLITE_ENABLE_LOCKING_STYLE
4876 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4877#endif
danielk1977b4b47412007-08-17 15:53:36 +00004878
danielk1977fee2d252007-08-18 10:59:19 +00004879 /* If creating a master or main-file journal, this function will open
4880 ** a file-descriptor on the directory too. The first time unixSync()
4881 ** is called the directory file descriptor will be fsync()ed and close()d.
4882 */
danddb0ac42010-07-14 14:48:58 +00004883 int isOpenDirectory = (isCreate && (
4884 eType==SQLITE_OPEN_MASTER_JOURNAL
4885 || eType==SQLITE_OPEN_MAIN_JOURNAL
4886 || eType==SQLITE_OPEN_WAL
4887 ));
danielk1977fee2d252007-08-18 10:59:19 +00004888
danielk197717b90b52008-06-06 11:11:25 +00004889 /* If argument zPath is a NULL pointer, this function is required to open
4890 ** a temporary file. Use this buffer to store the file name in.
4891 */
4892 char zTmpname[MAX_PATHNAME+1];
4893 const char *zName = zPath;
4894
danielk1977fee2d252007-08-18 10:59:19 +00004895 /* Check the following statements are true:
4896 **
4897 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4898 ** (b) if CREATE is set, then READWRITE must also be set, and
4899 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004900 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004901 */
danielk1977b4b47412007-08-17 15:53:36 +00004902 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004903 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004904 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004905 assert(isDelete==0 || isCreate);
4906
danddb0ac42010-07-14 14:48:58 +00004907 /* The main DB, main journal, WAL file and master journal are never
4908 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004909 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4910 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4911 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004912 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004913
danielk1977fee2d252007-08-18 10:59:19 +00004914 /* Assert that the upper layer has set one of the "file-type" flags. */
4915 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4916 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4917 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004918 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004919 );
4920
dan08da86a2009-08-21 17:18:03 +00004921 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004922
dan08da86a2009-08-21 17:18:03 +00004923 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004924 UnixUnusedFd *pUnused;
4925 pUnused = findReusableFd(zName, flags);
4926 if( pUnused ){
4927 fd = pUnused->fd;
4928 }else{
dan6aa657f2009-08-24 18:57:58 +00004929 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004930 if( !pUnused ){
4931 return SQLITE_NOMEM;
4932 }
4933 }
4934 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004935 }else if( !zName ){
4936 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004937 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004938 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004939 if( rc!=SQLITE_OK ){
4940 return rc;
4941 }
4942 zName = zTmpname;
4943 }
4944
dan08da86a2009-08-21 17:18:03 +00004945 /* Determine the value of the flags parameter passed to POSIX function
4946 ** open(). These must be calculated even if open() is not called, as
4947 ** they may be stored as part of the file handle and used by the
4948 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004949 if( isReadonly ) openFlags |= O_RDONLY;
4950 if( isReadWrite ) openFlags |= O_RDWR;
4951 if( isCreate ) openFlags |= O_CREAT;
4952 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4953 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004954
danielk1977b4b47412007-08-17 15:53:36 +00004955 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004956 mode_t openMode; /* Permissions to create file with */
4957 rc = findCreateFileMode(zName, flags, &openMode);
4958 if( rc!=SQLITE_OK ){
4959 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004960 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004961 return rc;
4962 }
drhad4f1e52011-03-04 15:43:57 +00004963 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004964 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004965 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4966 /* Failed to open the file for read/write access. Try read-only. */
4967 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004968 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004969 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004970 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00004971 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00004972 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004973 }
4974 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004975 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004976 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004977 }
danielk1977b4b47412007-08-17 15:53:36 +00004978 }
dan08da86a2009-08-21 17:18:03 +00004979 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004980 if( pOutFlags ){
4981 *pOutFlags = flags;
4982 }
4983
dane946c392009-08-22 11:39:46 +00004984 if( p->pUnused ){
4985 p->pUnused->fd = fd;
4986 p->pUnused->flags = flags;
4987 }
4988
danielk1977b4b47412007-08-17 15:53:36 +00004989 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004990#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004991 zPath = zName;
4992#else
danielk197717b90b52008-06-06 11:11:25 +00004993 unlink(zName);
chw97185482008-11-17 08:05:31 +00004994#endif
danielk1977b4b47412007-08-17 15:53:36 +00004995 }
drh41022642008-11-21 00:24:42 +00004996#if SQLITE_ENABLE_LOCKING_STYLE
4997 else{
dan08da86a2009-08-21 17:18:03 +00004998 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004999 }
5000#endif
5001
danielk1977fee2d252007-08-18 10:59:19 +00005002 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005003 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005004 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005005 /* It is safe to close fd at this point, because it is guaranteed not
5006 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005007 ** it would not be safe to close as this would release any locks held
5008 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005009 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005010 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005011 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005012 }
5013 }
danielk1977e339d652008-06-28 11:23:00 +00005014
5015#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005016 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005017#endif
5018
drhda0e7682008-07-30 15:27:54 +00005019 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005020
drh7ed97b92010-01-20 13:07:21 +00005021
5022#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5023 struct statfs fsInfo;
5024 if( fstatfs(fd, &fsInfo) == -1 ){
5025 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005026 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5027 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005028 return SQLITE_IOERR_ACCESS;
5029 }
5030 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5031 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5032 }
5033#endif
5034
5035#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005036#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005037 isAutoProxy = 1;
5038#endif
5039 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005040 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5041 int useProxy = 0;
5042
dan08da86a2009-08-21 17:18:03 +00005043 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5044 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005045 if( envforce!=NULL ){
5046 useProxy = atoi(envforce)>0;
5047 }else{
5048 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005049 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005050 /* In theory, the close(fd) call is sub-optimal. If the file opened
5051 ** with fd is a database file, and there are other connections open
5052 ** on that file that are currently holding advisory locks on it,
5053 ** then the call to close() will cancel those locks. In practice,
5054 ** we're assuming that statfs() doesn't fail very often. At least
5055 ** not while other file descriptors opened by the same process on
5056 ** the same file are working. */
5057 p->lastErrno = errno;
5058 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005059 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005060 }
drh0e9365c2011-03-02 02:08:13 +00005061 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005062 rc = SQLITE_IOERR_ACCESS;
5063 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005064 }
5065 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5066 }
5067 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005068 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5069 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005070 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005071 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005072 if( rc!=SQLITE_OK ){
5073 /* Use unixClose to clean up the resources added in fillInUnixFile
5074 ** and clear all the structure's references. Specifically,
5075 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5076 */
5077 unixClose(pFile);
5078 return rc;
5079 }
aswiftaebf4132008-11-21 00:10:35 +00005080 }
dane946c392009-08-22 11:39:46 +00005081 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005082 }
5083 }
5084#endif
5085
drh77197112011-03-15 19:08:48 +00005086 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5087 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005088open_finished:
5089 if( rc!=SQLITE_OK ){
5090 sqlite3_free(p->pUnused);
5091 }
5092 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005093}
5094
dane946c392009-08-22 11:39:46 +00005095
danielk1977b4b47412007-08-17 15:53:36 +00005096/*
danielk1977fee2d252007-08-18 10:59:19 +00005097** Delete the file at zPath. If the dirSync argument is true, fsync()
5098** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005099*/
drh6b9d6dd2008-12-03 19:34:47 +00005100static int unixDelete(
5101 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5102 const char *zPath, /* Name of file to be deleted */
5103 int dirSync /* If true, fsync() directory after deleting file */
5104){
danielk1977fee2d252007-08-18 10:59:19 +00005105 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005106 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005107 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005108 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005109 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005110 }
danielk1977d39fa702008-10-16 13:27:40 +00005111#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005112 if( dirSync ){
5113 int fd;
5114 rc = openDirectory(zPath, &fd);
5115 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005116#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005117 if( fsync(fd)==-1 )
5118#else
5119 if( fsync(fd) )
5120#endif
5121 {
dane18d4952011-02-21 11:46:24 +00005122 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005123 }
drh0e9365c2011-03-02 02:08:13 +00005124 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005125 }
5126 }
danielk1977d138dd82008-10-15 16:02:48 +00005127#endif
danielk1977fee2d252007-08-18 10:59:19 +00005128 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005129}
5130
danielk197790949c22007-08-17 16:50:38 +00005131/*
5132** Test the existance of or access permissions of file zPath. The
5133** test performed depends on the value of flags:
5134**
5135** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5136** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5137** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5138**
5139** Otherwise return 0.
5140*/
danielk1977861f7452008-06-05 11:39:11 +00005141static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005142 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5143 const char *zPath, /* Path of the file to examine */
5144 int flags, /* What do we want to learn about the zPath file? */
5145 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005146){
rse25c0d1a2007-09-20 08:38:14 +00005147 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005148 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005149 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005150 switch( flags ){
5151 case SQLITE_ACCESS_EXISTS:
5152 amode = F_OK;
5153 break;
5154 case SQLITE_ACCESS_READWRITE:
5155 amode = W_OK|R_OK;
5156 break;
drh50d3f902007-08-27 21:10:36 +00005157 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005158 amode = R_OK;
5159 break;
5160
5161 default:
5162 assert(!"Invalid flags argument");
5163 }
drh99ab3b12011-03-02 15:09:07 +00005164 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005165 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5166 struct stat buf;
5167 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5168 *pResOut = 0;
5169 }
5170 }
danielk1977861f7452008-06-05 11:39:11 +00005171 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005172}
5173
danielk1977b4b47412007-08-17 15:53:36 +00005174
5175/*
5176** Turn a relative pathname into a full pathname. The relative path
5177** is stored as a nul-terminated string in the buffer pointed to by
5178** zPath.
5179**
5180** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5181** (in this case, MAX_PATHNAME bytes). The full-path is written to
5182** this buffer before returning.
5183*/
danielk1977adfb9b02007-09-17 07:02:56 +00005184static int unixFullPathname(
5185 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5186 const char *zPath, /* Possibly relative input path */
5187 int nOut, /* Size of output buffer in bytes */
5188 char *zOut /* Output buffer */
5189){
danielk1977843e65f2007-09-01 16:16:15 +00005190
5191 /* It's odd to simulate an io-error here, but really this is just
5192 ** using the io-error infrastructure to test that SQLite handles this
5193 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005194 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005195 */
5196 SimulateIOError( return SQLITE_ERROR );
5197
drh153c62c2007-08-24 03:51:33 +00005198 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005199 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005200
drh3c7f2dc2007-12-06 13:26:20 +00005201 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005202 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005203 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005204 }else{
5205 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005206 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005207 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005208 }
drhea678832008-12-10 19:26:22 +00005209 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005210 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005211 }
5212 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005213}
5214
drh0ccebe72005-06-07 22:22:50 +00005215
drh761df872006-12-21 01:29:22 +00005216#ifndef SQLITE_OMIT_LOAD_EXTENSION
5217/*
5218** Interfaces for opening a shared library, finding entry points
5219** within the shared library, and closing the shared library.
5220*/
5221#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005222static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5223 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005224 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5225}
danielk197795c8a542007-09-01 06:51:27 +00005226
5227/*
5228** SQLite calls this function immediately after a call to unixDlSym() or
5229** unixDlOpen() fails (returns a null pointer). If a more detailed error
5230** message is available, it is written to zBufOut. If no error message
5231** is available, zBufOut is left unmodified and SQLite uses a default
5232** error message.
5233*/
danielk1977397d65f2008-11-19 11:35:39 +00005234static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005235 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005236 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005237 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005238 zErr = dlerror();
5239 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005240 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005241 }
drh6c7d5c52008-11-21 20:32:33 +00005242 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005243}
drh1875f7a2008-12-08 18:19:17 +00005244static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5245 /*
5246 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5247 ** cast into a pointer to a function. And yet the library dlsym() routine
5248 ** returns a void* which is really a pointer to a function. So how do we
5249 ** use dlsym() with -pedantic-errors?
5250 **
5251 ** Variable x below is defined to be a pointer to a function taking
5252 ** parameters void* and const char* and returning a pointer to a function.
5253 ** We initialize x by assigning it a pointer to the dlsym() function.
5254 ** (That assignment requires a cast.) Then we call the function that
5255 ** x points to.
5256 **
5257 ** This work-around is unlikely to work correctly on any system where
5258 ** you really cannot cast a function pointer into void*. But then, on the
5259 ** other hand, dlsym() will not work on such a system either, so we have
5260 ** not really lost anything.
5261 */
5262 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005263 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005264 x = (void(*(*)(void*,const char*))(void))dlsym;
5265 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005266}
danielk1977397d65f2008-11-19 11:35:39 +00005267static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5268 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005269 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005270}
danielk1977b4b47412007-08-17 15:53:36 +00005271#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5272 #define unixDlOpen 0
5273 #define unixDlError 0
5274 #define unixDlSym 0
5275 #define unixDlClose 0
5276#endif
5277
5278/*
danielk197790949c22007-08-17 16:50:38 +00005279** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005280*/
danielk1977397d65f2008-11-19 11:35:39 +00005281static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5282 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005283 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005284
drhbbd42a62004-05-22 17:41:58 +00005285 /* We have to initialize zBuf to prevent valgrind from reporting
5286 ** errors. The reports issued by valgrind are incorrect - we would
5287 ** prefer that the randomness be increased by making use of the
5288 ** uninitialized space in zBuf - but valgrind errors tend to worry
5289 ** some users. Rather than argue, it seems easier just to initialize
5290 ** the whole array and silence valgrind, even if that means less randomness
5291 ** in the random seed.
5292 **
5293 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005294 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005295 ** tests repeatable.
5296 */
danielk1977b4b47412007-08-17 15:53:36 +00005297 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005298#if !defined(SQLITE_TEST)
5299 {
drh842b8642005-01-21 17:53:17 +00005300 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005301 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005302 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005303 time_t t;
5304 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005305 memcpy(zBuf, &t, sizeof(t));
5306 pid = getpid();
5307 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005308 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005309 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005310 }else{
drhe562be52011-03-02 18:01:10 +00005311 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005312 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005313 }
drhbbd42a62004-05-22 17:41:58 +00005314 }
5315#endif
drh72cbd072008-10-14 17:58:38 +00005316 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005317}
5318
danielk1977b4b47412007-08-17 15:53:36 +00005319
drhbbd42a62004-05-22 17:41:58 +00005320/*
5321** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005322** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005323** The return value is the number of microseconds of sleep actually
5324** requested from the underlying operating system, a number which
5325** might be greater than or equal to the argument, but not less
5326** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005327*/
danielk1977397d65f2008-11-19 11:35:39 +00005328static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005329#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005330 struct timespec sp;
5331
5332 sp.tv_sec = microseconds / 1000000;
5333 sp.tv_nsec = (microseconds % 1000000) * 1000;
5334 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005335 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005336 return microseconds;
5337#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005338 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005339 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005340 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005341#else
danielk1977b4b47412007-08-17 15:53:36 +00005342 int seconds = (microseconds+999999)/1000000;
5343 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005344 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005345 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005346#endif
drh88f474a2006-01-02 20:00:12 +00005347}
5348
5349/*
drh6b9d6dd2008-12-03 19:34:47 +00005350** The following variable, if set to a non-zero value, is interpreted as
5351** the number of seconds since 1970 and is used to set the result of
5352** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005353*/
5354#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005355int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005356#endif
5357
5358/*
drhb7e8ea22010-05-03 14:32:30 +00005359** Find the current time (in Universal Coordinated Time). Write into *piNow
5360** the current time and date as a Julian Day number times 86_400_000. In
5361** other words, write into *piNow the number of milliseconds since the Julian
5362** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5363** proleptic Gregorian calendar.
5364**
5365** On success, return 0. Return 1 if the time and date cannot be found.
5366*/
5367static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5368 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5369#if defined(NO_GETTOD)
5370 time_t t;
5371 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005372 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005373#elif OS_VXWORKS
5374 struct timespec sNow;
5375 clock_gettime(CLOCK_REALTIME, &sNow);
5376 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5377#else
5378 struct timeval sNow;
5379 gettimeofday(&sNow, 0);
5380 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5381#endif
5382
5383#ifdef SQLITE_TEST
5384 if( sqlite3_current_time ){
5385 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5386 }
5387#endif
5388 UNUSED_PARAMETER(NotUsed);
5389 return 0;
5390}
5391
5392/*
drhbbd42a62004-05-22 17:41:58 +00005393** Find the current time (in Universal Coordinated Time). Write the
5394** current time and date as a Julian Day number into *prNow and
5395** return 0. Return 1 if the time and date cannot be found.
5396*/
danielk1977397d65f2008-11-19 11:35:39 +00005397static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005398 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005399 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005400 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005401 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005402 return 0;
5403}
danielk1977b4b47412007-08-17 15:53:36 +00005404
drh6b9d6dd2008-12-03 19:34:47 +00005405/*
5406** We added the xGetLastError() method with the intention of providing
5407** better low-level error messages when operating-system problems come up
5408** during SQLite operation. But so far, none of that has been implemented
5409** in the core. So this routine is never called. For now, it is merely
5410** a place-holder.
5411*/
danielk1977397d65f2008-11-19 11:35:39 +00005412static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5413 UNUSED_PARAMETER(NotUsed);
5414 UNUSED_PARAMETER(NotUsed2);
5415 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005416 return 0;
5417}
5418
drhf2424c52010-04-26 00:04:55 +00005419
5420/*
drh734c9862008-11-28 15:37:20 +00005421************************ End of sqlite3_vfs methods ***************************
5422******************************************************************************/
5423
drh715ff302008-12-03 22:32:44 +00005424/******************************************************************************
5425************************** Begin Proxy Locking ********************************
5426**
5427** Proxy locking is a "uber-locking-method" in this sense: It uses the
5428** other locking methods on secondary lock files. Proxy locking is a
5429** meta-layer over top of the primitive locking implemented above. For
5430** this reason, the division that implements of proxy locking is deferred
5431** until late in the file (here) after all of the other I/O methods have
5432** been defined - so that the primitive locking methods are available
5433** as services to help with the implementation of proxy locking.
5434**
5435****
5436**
5437** The default locking schemes in SQLite use byte-range locks on the
5438** database file to coordinate safe, concurrent access by multiple readers
5439** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5440** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5441** as POSIX read & write locks over fixed set of locations (via fsctl),
5442** on AFP and SMB only exclusive byte-range locks are available via fsctl
5443** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5444** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5445** address in the shared range is taken for a SHARED lock, the entire
5446** shared range is taken for an EXCLUSIVE lock):
5447**
5448** PENDING_BYTE 0x40000000
5449** RESERVED_BYTE 0x40000001
5450** SHARED_RANGE 0x40000002 -> 0x40000200
5451**
5452** This works well on the local file system, but shows a nearly 100x
5453** slowdown in read performance on AFP because the AFP client disables
5454** the read cache when byte-range locks are present. Enabling the read
5455** cache exposes a cache coherency problem that is present on all OS X
5456** supported network file systems. NFS and AFP both observe the
5457** close-to-open semantics for ensuring cache coherency
5458** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5459** address the requirements for concurrent database access by multiple
5460** readers and writers
5461** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5462**
5463** To address the performance and cache coherency issues, proxy file locking
5464** changes the way database access is controlled by limiting access to a
5465** single host at a time and moving file locks off of the database file
5466** and onto a proxy file on the local file system.
5467**
5468**
5469** Using proxy locks
5470** -----------------
5471**
5472** C APIs
5473**
5474** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5475** <proxy_path> | ":auto:");
5476** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5477**
5478**
5479** SQL pragmas
5480**
5481** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5482** PRAGMA [database.]lock_proxy_file
5483**
5484** Specifying ":auto:" means that if there is a conch file with a matching
5485** host ID in it, the proxy path in the conch file will be used, otherwise
5486** a proxy path based on the user's temp dir
5487** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5488** actual proxy file name is generated from the name and path of the
5489** database file. For example:
5490**
5491** For database path "/Users/me/foo.db"
5492** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5493**
5494** Once a lock proxy is configured for a database connection, it can not
5495** be removed, however it may be switched to a different proxy path via
5496** the above APIs (assuming the conch file is not being held by another
5497** connection or process).
5498**
5499**
5500** How proxy locking works
5501** -----------------------
5502**
5503** Proxy file locking relies primarily on two new supporting files:
5504**
5505** * conch file to limit access to the database file to a single host
5506** at a time
5507**
5508** * proxy file to act as a proxy for the advisory locks normally
5509** taken on the database
5510**
5511** The conch file - to use a proxy file, sqlite must first "hold the conch"
5512** by taking an sqlite-style shared lock on the conch file, reading the
5513** contents and comparing the host's unique host ID (see below) and lock
5514** proxy path against the values stored in the conch. The conch file is
5515** stored in the same directory as the database file and the file name
5516** is patterned after the database file name as ".<databasename>-conch".
5517** If the conch file does not exist, or it's contents do not match the
5518** host ID and/or proxy path, then the lock is escalated to an exclusive
5519** lock and the conch file contents is updated with the host ID and proxy
5520** path and the lock is downgraded to a shared lock again. If the conch
5521** is held by another process (with a shared lock), the exclusive lock
5522** will fail and SQLITE_BUSY is returned.
5523**
5524** The proxy file - a single-byte file used for all advisory file locks
5525** normally taken on the database file. This allows for safe sharing
5526** of the database file for multiple readers and writers on the same
5527** host (the conch ensures that they all use the same local lock file).
5528**
drh715ff302008-12-03 22:32:44 +00005529** Requesting the lock proxy does not immediately take the conch, it is
5530** only taken when the first request to lock database file is made.
5531** This matches the semantics of the traditional locking behavior, where
5532** opening a connection to a database file does not take a lock on it.
5533** The shared lock and an open file descriptor are maintained until
5534** the connection to the database is closed.
5535**
5536** The proxy file and the lock file are never deleted so they only need
5537** to be created the first time they are used.
5538**
5539** Configuration options
5540** ---------------------
5541**
5542** SQLITE_PREFER_PROXY_LOCKING
5543**
5544** Database files accessed on non-local file systems are
5545** automatically configured for proxy locking, lock files are
5546** named automatically using the same logic as
5547** PRAGMA lock_proxy_file=":auto:"
5548**
5549** SQLITE_PROXY_DEBUG
5550**
5551** Enables the logging of error messages during host id file
5552** retrieval and creation
5553**
drh715ff302008-12-03 22:32:44 +00005554** LOCKPROXYDIR
5555**
5556** Overrides the default directory used for lock proxy files that
5557** are named automatically via the ":auto:" setting
5558**
5559** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5560**
5561** Permissions to use when creating a directory for storing the
5562** lock proxy files, only used when LOCKPROXYDIR is not set.
5563**
5564**
5565** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5566** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5567** force proxy locking to be used for every database file opened, and 0
5568** will force automatic proxy locking to be disabled for all database
5569** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5570** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5571*/
5572
5573/*
5574** Proxy locking is only available on MacOSX
5575*/
drhd2cb50b2009-01-09 21:41:17 +00005576#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005577
drh715ff302008-12-03 22:32:44 +00005578/*
5579** The proxyLockingContext has the path and file structures for the remote
5580** and local proxy files in it
5581*/
5582typedef struct proxyLockingContext proxyLockingContext;
5583struct proxyLockingContext {
5584 unixFile *conchFile; /* Open conch file */
5585 char *conchFilePath; /* Name of the conch file */
5586 unixFile *lockProxy; /* Open proxy lock file */
5587 char *lockProxyPath; /* Name of the proxy lock file */
5588 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005589 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005590 void *oldLockingContext; /* Original lockingcontext to restore on close */
5591 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5592};
5593
drh7ed97b92010-01-20 13:07:21 +00005594/*
5595** The proxy lock file path for the database at dbPath is written into lPath,
5596** which must point to valid, writable memory large enough for a maxLen length
5597** file path.
drh715ff302008-12-03 22:32:44 +00005598*/
drh715ff302008-12-03 22:32:44 +00005599static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5600 int len;
5601 int dbLen;
5602 int i;
5603
5604#ifdef LOCKPROXYDIR
5605 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5606#else
5607# ifdef _CS_DARWIN_USER_TEMP_DIR
5608 {
drh7ed97b92010-01-20 13:07:21 +00005609 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005610 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5611 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005612 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005613 }
drh7ed97b92010-01-20 13:07:21 +00005614 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005615 }
5616# else
5617 len = strlcpy(lPath, "/tmp/", maxLen);
5618# endif
5619#endif
5620
5621 if( lPath[len-1]!='/' ){
5622 len = strlcat(lPath, "/", maxLen);
5623 }
5624
5625 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005626 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005627 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005628 char c = dbPath[i];
5629 lPath[i+len] = (c=='/')?'_':c;
5630 }
5631 lPath[i+len]='\0';
5632 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005633 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005634 return SQLITE_OK;
5635}
5636
drh7ed97b92010-01-20 13:07:21 +00005637/*
5638 ** Creates the lock file and any missing directories in lockPath
5639 */
5640static int proxyCreateLockPath(const char *lockPath){
5641 int i, len;
5642 char buf[MAXPATHLEN];
5643 int start = 0;
5644
5645 assert(lockPath!=NULL);
5646 /* try to create all the intermediate directories */
5647 len = (int)strlen(lockPath);
5648 buf[0] = lockPath[0];
5649 for( i=1; i<len; i++ ){
5650 if( lockPath[i] == '/' && (i - start > 0) ){
5651 /* only mkdir if leaf dir != "." or "/" or ".." */
5652 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5653 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5654 buf[i]='\0';
5655 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5656 int err=errno;
5657 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005658 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005659 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005660 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005661 return err;
5662 }
5663 }
5664 }
5665 start=i+1;
5666 }
5667 buf[i] = lockPath[i];
5668 }
drh308c2a52010-05-14 11:30:18 +00005669 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005670 return 0;
5671}
5672
drh715ff302008-12-03 22:32:44 +00005673/*
5674** Create a new VFS file descriptor (stored in memory obtained from
5675** sqlite3_malloc) and open the file named "path" in the file descriptor.
5676**
5677** The caller is responsible not only for closing the file descriptor
5678** but also for freeing the memory associated with the file descriptor.
5679*/
drh7ed97b92010-01-20 13:07:21 +00005680static int proxyCreateUnixFile(
5681 const char *path, /* path for the new unixFile */
5682 unixFile **ppFile, /* unixFile created and returned by ref */
5683 int islockfile /* if non zero missing dirs will be created */
5684) {
5685 int fd = -1;
5686 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005687 unixFile *pNew;
5688 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005689 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005690 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005691 int terrno = 0;
5692 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005693
drh7ed97b92010-01-20 13:07:21 +00005694 /* 1. first try to open/create the file
5695 ** 2. if that fails, and this is a lock file (not-conch), try creating
5696 ** the parent directories and then try again.
5697 ** 3. if that fails, try to open the file read-only
5698 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5699 */
5700 pUnused = findReusableFd(path, openFlags);
5701 if( pUnused ){
5702 fd = pUnused->fd;
5703 }else{
5704 pUnused = sqlite3_malloc(sizeof(*pUnused));
5705 if( !pUnused ){
5706 return SQLITE_NOMEM;
5707 }
5708 }
5709 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005710 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005711 terrno = errno;
5712 if( fd<0 && errno==ENOENT && islockfile ){
5713 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005714 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005715 }
5716 }
5717 }
5718 if( fd<0 ){
5719 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005720 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005721 terrno = errno;
5722 }
5723 if( fd<0 ){
5724 if( islockfile ){
5725 return SQLITE_BUSY;
5726 }
5727 switch (terrno) {
5728 case EACCES:
5729 return SQLITE_PERM;
5730 case EIO:
5731 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5732 default:
drh9978c972010-02-23 17:36:32 +00005733 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005734 }
5735 }
5736
5737 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5738 if( pNew==NULL ){
5739 rc = SQLITE_NOMEM;
5740 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005741 }
5742 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005743 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005744 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005745 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005746 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005747 pUnused->fd = fd;
5748 pUnused->flags = openFlags;
5749 pNew->pUnused = pUnused;
5750
drh77197112011-03-15 19:08:48 +00005751 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005752 if( rc==SQLITE_OK ){
5753 *ppFile = pNew;
5754 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005755 }
drh7ed97b92010-01-20 13:07:21 +00005756end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005757 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005758 sqlite3_free(pNew);
5759 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005760 return rc;
5761}
5762
drh7ed97b92010-01-20 13:07:21 +00005763#ifdef SQLITE_TEST
5764/* simulate multiple hosts by creating unique hostid file paths */
5765int sqlite3_hostid_num = 0;
5766#endif
5767
5768#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5769
drh0ab216a2010-07-02 17:10:40 +00005770/* Not always defined in the headers as it ought to be */
5771extern int gethostuuid(uuid_t id, const struct timespec *wait);
5772
drh7ed97b92010-01-20 13:07:21 +00005773/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5774** bytes of writable memory.
5775*/
5776static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005777 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5778 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005779#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5780 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005781 {
5782 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5783 if( gethostuuid(pHostID, &timeout) ){
5784 int err = errno;
5785 if( pError ){
5786 *pError = err;
5787 }
5788 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005789 }
drh7ed97b92010-01-20 13:07:21 +00005790 }
drhe8b0c9b2010-09-25 14:13:17 +00005791#endif
drh7ed97b92010-01-20 13:07:21 +00005792#ifdef SQLITE_TEST
5793 /* simulate multiple hosts by creating unique hostid file paths */
5794 if( sqlite3_hostid_num != 0){
5795 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5796 }
5797#endif
5798
5799 return SQLITE_OK;
5800}
5801
5802/* The conch file contains the header, host id and lock file path
5803 */
5804#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5805#define PROXY_HEADERLEN 1 /* conch file header length */
5806#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5807#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5808
5809/*
5810** Takes an open conch file, copies the contents to a new path and then moves
5811** it back. The newly created file's file descriptor is assigned to the
5812** conch file structure and finally the original conch file descriptor is
5813** closed. Returns zero if successful.
5814*/
5815static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5816 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5817 unixFile *conchFile = pCtx->conchFile;
5818 char tPath[MAXPATHLEN];
5819 char buf[PROXY_MAXCONCHLEN];
5820 char *cPath = pCtx->conchFilePath;
5821 size_t readLen = 0;
5822 size_t pathLen = 0;
5823 char errmsg[64] = "";
5824 int fd = -1;
5825 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005826 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005827
5828 /* create a new path by replace the trailing '-conch' with '-break' */
5829 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5830 if( pathLen>MAXPATHLEN || pathLen<6 ||
5831 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005832 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005833 goto end_breaklock;
5834 }
5835 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005836 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005837 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005838 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005839 goto end_breaklock;
5840 }
5841 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005842 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5843 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005844 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005845 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005846 goto end_breaklock;
5847 }
drhe562be52011-03-02 18:01:10 +00005848 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005849 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005850 goto end_breaklock;
5851 }
5852 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005853 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005854 goto end_breaklock;
5855 }
5856 rc = 0;
5857 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005858 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005859 conchFile->h = fd;
5860 conchFile->openFlags = O_RDWR | O_CREAT;
5861
5862end_breaklock:
5863 if( rc ){
5864 if( fd>=0 ){
5865 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005866 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005867 }
5868 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5869 }
5870 return rc;
5871}
5872
5873/* Take the requested lock on the conch file and break a stale lock if the
5874** host id matches.
5875*/
5876static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5877 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5878 unixFile *conchFile = pCtx->conchFile;
5879 int rc = SQLITE_OK;
5880 int nTries = 0;
5881 struct timespec conchModTime;
5882
5883 do {
5884 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5885 nTries ++;
5886 if( rc==SQLITE_BUSY ){
5887 /* If the lock failed (busy):
5888 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5889 * 2nd try: fail if the mod time changed or host id is different, wait
5890 * 10 sec and try again
5891 * 3rd try: break the lock unless the mod time has changed.
5892 */
5893 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005894 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005895 pFile->lastErrno = errno;
5896 return SQLITE_IOERR_LOCK;
5897 }
5898
5899 if( nTries==1 ){
5900 conchModTime = buf.st_mtimespec;
5901 usleep(500000); /* wait 0.5 sec and try the lock again*/
5902 continue;
5903 }
5904
5905 assert( nTries>1 );
5906 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5907 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5908 return SQLITE_BUSY;
5909 }
5910
5911 if( nTries==2 ){
5912 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005913 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005914 if( len<0 ){
5915 pFile->lastErrno = errno;
5916 return SQLITE_IOERR_LOCK;
5917 }
5918 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5919 /* don't break the lock if the host id doesn't match */
5920 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5921 return SQLITE_BUSY;
5922 }
5923 }else{
5924 /* don't break the lock on short read or a version mismatch */
5925 return SQLITE_BUSY;
5926 }
5927 usleep(10000000); /* wait 10 sec and try the lock again */
5928 continue;
5929 }
5930
5931 assert( nTries==3 );
5932 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5933 rc = SQLITE_OK;
5934 if( lockType==EXCLUSIVE_LOCK ){
5935 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5936 }
5937 if( !rc ){
5938 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5939 }
5940 }
5941 }
5942 } while( rc==SQLITE_BUSY && nTries<3 );
5943
5944 return rc;
5945}
5946
5947/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005948** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5949** lockPath means that the lockPath in the conch file will be used if the
5950** host IDs match, or a new lock path will be generated automatically
5951** and written to the conch file.
5952*/
5953static int proxyTakeConch(unixFile *pFile){
5954 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5955
drh7ed97b92010-01-20 13:07:21 +00005956 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005957 return SQLITE_OK;
5958 }else{
5959 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005960 uuid_t myHostID;
5961 int pError = 0;
5962 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005963 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005964 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005965 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005966 int createConch = 0;
5967 int hostIdMatch = 0;
5968 int readLen = 0;
5969 int tryOldLockPath = 0;
5970 int forceNewLockPath = 0;
5971
drh308c2a52010-05-14 11:30:18 +00005972 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5973 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005974
drh7ed97b92010-01-20 13:07:21 +00005975 rc = proxyGetHostID(myHostID, &pError);
5976 if( (rc&0xff)==SQLITE_IOERR ){
5977 pFile->lastErrno = pError;
5978 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005979 }
drh7ed97b92010-01-20 13:07:21 +00005980 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005981 if( rc!=SQLITE_OK ){
5982 goto end_takeconch;
5983 }
drh7ed97b92010-01-20 13:07:21 +00005984 /* read the existing conch file */
5985 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5986 if( readLen<0 ){
5987 /* I/O error: lastErrno set by seekAndRead */
5988 pFile->lastErrno = conchFile->lastErrno;
5989 rc = SQLITE_IOERR_READ;
5990 goto end_takeconch;
5991 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5992 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5993 /* a short read or version format mismatch means we need to create a new
5994 ** conch file.
5995 */
5996 createConch = 1;
5997 }
5998 /* if the host id matches and the lock path already exists in the conch
5999 ** we'll try to use the path there, if we can't open that path, we'll
6000 ** retry with a new auto-generated path
6001 */
6002 do { /* in case we need to try again for an :auto: named lock file */
6003
6004 if( !createConch && !forceNewLockPath ){
6005 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6006 PROXY_HOSTIDLEN);
6007 /* if the conch has data compare the contents */
6008 if( !pCtx->lockProxyPath ){
6009 /* for auto-named local lock file, just check the host ID and we'll
6010 ** use the local lock file path that's already in there
6011 */
6012 if( hostIdMatch ){
6013 size_t pathLen = (readLen - PROXY_PATHINDEX);
6014
6015 if( pathLen>=MAXPATHLEN ){
6016 pathLen=MAXPATHLEN-1;
6017 }
6018 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6019 lockPath[pathLen] = 0;
6020 tempLockPath = lockPath;
6021 tryOldLockPath = 1;
6022 /* create a copy of the lock path if the conch is taken */
6023 goto end_takeconch;
6024 }
6025 }else if( hostIdMatch
6026 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6027 readLen-PROXY_PATHINDEX)
6028 ){
6029 /* conch host and lock path match */
6030 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006031 }
drh7ed97b92010-01-20 13:07:21 +00006032 }
6033
6034 /* if the conch isn't writable and doesn't match, we can't take it */
6035 if( (conchFile->openFlags&O_RDWR) == 0 ){
6036 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006037 goto end_takeconch;
6038 }
drh7ed97b92010-01-20 13:07:21 +00006039
6040 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006041 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006042 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6043 tempLockPath = lockPath;
6044 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006045 }
drh7ed97b92010-01-20 13:07:21 +00006046
6047 /* update conch with host and path (this will fail if other process
6048 ** has a shared lock already), if the host id matches, use the big
6049 ** stick.
drh715ff302008-12-03 22:32:44 +00006050 */
drh7ed97b92010-01-20 13:07:21 +00006051 futimes(conchFile->h, NULL);
6052 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006053 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006054 /* We are trying for an exclusive lock but another thread in this
6055 ** same process is still holding a shared lock. */
6056 rc = SQLITE_BUSY;
6057 } else {
6058 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006059 }
drh715ff302008-12-03 22:32:44 +00006060 }else{
drh7ed97b92010-01-20 13:07:21 +00006061 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006062 }
drh7ed97b92010-01-20 13:07:21 +00006063 if( rc==SQLITE_OK ){
6064 char writeBuffer[PROXY_MAXCONCHLEN];
6065 int writeSize = 0;
6066
6067 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6068 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6069 if( pCtx->lockProxyPath!=NULL ){
6070 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6071 }else{
6072 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6073 }
6074 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006075 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006076 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6077 fsync(conchFile->h);
6078 /* If we created a new conch file (not just updated the contents of a
6079 ** valid conch file), try to match the permissions of the database
6080 */
6081 if( rc==SQLITE_OK && createConch ){
6082 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006083 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006084 if( err==0 ){
6085 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6086 S_IROTH|S_IWOTH);
6087 /* try to match the database file R/W permissions, ignore failure */
6088#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006089 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006090#else
drhff812312011-02-23 13:33:46 +00006091 do{
drhe562be52011-03-02 18:01:10 +00006092 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006093 }while( rc==(-1) && errno==EINTR );
6094 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006095 int code = errno;
6096 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6097 cmode, code, strerror(code));
6098 } else {
6099 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6100 }
6101 }else{
6102 int code = errno;
6103 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6104 err, code, strerror(code));
6105#endif
6106 }
drh715ff302008-12-03 22:32:44 +00006107 }
6108 }
drh7ed97b92010-01-20 13:07:21 +00006109 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6110
6111 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006112 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006113 if( rc==SQLITE_OK && pFile->openFlags ){
6114 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006115 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006116 }
6117 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006118 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006119 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006120 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006121 if( fd>=0 ){
6122 pFile->h = fd;
6123 }else{
drh9978c972010-02-23 17:36:32 +00006124 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006125 during locking */
6126 }
6127 }
6128 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6129 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6130 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6131 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6132 /* we couldn't create the proxy lock file with the old lock file path
6133 ** so try again via auto-naming
6134 */
6135 forceNewLockPath = 1;
6136 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006137 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006138 }
6139 }
6140 if( rc==SQLITE_OK ){
6141 /* Need to make a copy of path if we extracted the value
6142 ** from the conch file or the path was allocated on the stack
6143 */
6144 if( tempLockPath ){
6145 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6146 if( !pCtx->lockProxyPath ){
6147 rc = SQLITE_NOMEM;
6148 }
6149 }
6150 }
6151 if( rc==SQLITE_OK ){
6152 pCtx->conchHeld = 1;
6153
6154 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6155 afpLockingContext *afpCtx;
6156 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6157 afpCtx->dbPath = pCtx->lockProxyPath;
6158 }
6159 } else {
6160 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6161 }
drh308c2a52010-05-14 11:30:18 +00006162 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6163 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006164 return rc;
drh308c2a52010-05-14 11:30:18 +00006165 } while (1); /* in case we need to retry the :auto: lock file -
6166 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006167 }
6168}
6169
6170/*
6171** If pFile holds a lock on a conch file, then release that lock.
6172*/
6173static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006174 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006175 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6176 unixFile *conchFile; /* Name of the conch file */
6177
6178 pCtx = (proxyLockingContext *)pFile->lockingContext;
6179 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006180 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006181 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006182 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006183 if( pCtx->conchHeld>0 ){
6184 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6185 }
drh715ff302008-12-03 22:32:44 +00006186 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006187 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6188 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006189 return rc;
6190}
6191
6192/*
6193** Given the name of a database file, compute the name of its conch file.
6194** Store the conch filename in memory obtained from sqlite3_malloc().
6195** Make *pConchPath point to the new name. Return SQLITE_OK on success
6196** or SQLITE_NOMEM if unable to obtain memory.
6197**
6198** The caller is responsible for ensuring that the allocated memory
6199** space is eventually freed.
6200**
6201** *pConchPath is set to NULL if a memory allocation error occurs.
6202*/
6203static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6204 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006205 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006206 char *conchPath; /* buffer in which to construct conch name */
6207
6208 /* Allocate space for the conch filename and initialize the name to
6209 ** the name of the original database file. */
6210 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6211 if( conchPath==0 ){
6212 return SQLITE_NOMEM;
6213 }
6214 memcpy(conchPath, dbPath, len+1);
6215
6216 /* now insert a "." before the last / character */
6217 for( i=(len-1); i>=0; i-- ){
6218 if( conchPath[i]=='/' ){
6219 i++;
6220 break;
6221 }
6222 }
6223 conchPath[i]='.';
6224 while ( i<len ){
6225 conchPath[i+1]=dbPath[i];
6226 i++;
6227 }
6228
6229 /* append the "-conch" suffix to the file */
6230 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006231 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006232
6233 return SQLITE_OK;
6234}
6235
6236
6237/* Takes a fully configured proxy locking-style unix file and switches
6238** the local lock file path
6239*/
6240static int switchLockProxyPath(unixFile *pFile, const char *path) {
6241 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6242 char *oldPath = pCtx->lockProxyPath;
6243 int rc = SQLITE_OK;
6244
drh308c2a52010-05-14 11:30:18 +00006245 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006246 return SQLITE_BUSY;
6247 }
6248
6249 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6250 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6251 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6252 return SQLITE_OK;
6253 }else{
6254 unixFile *lockProxy = pCtx->lockProxy;
6255 pCtx->lockProxy=NULL;
6256 pCtx->conchHeld = 0;
6257 if( lockProxy!=NULL ){
6258 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6259 if( rc ) return rc;
6260 sqlite3_free(lockProxy);
6261 }
6262 sqlite3_free(oldPath);
6263 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6264 }
6265
6266 return rc;
6267}
6268
6269/*
6270** pFile is a file that has been opened by a prior xOpen call. dbPath
6271** is a string buffer at least MAXPATHLEN+1 characters in size.
6272**
6273** This routine find the filename associated with pFile and writes it
6274** int dbPath.
6275*/
6276static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006277#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006278 if( pFile->pMethod == &afpIoMethods ){
6279 /* afp style keeps a reference to the db path in the filePath field
6280 ** of the struct */
drhea678832008-12-10 19:26:22 +00006281 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006282 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6283 } else
drh715ff302008-12-03 22:32:44 +00006284#endif
6285 if( pFile->pMethod == &dotlockIoMethods ){
6286 /* dot lock style uses the locking context to store the dot lock
6287 ** file path */
6288 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6289 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6290 }else{
6291 /* all other styles use the locking context to store the db file path */
6292 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006293 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006294 }
6295 return SQLITE_OK;
6296}
6297
6298/*
6299** Takes an already filled in unix file and alters it so all file locking
6300** will be performed on the local proxy lock file. The following fields
6301** are preserved in the locking context so that they can be restored and
6302** the unix structure properly cleaned up at close time:
6303** ->lockingContext
6304** ->pMethod
6305*/
6306static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6307 proxyLockingContext *pCtx;
6308 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6309 char *lockPath=NULL;
6310 int rc = SQLITE_OK;
6311
drh308c2a52010-05-14 11:30:18 +00006312 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006313 return SQLITE_BUSY;
6314 }
6315 proxyGetDbPathForUnixFile(pFile, dbPath);
6316 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6317 lockPath=NULL;
6318 }else{
6319 lockPath=(char *)path;
6320 }
6321
drh308c2a52010-05-14 11:30:18 +00006322 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6323 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006324
6325 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6326 if( pCtx==0 ){
6327 return SQLITE_NOMEM;
6328 }
6329 memset(pCtx, 0, sizeof(*pCtx));
6330
6331 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6332 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006333 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6334 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6335 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6336 ** (c) the file system is read-only, then enable no-locking access.
6337 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6338 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6339 */
6340 struct statfs fsInfo;
6341 struct stat conchInfo;
6342 int goLockless = 0;
6343
drh99ab3b12011-03-02 15:09:07 +00006344 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006345 int err = errno;
6346 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6347 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6348 }
6349 }
6350 if( goLockless ){
6351 pCtx->conchHeld = -1; /* read only FS/ lockless */
6352 rc = SQLITE_OK;
6353 }
6354 }
drh715ff302008-12-03 22:32:44 +00006355 }
6356 if( rc==SQLITE_OK && lockPath ){
6357 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6358 }
6359
6360 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006361 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6362 if( pCtx->dbPath==NULL ){
6363 rc = SQLITE_NOMEM;
6364 }
6365 }
6366 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006367 /* all memory is allocated, proxys are created and assigned,
6368 ** switch the locking context and pMethod then return.
6369 */
drh715ff302008-12-03 22:32:44 +00006370 pCtx->oldLockingContext = pFile->lockingContext;
6371 pFile->lockingContext = pCtx;
6372 pCtx->pOldMethod = pFile->pMethod;
6373 pFile->pMethod = &proxyIoMethods;
6374 }else{
6375 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006376 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006377 sqlite3_free(pCtx->conchFile);
6378 }
drhd56b1212010-08-11 06:14:15 +00006379 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006380 sqlite3_free(pCtx->conchFilePath);
6381 sqlite3_free(pCtx);
6382 }
drh308c2a52010-05-14 11:30:18 +00006383 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6384 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006385 return rc;
6386}
6387
6388
6389/*
6390** This routine handles sqlite3_file_control() calls that are specific
6391** to proxy locking.
6392*/
6393static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6394 switch( op ){
6395 case SQLITE_GET_LOCKPROXYFILE: {
6396 unixFile *pFile = (unixFile*)id;
6397 if( pFile->pMethod == &proxyIoMethods ){
6398 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6399 proxyTakeConch(pFile);
6400 if( pCtx->lockProxyPath ){
6401 *(const char **)pArg = pCtx->lockProxyPath;
6402 }else{
6403 *(const char **)pArg = ":auto: (not held)";
6404 }
6405 } else {
6406 *(const char **)pArg = NULL;
6407 }
6408 return SQLITE_OK;
6409 }
6410 case SQLITE_SET_LOCKPROXYFILE: {
6411 unixFile *pFile = (unixFile*)id;
6412 int rc = SQLITE_OK;
6413 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6414 if( pArg==NULL || (const char *)pArg==0 ){
6415 if( isProxyStyle ){
6416 /* turn off proxy locking - not supported */
6417 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6418 }else{
6419 /* turn off proxy locking - already off - NOOP */
6420 rc = SQLITE_OK;
6421 }
6422 }else{
6423 const char *proxyPath = (const char *)pArg;
6424 if( isProxyStyle ){
6425 proxyLockingContext *pCtx =
6426 (proxyLockingContext*)pFile->lockingContext;
6427 if( !strcmp(pArg, ":auto:")
6428 || (pCtx->lockProxyPath &&
6429 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6430 ){
6431 rc = SQLITE_OK;
6432 }else{
6433 rc = switchLockProxyPath(pFile, proxyPath);
6434 }
6435 }else{
6436 /* turn on proxy file locking */
6437 rc = proxyTransformUnixFile(pFile, proxyPath);
6438 }
6439 }
6440 return rc;
6441 }
6442 default: {
6443 assert( 0 ); /* The call assures that only valid opcodes are sent */
6444 }
6445 }
6446 /*NOTREACHED*/
6447 return SQLITE_ERROR;
6448}
6449
6450/*
6451** Within this division (the proxying locking implementation) the procedures
6452** above this point are all utilities. The lock-related methods of the
6453** proxy-locking sqlite3_io_method object follow.
6454*/
6455
6456
6457/*
6458** This routine checks if there is a RESERVED lock held on the specified
6459** file by this or any other process. If such a lock is held, set *pResOut
6460** to a non-zero value otherwise *pResOut is set to zero. The return value
6461** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6462*/
6463static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6464 unixFile *pFile = (unixFile*)id;
6465 int rc = proxyTakeConch(pFile);
6466 if( rc==SQLITE_OK ){
6467 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006468 if( pCtx->conchHeld>0 ){
6469 unixFile *proxy = pCtx->lockProxy;
6470 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6471 }else{ /* conchHeld < 0 is lockless */
6472 pResOut=0;
6473 }
drh715ff302008-12-03 22:32:44 +00006474 }
6475 return rc;
6476}
6477
6478/*
drh308c2a52010-05-14 11:30:18 +00006479** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006480** of the following:
6481**
6482** (1) SHARED_LOCK
6483** (2) RESERVED_LOCK
6484** (3) PENDING_LOCK
6485** (4) EXCLUSIVE_LOCK
6486**
6487** Sometimes when requesting one lock state, additional lock states
6488** are inserted in between. The locking might fail on one of the later
6489** transitions leaving the lock state different from what it started but
6490** still short of its goal. The following chart shows the allowed
6491** transitions and the inserted intermediate states:
6492**
6493** UNLOCKED -> SHARED
6494** SHARED -> RESERVED
6495** SHARED -> (PENDING) -> EXCLUSIVE
6496** RESERVED -> (PENDING) -> EXCLUSIVE
6497** PENDING -> EXCLUSIVE
6498**
6499** This routine will only increase a lock. Use the sqlite3OsUnlock()
6500** routine to lower a locking level.
6501*/
drh308c2a52010-05-14 11:30:18 +00006502static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006503 unixFile *pFile = (unixFile*)id;
6504 int rc = proxyTakeConch(pFile);
6505 if( rc==SQLITE_OK ){
6506 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006507 if( pCtx->conchHeld>0 ){
6508 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006509 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6510 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006511 }else{
6512 /* conchHeld < 0 is lockless */
6513 }
drh715ff302008-12-03 22:32:44 +00006514 }
6515 return rc;
6516}
6517
6518
6519/*
drh308c2a52010-05-14 11:30:18 +00006520** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006521** must be either NO_LOCK or SHARED_LOCK.
6522**
6523** If the locking level of the file descriptor is already at or below
6524** the requested locking level, this routine is a no-op.
6525*/
drh308c2a52010-05-14 11:30:18 +00006526static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006527 unixFile *pFile = (unixFile*)id;
6528 int rc = proxyTakeConch(pFile);
6529 if( rc==SQLITE_OK ){
6530 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006531 if( pCtx->conchHeld>0 ){
6532 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006533 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6534 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006535 }else{
6536 /* conchHeld < 0 is lockless */
6537 }
drh715ff302008-12-03 22:32:44 +00006538 }
6539 return rc;
6540}
6541
6542/*
6543** Close a file that uses proxy locks.
6544*/
6545static int proxyClose(sqlite3_file *id) {
6546 if( id ){
6547 unixFile *pFile = (unixFile*)id;
6548 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6549 unixFile *lockProxy = pCtx->lockProxy;
6550 unixFile *conchFile = pCtx->conchFile;
6551 int rc = SQLITE_OK;
6552
6553 if( lockProxy ){
6554 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6555 if( rc ) return rc;
6556 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6557 if( rc ) return rc;
6558 sqlite3_free(lockProxy);
6559 pCtx->lockProxy = 0;
6560 }
6561 if( conchFile ){
6562 if( pCtx->conchHeld ){
6563 rc = proxyReleaseConch(pFile);
6564 if( rc ) return rc;
6565 }
6566 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6567 if( rc ) return rc;
6568 sqlite3_free(conchFile);
6569 }
drhd56b1212010-08-11 06:14:15 +00006570 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006571 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006572 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006573 /* restore the original locking context and pMethod then close it */
6574 pFile->lockingContext = pCtx->oldLockingContext;
6575 pFile->pMethod = pCtx->pOldMethod;
6576 sqlite3_free(pCtx);
6577 return pFile->pMethod->xClose(id);
6578 }
6579 return SQLITE_OK;
6580}
6581
6582
6583
drhd2cb50b2009-01-09 21:41:17 +00006584#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006585/*
6586** The proxy locking style is intended for use with AFP filesystems.
6587** And since AFP is only supported on MacOSX, the proxy locking is also
6588** restricted to MacOSX.
6589**
6590**
6591******************* End of the proxy lock implementation **********************
6592******************************************************************************/
6593
drh734c9862008-11-28 15:37:20 +00006594/*
danielk1977e339d652008-06-28 11:23:00 +00006595** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006596**
6597** This routine registers all VFS implementations for unix-like operating
6598** systems. This routine, and the sqlite3_os_end() routine that follows,
6599** should be the only routines in this file that are visible from other
6600** files.
drh6b9d6dd2008-12-03 19:34:47 +00006601**
6602** This routine is called once during SQLite initialization and by a
6603** single thread. The memory allocation and mutex subsystems have not
6604** necessarily been initialized when this routine is called, and so they
6605** should not be used.
drh153c62c2007-08-24 03:51:33 +00006606*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006607int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006608 /*
6609 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006610 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6611 ** to the "finder" function. (pAppData is a pointer to a pointer because
6612 ** silly C90 rules prohibit a void* from being cast to a function pointer
6613 ** and so we have to go through the intermediate pointer to avoid problems
6614 ** when compiling with -pedantic-errors on GCC.)
6615 **
6616 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006617 ** finder-function. The finder-function returns a pointer to the
6618 ** sqlite_io_methods object that implements the desired locking
6619 ** behaviors. See the division above that contains the IOMETHODS
6620 ** macro for addition information on finder-functions.
6621 **
6622 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6623 ** object. But the "autolockIoFinder" available on MacOSX does a little
6624 ** more than that; it looks at the filesystem type that hosts the
6625 ** database file and tries to choose an locking method appropriate for
6626 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006627 */
drh7708e972008-11-29 00:56:52 +00006628 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006629 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006630 sizeof(unixFile), /* szOsFile */ \
6631 MAX_PATHNAME, /* mxPathname */ \
6632 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006633 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006634 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006635 unixOpen, /* xOpen */ \
6636 unixDelete, /* xDelete */ \
6637 unixAccess, /* xAccess */ \
6638 unixFullPathname, /* xFullPathname */ \
6639 unixDlOpen, /* xDlOpen */ \
6640 unixDlError, /* xDlError */ \
6641 unixDlSym, /* xDlSym */ \
6642 unixDlClose, /* xDlClose */ \
6643 unixRandomness, /* xRandomness */ \
6644 unixSleep, /* xSleep */ \
6645 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006646 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006647 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006648 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006649 unixGetSystemCall, /* xGetSystemCall */ \
6650 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006651 }
6652
drh6b9d6dd2008-12-03 19:34:47 +00006653 /*
6654 ** All default VFSes for unix are contained in the following array.
6655 **
6656 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6657 ** by the SQLite core when the VFS is registered. So the following
6658 ** array cannot be const.
6659 */
danielk1977e339d652008-06-28 11:23:00 +00006660 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006661#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006662 UNIXVFS("unix", autolockIoFinder ),
6663#else
6664 UNIXVFS("unix", posixIoFinder ),
6665#endif
6666 UNIXVFS("unix-none", nolockIoFinder ),
6667 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006668 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006669#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006670 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006671#endif
6672#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006673 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006674#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006675 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006676#endif
chw78a13182009-04-07 05:35:03 +00006677#endif
drhd2cb50b2009-01-09 21:41:17 +00006678#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006679 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006680 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006681 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006682#endif
drh153c62c2007-08-24 03:51:33 +00006683 };
drh6b9d6dd2008-12-03 19:34:47 +00006684 unsigned int i; /* Loop counter */
6685
6686 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006687 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006688 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006689 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006690 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006691}
danielk1977e339d652008-06-28 11:23:00 +00006692
6693/*
drh6b9d6dd2008-12-03 19:34:47 +00006694** Shutdown the operating system interface.
6695**
6696** Some operating systems might need to do some cleanup in this routine,
6697** to release dynamically allocated objects. But not on unix.
6698** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006699*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006700int sqlite3_os_end(void){
6701 return SQLITE_OK;
6702}
drhdce8bdb2007-08-16 13:01:44 +00006703
danielk197729bafea2008-06-26 10:41:19 +00006704#endif /* SQLITE_OS_UNIX */