blob: e3fa9ea46541a1418ff5b1c69fc13cfdb6aaaa39 [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 */
dan51438a72011-04-02 17:00:47 +0000397 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000398 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
399 if( aSyscall[i].pDefault ){
400 aSyscall[i].pCurrent = aSyscall[i].pDefault;
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 */
dan502019c2010-07-28 14:26:17 +00003401
drhff812312011-02-23 13:33:46 +00003402 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003403 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003404 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003405 }
3406 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003407 while( iWrite<nSize ){
3408 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3409 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003410 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003411 }
dan502019c2010-07-28 14:26:17 +00003412#endif
3413 }
3414 }
3415
3416 return SQLITE_OK;
3417}
danielk1977ad94b582007-08-20 06:44:22 +00003418
danielk1977e3026632004-06-22 11:29:02 +00003419/*
drh9e33c2c2007-08-31 18:34:59 +00003420** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003421*/
drhcc6bb3e2007-08-31 16:11:35 +00003422static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003423 switch( op ){
3424 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003425 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003426 return SQLITE_OK;
3427 }
drh7708e972008-11-29 00:56:52 +00003428 case SQLITE_LAST_ERRNO: {
3429 *(int*)pArg = ((unixFile*)id)->lastErrno;
3430 return SQLITE_OK;
3431 }
dan6e09d692010-07-27 18:34:15 +00003432 case SQLITE_FCNTL_CHUNK_SIZE: {
3433 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003434 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003435 }
drh9ff27ec2010-05-19 19:26:05 +00003436 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003437 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003438 }
drh8f941bc2009-01-14 23:03:40 +00003439#ifndef NDEBUG
3440 /* The pager calls this method to signal that it has done
3441 ** a rollback and that the database is therefore unchanged and
3442 ** it hence it is OK for the transaction change counter to be
3443 ** unchanged.
3444 */
3445 case SQLITE_FCNTL_DB_UNCHANGED: {
3446 ((unixFile*)id)->dbUpdate = 0;
3447 return SQLITE_OK;
3448 }
3449#endif
drhd2cb50b2009-01-09 21:41:17 +00003450#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003451 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003452 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003453 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003454 }
drhd2cb50b2009-01-09 21:41:17 +00003455#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003456 case SQLITE_FCNTL_SYNC_OMITTED: {
3457 return SQLITE_OK; /* A no-op */
3458 }
drh9e33c2c2007-08-31 18:34:59 +00003459 }
drh0b52b7d2011-01-26 19:46:22 +00003460 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003461}
3462
3463/*
danielk1977a3d4c882007-03-23 10:08:38 +00003464** Return the sector size in bytes of the underlying block device for
3465** the specified file. This is almost always 512 bytes, but may be
3466** larger for some devices.
3467**
3468** SQLite code assumes this function cannot fail. It also assumes that
3469** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003470** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003471** same for both.
3472*/
danielk1977397d65f2008-11-19 11:35:39 +00003473static int unixSectorSize(sqlite3_file *NotUsed){
3474 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003475 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003476}
3477
danielk197790949c22007-08-17 16:50:38 +00003478/*
danielk1977397d65f2008-11-19 11:35:39 +00003479** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003480*/
danielk1977397d65f2008-11-19 11:35:39 +00003481static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3482 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003483 return 0;
3484}
3485
drhd9e5c4f2010-05-12 18:01:39 +00003486#ifndef SQLITE_OMIT_WAL
3487
3488
3489/*
drhd91c68f2010-05-14 14:52:25 +00003490** Object used to represent an shared memory buffer.
3491**
3492** When multiple threads all reference the same wal-index, each thread
3493** has its own unixShm object, but they all point to a single instance
3494** of this unixShmNode object. In other words, each wal-index is opened
3495** only once per process.
3496**
3497** Each unixShmNode object is connected to a single unixInodeInfo object.
3498** We could coalesce this object into unixInodeInfo, but that would mean
3499** every open file that does not use shared memory (in other words, most
3500** open files) would have to carry around this extra information. So
3501** the unixInodeInfo object contains a pointer to this unixShmNode object
3502** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003503**
3504** unixMutexHeld() must be true when creating or destroying
3505** this object or while reading or writing the following fields:
3506**
3507** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003508**
3509** The following fields are read-only after the object is created:
3510**
3511** fid
3512** zFilename
3513**
drhd91c68f2010-05-14 14:52:25 +00003514** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003515** unixMutexHeld() is true when reading or writing any other field
3516** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003517*/
drhd91c68f2010-05-14 14:52:25 +00003518struct unixShmNode {
3519 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003520 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003521 char *zFilename; /* Name of the mmapped file */
3522 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003523 int szRegion; /* Size of shared-memory regions */
3524 int nRegion; /* Size of array apRegion */
3525 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003526 int nRef; /* Number of unixShm objects pointing to this */
3527 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003528#ifdef SQLITE_DEBUG
3529 u8 exclMask; /* Mask of exclusive locks held */
3530 u8 sharedMask; /* Mask of shared locks held */
3531 u8 nextShmId; /* Next available unixShm.id value */
3532#endif
3533};
3534
3535/*
drhd9e5c4f2010-05-12 18:01:39 +00003536** Structure used internally by this VFS to record the state of an
3537** open shared memory connection.
3538**
drhd91c68f2010-05-14 14:52:25 +00003539** The following fields are initialized when this object is created and
3540** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003541**
drhd91c68f2010-05-14 14:52:25 +00003542** unixShm.pFile
3543** unixShm.id
3544**
3545** All other fields are read/write. The unixShm.pFile->mutex must be held
3546** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003547*/
3548struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003549 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3550 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003551 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003552 u16 sharedMask; /* Mask of shared locks held */
3553 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003554#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003555 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003556#endif
3557};
3558
3559/*
drhd9e5c4f2010-05-12 18:01:39 +00003560** Constants used for locking
3561*/
drhbd9676c2010-06-23 17:58:38 +00003562#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003563#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003564
drhd9e5c4f2010-05-12 18:01:39 +00003565/*
drh73b64e42010-05-30 19:55:15 +00003566** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003567**
3568** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3569** otherwise.
3570*/
3571static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003572 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3573 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003574 int ofst, /* First byte of the locking range */
3575 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003576){
3577 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003578 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003579
drhd91c68f2010-05-14 14:52:25 +00003580 /* Access to the unixShmNode object is serialized by the caller */
3581 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003582
drh73b64e42010-05-30 19:55:15 +00003583 /* Shared locks never span more than one byte */
3584 assert( n==1 || lockType!=F_RDLCK );
3585
3586 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003587 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003588
drh3cb93392011-03-12 18:10:44 +00003589 if( pShmNode->h>=0 ){
3590 /* Initialize the locking parameters */
3591 memset(&f, 0, sizeof(f));
3592 f.l_type = lockType;
3593 f.l_whence = SEEK_SET;
3594 f.l_start = ofst;
3595 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003596
drh3cb93392011-03-12 18:10:44 +00003597 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3598 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3599 }
drhd9e5c4f2010-05-12 18:01:39 +00003600
3601 /* Update the global lock state and do debug tracing */
3602#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003603 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003604 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003605 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003606 if( rc==SQLITE_OK ){
3607 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003608 OSTRACE(("unlock %d ok", ofst));
3609 pShmNode->exclMask &= ~mask;
3610 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003611 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003612 OSTRACE(("read-lock %d ok", ofst));
3613 pShmNode->exclMask &= ~mask;
3614 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003615 }else{
3616 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003617 OSTRACE(("write-lock %d ok", ofst));
3618 pShmNode->exclMask |= mask;
3619 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003620 }
3621 }else{
3622 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003623 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003624 }else if( lockType==F_RDLCK ){
3625 OSTRACE(("read-lock failed"));
3626 }else{
3627 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003628 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003629 }
3630 }
drh20e1f082010-05-31 16:10:12 +00003631 OSTRACE((" - afterwards %03x,%03x\n",
3632 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003633 }
drhd9e5c4f2010-05-12 18:01:39 +00003634#endif
3635
3636 return rc;
3637}
3638
drhd9e5c4f2010-05-12 18:01:39 +00003639
3640/*
drhd91c68f2010-05-14 14:52:25 +00003641** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003642**
3643** This is not a VFS shared-memory method; it is a utility function called
3644** by VFS shared-memory methods.
3645*/
drhd91c68f2010-05-14 14:52:25 +00003646static void unixShmPurge(unixFile *pFd){
3647 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003648 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003649 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003650 int i;
drhd91c68f2010-05-14 14:52:25 +00003651 assert( p->pInode==pFd->pInode );
3652 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003653 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003654 if( p->h>=0 ){
3655 munmap(p->apRegion[i], p->szRegion);
3656 }else{
3657 sqlite3_free(p->apRegion[i]);
3658 }
dan13a3cb82010-06-11 19:04:21 +00003659 }
dan18801912010-06-14 14:07:50 +00003660 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003661 if( p->h>=0 ){
3662 robust_close(pFd, p->h, __LINE__);
3663 p->h = -1;
3664 }
drhd91c68f2010-05-14 14:52:25 +00003665 p->pInode->pShmNode = 0;
3666 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003667 }
3668}
3669
3670/*
danda9fe0c2010-07-13 18:44:03 +00003671** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003672** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003673**
drh7234c6d2010-06-19 15:10:09 +00003674** The file used to implement shared-memory is in the same directory
3675** as the open database file and has the same name as the open database
3676** file with the "-shm" suffix added. For example, if the database file
3677** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003678** for shared memory will be called "/home/user1/config.db-shm".
3679**
3680** Another approach to is to use files in /dev/shm or /dev/tmp or an
3681** some other tmpfs mount. But if a file in a different directory
3682** from the database file is used, then differing access permissions
3683** or a chroot() might cause two different processes on the same
3684** database to end up using different files for shared memory -
3685** meaning that their memory would not really be shared - resulting
3686** in database corruption. Nevertheless, this tmpfs file usage
3687** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3688** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3689** option results in an incompatible build of SQLite; builds of SQLite
3690** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3691** same database file at the same time, database corruption will likely
3692** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3693** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003694**
3695** When opening a new shared-memory file, if no other instances of that
3696** file are currently open, in this process or in other processes, then
3697** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003698**
3699** If the original database file (pDbFd) is using the "unix-excl" VFS
3700** that means that an exclusive lock is held on the database file and
3701** that no other processes are able to read or write the database. In
3702** that case, we do not really need shared memory. No shared memory
3703** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003704*/
danda9fe0c2010-07-13 18:44:03 +00003705static int unixOpenSharedMemory(unixFile *pDbFd){
3706 struct unixShm *p = 0; /* The connection to be opened */
3707 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3708 int rc; /* Result code */
3709 unixInodeInfo *pInode; /* The inode of fd */
3710 char *zShmFilename; /* Name of the file used for SHM */
3711 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003712
danda9fe0c2010-07-13 18:44:03 +00003713 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003714 p = sqlite3_malloc( sizeof(*p) );
3715 if( p==0 ) return SQLITE_NOMEM;
3716 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003717 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003718
danda9fe0c2010-07-13 18:44:03 +00003719 /* Check to see if a unixShmNode object already exists. Reuse an existing
3720 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003721 */
3722 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003723 pInode = pDbFd->pInode;
3724 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003725 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003726 struct stat sStat; /* fstat() info for database file */
3727
3728 /* Call fstat() to figure out the permissions on the database file. If
3729 ** a new *-shm file is created, an attempt will be made to create it
3730 ** with the same permissions. The actual permissions the file is created
3731 ** with are subject to the current umask setting.
3732 */
drh3cb93392011-03-12 18:10:44 +00003733 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003734 rc = SQLITE_IOERR_FSTAT;
3735 goto shm_open_err;
3736 }
3737
drha4ced192010-07-15 18:32:40 +00003738#ifdef SQLITE_SHM_DIRECTORY
3739 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3740#else
drh7234c6d2010-06-19 15:10:09 +00003741 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003742#endif
drh7234c6d2010-06-19 15:10:09 +00003743 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003744 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003745 rc = SQLITE_NOMEM;
3746 goto shm_open_err;
3747 }
drhd91c68f2010-05-14 14:52:25 +00003748 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003749 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003750#ifdef SQLITE_SHM_DIRECTORY
3751 sqlite3_snprintf(nShmFilename, zShmFilename,
3752 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3753 (u32)sStat.st_ino, (u32)sStat.st_dev);
3754#else
drh7234c6d2010-06-19 15:10:09 +00003755 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003756#endif
drhd91c68f2010-05-14 14:52:25 +00003757 pShmNode->h = -1;
3758 pDbFd->pInode->pShmNode = pShmNode;
3759 pShmNode->pInode = pDbFd->pInode;
3760 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3761 if( pShmNode->mutex==0 ){
3762 rc = SQLITE_NOMEM;
3763 goto shm_open_err;
3764 }
drhd9e5c4f2010-05-12 18:01:39 +00003765
drh3cb93392011-03-12 18:10:44 +00003766 if( pInode->bProcessLock==0 ){
3767 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3768 (sStat.st_mode & 0777));
3769 if( pShmNode->h<0 ){
3770 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3771 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003772 }
drh3cb93392011-03-12 18:10:44 +00003773
3774 /* Check to see if another process is holding the dead-man switch.
3775 ** If not, truncate the file to zero length.
3776 */
3777 rc = SQLITE_OK;
3778 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3779 if( robust_ftruncate(pShmNode->h, 0) ){
3780 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3781 }
3782 }
3783 if( rc==SQLITE_OK ){
3784 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3785 }
3786 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003787 }
drhd9e5c4f2010-05-12 18:01:39 +00003788 }
3789
drhd91c68f2010-05-14 14:52:25 +00003790 /* Make the new connection a child of the unixShmNode */
3791 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003792#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003793 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003794#endif
drhd91c68f2010-05-14 14:52:25 +00003795 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003796 pDbFd->pShm = p;
3797 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003798
3799 /* The reference count on pShmNode has already been incremented under
3800 ** the cover of the unixEnterMutex() mutex and the pointer from the
3801 ** new (struct unixShm) object to the pShmNode has been set. All that is
3802 ** left to do is to link the new object into the linked list starting
3803 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3804 ** mutex.
3805 */
3806 sqlite3_mutex_enter(pShmNode->mutex);
3807 p->pNext = pShmNode->pFirst;
3808 pShmNode->pFirst = p;
3809 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003810 return SQLITE_OK;
3811
3812 /* Jump here on any error */
3813shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003814 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003815 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003816 unixLeaveMutex();
3817 return rc;
3818}
3819
3820/*
danda9fe0c2010-07-13 18:44:03 +00003821** This function is called to obtain a pointer to region iRegion of the
3822** shared-memory associated with the database file fd. Shared-memory regions
3823** are numbered starting from zero. Each shared-memory region is szRegion
3824** bytes in size.
3825**
3826** If an error occurs, an error code is returned and *pp is set to NULL.
3827**
3828** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3829** region has not been allocated (by any client, including one running in a
3830** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3831** bExtend is non-zero and the requested shared-memory region has not yet
3832** been allocated, it is allocated by this function.
3833**
3834** If the shared-memory region has already been allocated or is allocated by
3835** this call as described above, then it is mapped into this processes
3836** address space (if it is not already), *pp is set to point to the mapped
3837** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003838*/
danda9fe0c2010-07-13 18:44:03 +00003839static int unixShmMap(
3840 sqlite3_file *fd, /* Handle open on database file */
3841 int iRegion, /* Region to retrieve */
3842 int szRegion, /* Size of regions */
3843 int bExtend, /* True to extend file if necessary */
3844 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003845){
danda9fe0c2010-07-13 18:44:03 +00003846 unixFile *pDbFd = (unixFile*)fd;
3847 unixShm *p;
3848 unixShmNode *pShmNode;
3849 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003850
danda9fe0c2010-07-13 18:44:03 +00003851 /* If the shared-memory file has not yet been opened, open it now. */
3852 if( pDbFd->pShm==0 ){
3853 rc = unixOpenSharedMemory(pDbFd);
3854 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003855 }
drhd9e5c4f2010-05-12 18:01:39 +00003856
danda9fe0c2010-07-13 18:44:03 +00003857 p = pDbFd->pShm;
3858 pShmNode = p->pShmNode;
3859 sqlite3_mutex_enter(pShmNode->mutex);
3860 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003861 assert( pShmNode->pInode==pDbFd->pInode );
3862 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3863 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003864
3865 if( pShmNode->nRegion<=iRegion ){
3866 char **apNew; /* New apRegion[] array */
3867 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3868 struct stat sStat; /* Used by fstat() */
3869
3870 pShmNode->szRegion = szRegion;
3871
drh3cb93392011-03-12 18:10:44 +00003872 if( pShmNode->h>=0 ){
3873 /* The requested region is not mapped into this processes address space.
3874 ** Check to see if it has been allocated (i.e. if the wal-index file is
3875 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003876 */
drh3cb93392011-03-12 18:10:44 +00003877 if( osFstat(pShmNode->h, &sStat) ){
3878 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003879 goto shmpage_out;
3880 }
drh3cb93392011-03-12 18:10:44 +00003881
3882 if( sStat.st_size<nByte ){
3883 /* The requested memory region does not exist. If bExtend is set to
3884 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3885 **
3886 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3887 ** the requested memory region.
3888 */
3889 if( !bExtend ) goto shmpage_out;
3890 if( robust_ftruncate(pShmNode->h, nByte) ){
3891 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3892 pShmNode->zFilename);
3893 goto shmpage_out;
3894 }
3895 }
danda9fe0c2010-07-13 18:44:03 +00003896 }
3897
3898 /* Map the requested memory region into this processes address space. */
3899 apNew = (char **)sqlite3_realloc(
3900 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3901 );
3902 if( !apNew ){
3903 rc = SQLITE_IOERR_NOMEM;
3904 goto shmpage_out;
3905 }
3906 pShmNode->apRegion = apNew;
3907 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003908 void *pMem;
3909 if( pShmNode->h>=0 ){
3910 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3911 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3912 );
3913 if( pMem==MAP_FAILED ){
3914 rc = SQLITE_IOERR;
3915 goto shmpage_out;
3916 }
3917 }else{
3918 pMem = sqlite3_malloc(szRegion);
3919 if( pMem==0 ){
3920 rc = SQLITE_NOMEM;
3921 goto shmpage_out;
3922 }
3923 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003924 }
3925 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3926 pShmNode->nRegion++;
3927 }
3928 }
3929
3930shmpage_out:
3931 if( pShmNode->nRegion>iRegion ){
3932 *pp = pShmNode->apRegion[iRegion];
3933 }else{
3934 *pp = 0;
3935 }
3936 sqlite3_mutex_leave(pShmNode->mutex);
3937 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003938}
3939
3940/*
drhd9e5c4f2010-05-12 18:01:39 +00003941** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003942**
3943** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3944** different here than in posix. In xShmLock(), one can go from unlocked
3945** to shared and back or from unlocked to exclusive and back. But one may
3946** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003947*/
3948static int unixShmLock(
3949 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003950 int ofst, /* First lock to acquire or release */
3951 int n, /* Number of locks to acquire or release */
3952 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003953){
drh73b64e42010-05-30 19:55:15 +00003954 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3955 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3956 unixShm *pX; /* For looping over all siblings */
3957 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3958 int rc = SQLITE_OK; /* Result code */
3959 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003960
drhd91c68f2010-05-14 14:52:25 +00003961 assert( pShmNode==pDbFd->pInode->pShmNode );
3962 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003963 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003964 assert( n>=1 );
3965 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3966 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3967 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3968 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3969 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003970 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3971 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003972
drhc99597c2010-05-31 01:41:15 +00003973 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003974 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003975 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003976 if( flags & SQLITE_SHM_UNLOCK ){
3977 u16 allMask = 0; /* Mask of locks held by siblings */
3978
3979 /* See if any siblings hold this same lock */
3980 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3981 if( pX==p ) continue;
3982 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3983 allMask |= pX->sharedMask;
3984 }
3985
3986 /* Unlock the system-level locks */
3987 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003988 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003989 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003990 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003991 }
drh73b64e42010-05-30 19:55:15 +00003992
3993 /* Undo the local locks */
3994 if( rc==SQLITE_OK ){
3995 p->exclMask &= ~mask;
3996 p->sharedMask &= ~mask;
3997 }
3998 }else if( flags & SQLITE_SHM_SHARED ){
3999 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4000
4001 /* Find out which shared locks are already held by sibling connections.
4002 ** If any sibling already holds an exclusive lock, go ahead and return
4003 ** SQLITE_BUSY.
4004 */
4005 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004006 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004007 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004008 break;
4009 }
4010 allShared |= pX->sharedMask;
4011 }
4012
4013 /* Get shared locks at the system level, if necessary */
4014 if( rc==SQLITE_OK ){
4015 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004016 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004017 }else{
drh73b64e42010-05-30 19:55:15 +00004018 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004019 }
drhd9e5c4f2010-05-12 18:01:39 +00004020 }
drh73b64e42010-05-30 19:55:15 +00004021
4022 /* Get the local shared locks */
4023 if( rc==SQLITE_OK ){
4024 p->sharedMask |= mask;
4025 }
4026 }else{
4027 /* Make sure no sibling connections hold locks that will block this
4028 ** lock. If any do, return SQLITE_BUSY right away.
4029 */
4030 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004031 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4032 rc = SQLITE_BUSY;
4033 break;
4034 }
4035 }
4036
4037 /* Get the exclusive locks at the system level. Then if successful
4038 ** also mark the local connection as being locked.
4039 */
4040 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004041 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004042 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004043 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004044 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004045 }
drhd9e5c4f2010-05-12 18:01:39 +00004046 }
4047 }
drhd91c68f2010-05-14 14:52:25 +00004048 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004049 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4050 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004051 return rc;
4052}
4053
drh286a2882010-05-20 23:51:06 +00004054/*
4055** Implement a memory barrier or memory fence on shared memory.
4056**
4057** All loads and stores begun before the barrier must complete before
4058** any load or store begun after the barrier.
4059*/
4060static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004061 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004062){
drhff828942010-06-26 21:34:06 +00004063 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004064 unixEnterMutex();
4065 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004066}
4067
dan18801912010-06-14 14:07:50 +00004068/*
danda9fe0c2010-07-13 18:44:03 +00004069** Close a connection to shared-memory. Delete the underlying
4070** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004071**
4072** If there is no shared memory associated with the connection then this
4073** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004074*/
danda9fe0c2010-07-13 18:44:03 +00004075static int unixShmUnmap(
4076 sqlite3_file *fd, /* The underlying database file */
4077 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004078){
danda9fe0c2010-07-13 18:44:03 +00004079 unixShm *p; /* The connection to be closed */
4080 unixShmNode *pShmNode; /* The underlying shared-memory file */
4081 unixShm **pp; /* For looping over sibling connections */
4082 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004083
danda9fe0c2010-07-13 18:44:03 +00004084 pDbFd = (unixFile*)fd;
4085 p = pDbFd->pShm;
4086 if( p==0 ) return SQLITE_OK;
4087 pShmNode = p->pShmNode;
4088
4089 assert( pShmNode==pDbFd->pInode->pShmNode );
4090 assert( pShmNode->pInode==pDbFd->pInode );
4091
4092 /* Remove connection p from the set of connections associated
4093 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004094 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004095 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4096 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004097
danda9fe0c2010-07-13 18:44:03 +00004098 /* Free the connection p */
4099 sqlite3_free(p);
4100 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004101 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004102
4103 /* If pShmNode->nRef has reached 0, then close the underlying
4104 ** shared-memory file, too */
4105 unixEnterMutex();
4106 assert( pShmNode->nRef>0 );
4107 pShmNode->nRef--;
4108 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004109 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004110 unixShmPurge(pDbFd);
4111 }
4112 unixLeaveMutex();
4113
4114 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004115}
drh286a2882010-05-20 23:51:06 +00004116
danda9fe0c2010-07-13 18:44:03 +00004117
drhd9e5c4f2010-05-12 18:01:39 +00004118#else
drh6b017cc2010-06-14 18:01:46 +00004119# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004120# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004121# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004122# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004123#endif /* #ifndef SQLITE_OMIT_WAL */
4124
drh734c9862008-11-28 15:37:20 +00004125/*
4126** Here ends the implementation of all sqlite3_file methods.
4127**
4128********************** End sqlite3_file Methods *******************************
4129******************************************************************************/
4130
4131/*
drh6b9d6dd2008-12-03 19:34:47 +00004132** This division contains definitions of sqlite3_io_methods objects that
4133** implement various file locking strategies. It also contains definitions
4134** of "finder" functions. A finder-function is used to locate the appropriate
4135** sqlite3_io_methods object for a particular database file. The pAppData
4136** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4137** the correct finder-function for that VFS.
4138**
4139** Most finder functions return a pointer to a fixed sqlite3_io_methods
4140** object. The only interesting finder-function is autolockIoFinder, which
4141** looks at the filesystem type and tries to guess the best locking
4142** strategy from that.
4143**
drh1875f7a2008-12-08 18:19:17 +00004144** For finder-funtion F, two objects are created:
4145**
4146** (1) The real finder-function named "FImpt()".
4147**
dane946c392009-08-22 11:39:46 +00004148** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004149**
4150**
4151** A pointer to the F pointer is used as the pAppData value for VFS
4152** objects. We have to do this instead of letting pAppData point
4153** directly at the finder-function since C90 rules prevent a void*
4154** from be cast into a function pointer.
4155**
drh6b9d6dd2008-12-03 19:34:47 +00004156**
drh7708e972008-11-29 00:56:52 +00004157** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004158**
drh7708e972008-11-29 00:56:52 +00004159** * A constant sqlite3_io_methods object call METHOD that has locking
4160** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4161**
4162** * An I/O method finder function called FINDER that returns a pointer
4163** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004164*/
drhd9e5c4f2010-05-12 18:01:39 +00004165#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004166static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004167 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004168 CLOSE, /* xClose */ \
4169 unixRead, /* xRead */ \
4170 unixWrite, /* xWrite */ \
4171 unixTruncate, /* xTruncate */ \
4172 unixSync, /* xSync */ \
4173 unixFileSize, /* xFileSize */ \
4174 LOCK, /* xLock */ \
4175 UNLOCK, /* xUnlock */ \
4176 CKLOCK, /* xCheckReservedLock */ \
4177 unixFileControl, /* xFileControl */ \
4178 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004179 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004180 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004181 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004182 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004183 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004184}; \
drh0c2694b2009-09-03 16:23:44 +00004185static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4186 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004187 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004188} \
drh0c2694b2009-09-03 16:23:44 +00004189static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004190 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004191
4192/*
4193** Here are all of the sqlite3_io_methods objects for each of the
4194** locking strategies. Functions that return pointers to these methods
4195** are also created.
4196*/
4197IOMETHODS(
4198 posixIoFinder, /* Finder function name */
4199 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004200 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004201 unixClose, /* xClose method */
4202 unixLock, /* xLock method */
4203 unixUnlock, /* xUnlock method */
4204 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004205)
drh7708e972008-11-29 00:56:52 +00004206IOMETHODS(
4207 nolockIoFinder, /* Finder function name */
4208 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004209 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004210 nolockClose, /* xClose method */
4211 nolockLock, /* xLock method */
4212 nolockUnlock, /* xUnlock method */
4213 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004214)
drh7708e972008-11-29 00:56:52 +00004215IOMETHODS(
4216 dotlockIoFinder, /* Finder function name */
4217 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004218 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004219 dotlockClose, /* xClose method */
4220 dotlockLock, /* xLock method */
4221 dotlockUnlock, /* xUnlock method */
4222 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004223)
drh7708e972008-11-29 00:56:52 +00004224
chw78a13182009-04-07 05:35:03 +00004225#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004226IOMETHODS(
4227 flockIoFinder, /* Finder function name */
4228 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004229 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004230 flockClose, /* xClose method */
4231 flockLock, /* xLock method */
4232 flockUnlock, /* xUnlock method */
4233 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004234)
drh7708e972008-11-29 00:56:52 +00004235#endif
4236
drh6c7d5c52008-11-21 20:32:33 +00004237#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004238IOMETHODS(
4239 semIoFinder, /* Finder function name */
4240 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004241 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004242 semClose, /* xClose method */
4243 semLock, /* xLock method */
4244 semUnlock, /* xUnlock method */
4245 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004246)
aswiftaebf4132008-11-21 00:10:35 +00004247#endif
drh7708e972008-11-29 00:56:52 +00004248
drhd2cb50b2009-01-09 21:41:17 +00004249#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004250IOMETHODS(
4251 afpIoFinder, /* Finder function name */
4252 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004253 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004254 afpClose, /* xClose method */
4255 afpLock, /* xLock method */
4256 afpUnlock, /* xUnlock method */
4257 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004258)
drh715ff302008-12-03 22:32:44 +00004259#endif
4260
4261/*
4262** The proxy locking method is a "super-method" in the sense that it
4263** opens secondary file descriptors for the conch and lock files and
4264** it uses proxy, dot-file, AFP, and flock() locking methods on those
4265** secondary files. For this reason, the division that implements
4266** proxy locking is located much further down in the file. But we need
4267** to go ahead and define the sqlite3_io_methods and finder function
4268** for proxy locking here. So we forward declare the I/O methods.
4269*/
drhd2cb50b2009-01-09 21:41:17 +00004270#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004271static int proxyClose(sqlite3_file*);
4272static int proxyLock(sqlite3_file*, int);
4273static int proxyUnlock(sqlite3_file*, int);
4274static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004275IOMETHODS(
4276 proxyIoFinder, /* Finder function name */
4277 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004278 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004279 proxyClose, /* xClose method */
4280 proxyLock, /* xLock method */
4281 proxyUnlock, /* xUnlock method */
4282 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004283)
aswiftaebf4132008-11-21 00:10:35 +00004284#endif
drh7708e972008-11-29 00:56:52 +00004285
drh7ed97b92010-01-20 13:07:21 +00004286/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4287#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4288IOMETHODS(
4289 nfsIoFinder, /* Finder function name */
4290 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004291 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004292 unixClose, /* xClose method */
4293 unixLock, /* xLock method */
4294 nfsUnlock, /* xUnlock method */
4295 unixCheckReservedLock /* xCheckReservedLock method */
4296)
4297#endif
drh7708e972008-11-29 00:56:52 +00004298
drhd2cb50b2009-01-09 21:41:17 +00004299#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004300/*
drh6b9d6dd2008-12-03 19:34:47 +00004301** This "finder" function attempts to determine the best locking strategy
4302** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004303** object that implements that strategy.
4304**
4305** This is for MacOSX only.
4306*/
drh1875f7a2008-12-08 18:19:17 +00004307static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004308 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004309 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004310){
4311 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004312 const char *zFilesystem; /* Filesystem type name */
4313 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004314 } aMap[] = {
4315 { "hfs", &posixIoMethods },
4316 { "ufs", &posixIoMethods },
4317 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004318 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004319 { "webdav", &nolockIoMethods },
4320 { 0, 0 }
4321 };
4322 int i;
4323 struct statfs fsInfo;
4324 struct flock lockInfo;
4325
4326 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004327 /* If filePath==NULL that means we are dealing with a transient file
4328 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004329 return &nolockIoMethods;
4330 }
4331 if( statfs(filePath, &fsInfo) != -1 ){
4332 if( fsInfo.f_flags & MNT_RDONLY ){
4333 return &nolockIoMethods;
4334 }
4335 for(i=0; aMap[i].zFilesystem; i++){
4336 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4337 return aMap[i].pMethods;
4338 }
4339 }
4340 }
4341
4342 /* Default case. Handles, amongst others, "nfs".
4343 ** Test byte-range lock using fcntl(). If the call succeeds,
4344 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004345 */
drh7708e972008-11-29 00:56:52 +00004346 lockInfo.l_len = 1;
4347 lockInfo.l_start = 0;
4348 lockInfo.l_whence = SEEK_SET;
4349 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004350 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004351 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4352 return &nfsIoMethods;
4353 } else {
4354 return &posixIoMethods;
4355 }
drh7708e972008-11-29 00:56:52 +00004356 }else{
4357 return &dotlockIoMethods;
4358 }
4359}
drh0c2694b2009-09-03 16:23:44 +00004360static const sqlite3_io_methods
4361 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004362
drhd2cb50b2009-01-09 21:41:17 +00004363#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004364
chw78a13182009-04-07 05:35:03 +00004365#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4366/*
4367** This "finder" function attempts to determine the best locking strategy
4368** for the database file "filePath". It then returns the sqlite3_io_methods
4369** object that implements that strategy.
4370**
4371** This is for VXWorks only.
4372*/
4373static const sqlite3_io_methods *autolockIoFinderImpl(
4374 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004375 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004376){
4377 struct flock lockInfo;
4378
4379 if( !filePath ){
4380 /* If filePath==NULL that means we are dealing with a transient file
4381 ** that does not need to be locked. */
4382 return &nolockIoMethods;
4383 }
4384
4385 /* Test if fcntl() is supported and use POSIX style locks.
4386 ** Otherwise fall back to the named semaphore method.
4387 */
4388 lockInfo.l_len = 1;
4389 lockInfo.l_start = 0;
4390 lockInfo.l_whence = SEEK_SET;
4391 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004392 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004393 return &posixIoMethods;
4394 }else{
4395 return &semIoMethods;
4396 }
4397}
drh0c2694b2009-09-03 16:23:44 +00004398static const sqlite3_io_methods
4399 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004400
4401#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4402
drh7708e972008-11-29 00:56:52 +00004403/*
4404** An abstract type for a pointer to a IO method finder function:
4405*/
drh0c2694b2009-09-03 16:23:44 +00004406typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004407
aswiftaebf4132008-11-21 00:10:35 +00004408
drh734c9862008-11-28 15:37:20 +00004409/****************************************************************************
4410**************************** sqlite3_vfs methods ****************************
4411**
4412** This division contains the implementation of methods on the
4413** sqlite3_vfs object.
4414*/
4415
danielk1977a3d4c882007-03-23 10:08:38 +00004416/*
danielk1977e339d652008-06-28 11:23:00 +00004417** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004418*/
4419static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004420 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004421 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004422 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004423 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004424 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004425 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004426 int isDelete, /* Delete on close if true */
4427 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004428){
drh7708e972008-11-29 00:56:52 +00004429 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004430 unixFile *pNew = (unixFile *)pId;
4431 int rc = SQLITE_OK;
4432
drh8af6c222010-05-14 12:43:01 +00004433 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004434
dane946c392009-08-22 11:39:46 +00004435 /* Parameter isDelete is only used on vxworks. Express this explicitly
4436 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004437 */
drh7708e972008-11-29 00:56:52 +00004438 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004439
dan00157392010-10-05 11:33:15 +00004440 /* Usually the path zFilename should not be a relative pathname. The
4441 ** exception is when opening the proxy "conch" file in builds that
4442 ** include the special Apple locking styles.
4443 */
dan00157392010-10-05 11:33:15 +00004444#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004445 assert( zFilename==0 || zFilename[0]=='/'
4446 || pVfs->pAppData==(void*)&autolockIoFinder );
4447#else
4448 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004449#endif
dan00157392010-10-05 11:33:15 +00004450
drh308c2a52010-05-14 11:30:18 +00004451 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004452 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004453 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004454 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004455 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4456 pNew->ctrlFlags = UNIXFILE_EXCL;
4457 }else{
4458 pNew->ctrlFlags = 0;
4459 }
drh77197112011-03-15 19:08:48 +00004460 if( isReadOnly ){
4461 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4462 }
drh339eb0b2008-03-07 15:34:11 +00004463
drh6c7d5c52008-11-21 20:32:33 +00004464#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004465 pNew->pId = vxworksFindFileId(zFilename);
4466 if( pNew->pId==0 ){
4467 noLock = 1;
4468 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004469 }
4470#endif
4471
drhda0e7682008-07-30 15:27:54 +00004472 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004473 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004474 }else{
drh0c2694b2009-09-03 16:23:44 +00004475 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004476#if SQLITE_ENABLE_LOCKING_STYLE
4477 /* Cache zFilename in the locking context (AFP and dotlock override) for
4478 ** proxyLock activation is possible (remote proxy is based on db name)
4479 ** zFilename remains valid until file is closed, to support */
4480 pNew->lockingContext = (void*)zFilename;
4481#endif
drhda0e7682008-07-30 15:27:54 +00004482 }
danielk1977e339d652008-06-28 11:23:00 +00004483
drh7ed97b92010-01-20 13:07:21 +00004484 if( pLockingStyle == &posixIoMethods
4485#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4486 || pLockingStyle == &nfsIoMethods
4487#endif
4488 ){
drh7708e972008-11-29 00:56:52 +00004489 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004490 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004491 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004492 /* If an error occured in findInodeInfo(), close the file descriptor
4493 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004494 ** in two scenarios:
4495 **
4496 ** (a) A call to fstat() failed.
4497 ** (b) A malloc failed.
4498 **
4499 ** Scenario (b) may only occur if the process is holding no other
4500 ** file descriptors open on the same file. If there were other file
4501 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004502 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004503 ** handle h - as it is guaranteed that no posix locks will be released
4504 ** by doing so.
4505 **
4506 ** If scenario (a) caused the error then things are not so safe. The
4507 ** implicit assumption here is that if fstat() fails, things are in
4508 ** such bad shape that dropping a lock or two doesn't matter much.
4509 */
drh0e9365c2011-03-02 02:08:13 +00004510 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004511 h = -1;
4512 }
drh7708e972008-11-29 00:56:52 +00004513 unixLeaveMutex();
4514 }
danielk1977e339d652008-06-28 11:23:00 +00004515
drhd2cb50b2009-01-09 21:41:17 +00004516#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004517 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004518 /* AFP locking uses the file path so it needs to be included in
4519 ** the afpLockingContext.
4520 */
4521 afpLockingContext *pCtx;
4522 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4523 if( pCtx==0 ){
4524 rc = SQLITE_NOMEM;
4525 }else{
4526 /* NB: zFilename exists and remains valid until the file is closed
4527 ** according to requirement F11141. So we do not need to make a
4528 ** copy of the filename. */
4529 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004530 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004531 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004532 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004533 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004534 if( rc!=SQLITE_OK ){
4535 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004536 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004537 h = -1;
4538 }
drh7708e972008-11-29 00:56:52 +00004539 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004540 }
drh7708e972008-11-29 00:56:52 +00004541 }
4542#endif
danielk1977e339d652008-06-28 11:23:00 +00004543
drh7708e972008-11-29 00:56:52 +00004544 else if( pLockingStyle == &dotlockIoMethods ){
4545 /* Dotfile locking uses the file path so it needs to be included in
4546 ** the dotlockLockingContext
4547 */
4548 char *zLockFile;
4549 int nFilename;
drhea678832008-12-10 19:26:22 +00004550 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004551 zLockFile = (char *)sqlite3_malloc(nFilename);
4552 if( zLockFile==0 ){
4553 rc = SQLITE_NOMEM;
4554 }else{
4555 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004556 }
drh7708e972008-11-29 00:56:52 +00004557 pNew->lockingContext = zLockFile;
4558 }
danielk1977e339d652008-06-28 11:23:00 +00004559
drh6c7d5c52008-11-21 20:32:33 +00004560#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004561 else if( pLockingStyle == &semIoMethods ){
4562 /* Named semaphore locking uses the file path so it needs to be
4563 ** included in the semLockingContext
4564 */
4565 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004566 rc = findInodeInfo(pNew, &pNew->pInode);
4567 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4568 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004569 int n;
drh2238dcc2009-08-27 17:56:20 +00004570 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004571 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004572 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004573 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004574 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4575 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004576 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004577 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004578 }
chw97185482008-11-17 08:05:31 +00004579 }
drh7708e972008-11-29 00:56:52 +00004580 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004581 }
drh7708e972008-11-29 00:56:52 +00004582#endif
aswift5b1a2562008-08-22 00:22:35 +00004583
4584 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004585#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004586 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004587 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004588 h = -1;
chw97185482008-11-17 08:05:31 +00004589 unlink(zFilename);
4590 isDelete = 0;
4591 }
4592 pNew->isDelete = isDelete;
4593#endif
danielk1977e339d652008-06-28 11:23:00 +00004594 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004595 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4596 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004597 }else{
drh7708e972008-11-29 00:56:52 +00004598 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004599 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004600 }
danielk1977e339d652008-06-28 11:23:00 +00004601 return rc;
drh054889e2005-11-30 03:20:31 +00004602}
drh9c06c952005-11-26 00:25:00 +00004603
danielk1977ad94b582007-08-20 06:44:22 +00004604/*
4605** Open a file descriptor to the directory containing file zFilename.
4606** If successful, *pFd is set to the opened file descriptor and
4607** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4608** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4609** value.
4610**
4611** If SQLITE_OK is returned, the caller is responsible for closing
4612** the file descriptor *pFd using close().
4613*/
danielk1977fee2d252007-08-18 10:59:19 +00004614static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004615 int ii;
drh777b17a2007-09-20 10:02:54 +00004616 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004617 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004618
drh153c62c2007-08-24 03:51:33 +00004619 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004620 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004621 if( ii>0 ){
4622 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004623 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004624 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004625#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004626 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004627#endif
drh308c2a52010-05-14 11:30:18 +00004628 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004629 }
4630 }
danielk1977fee2d252007-08-18 10:59:19 +00004631 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004632 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004633}
4634
danielk1977b4b47412007-08-17 15:53:36 +00004635/*
drh8b3cf822010-06-01 21:02:51 +00004636** Return the name of a directory in which to put temporary files.
4637** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004638*/
drh7234c6d2010-06-19 15:10:09 +00004639static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004640 static const char *azDirs[] = {
4641 0,
aswiftaebf4132008-11-21 00:10:35 +00004642 0,
danielk197717b90b52008-06-06 11:11:25 +00004643 "/var/tmp",
4644 "/usr/tmp",
4645 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004646 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004647 };
drh8b3cf822010-06-01 21:02:51 +00004648 unsigned int i;
4649 struct stat buf;
4650 const char *zDir = 0;
4651
4652 azDirs[0] = sqlite3_temp_directory;
4653 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004654 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004655 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004656 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004657 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004658 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004659 break;
4660 }
4661 return zDir;
4662}
4663
4664/*
4665** Create a temporary file name in zBuf. zBuf must be allocated
4666** by the calling process and must be big enough to hold at least
4667** pVfs->mxPathname bytes.
4668*/
4669static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004670 static const unsigned char zChars[] =
4671 "abcdefghijklmnopqrstuvwxyz"
4672 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4673 "0123456789";
drh41022642008-11-21 00:24:42 +00004674 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004675 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004676
4677 /* It's odd to simulate an io-error here, but really this is just
4678 ** using the io-error infrastructure to test that SQLite handles this
4679 ** function failing.
4680 */
4681 SimulateIOError( return SQLITE_IOERR );
4682
drh7234c6d2010-06-19 15:10:09 +00004683 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004684 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004685
4686 /* Check that the output buffer is large enough for the temporary file
4687 ** name. If it is not, return SQLITE_ERROR.
4688 */
danielk197700e13612008-11-17 19:18:54 +00004689 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004690 return SQLITE_ERROR;
4691 }
4692
4693 do{
4694 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004695 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004696 sqlite3_randomness(15, &zBuf[j]);
4697 for(i=0; i<15; i++, j++){
4698 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4699 }
4700 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004701 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004702 return SQLITE_OK;
4703}
4704
drhd2cb50b2009-01-09 21:41:17 +00004705#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004706/*
4707** Routine to transform a unixFile into a proxy-locking unixFile.
4708** Implementation in the proxy-lock division, but used by unixOpen()
4709** if SQLITE_PREFER_PROXY_LOCKING is defined.
4710*/
4711static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004712#endif
drhc66d5b62008-12-03 22:48:32 +00004713
dan08da86a2009-08-21 17:18:03 +00004714/*
4715** Search for an unused file descriptor that was opened on the database
4716** file (not a journal or master-journal file) identified by pathname
4717** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4718** argument to this function.
4719**
4720** Such a file descriptor may exist if a database connection was closed
4721** but the associated file descriptor could not be closed because some
4722** other file descriptor open on the same file is holding a file-lock.
4723** Refer to comments in the unixClose() function and the lengthy comment
4724** describing "Posix Advisory Locking" at the start of this file for
4725** further details. Also, ticket #4018.
4726**
4727** If a suitable file descriptor is found, then it is returned. If no
4728** such file descriptor is located, -1 is returned.
4729*/
dane946c392009-08-22 11:39:46 +00004730static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4731 UnixUnusedFd *pUnused = 0;
4732
4733 /* Do not search for an unused file descriptor on vxworks. Not because
4734 ** vxworks would not benefit from the change (it might, we're not sure),
4735 ** but because no way to test it is currently available. It is better
4736 ** not to risk breaking vxworks support for the sake of such an obscure
4737 ** feature. */
4738#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004739 struct stat sStat; /* Results of stat() call */
4740
4741 /* A stat() call may fail for various reasons. If this happens, it is
4742 ** almost certain that an open() call on the same path will also fail.
4743 ** For this reason, if an error occurs in the stat() call here, it is
4744 ** ignored and -1 is returned. The caller will try to open a new file
4745 ** descriptor on the same path, fail, and return an error to SQLite.
4746 **
4747 ** Even if a subsequent open() call does succeed, the consequences of
4748 ** not searching for a resusable file descriptor are not dire. */
4749 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004750 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004751
4752 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004753 pInode = inodeList;
4754 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4755 || pInode->fileId.ino!=sStat.st_ino) ){
4756 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004757 }
drh8af6c222010-05-14 12:43:01 +00004758 if( pInode ){
dane946c392009-08-22 11:39:46 +00004759 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004760 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004761 pUnused = *pp;
4762 if( pUnused ){
4763 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004764 }
4765 }
4766 unixLeaveMutex();
4767 }
dane946c392009-08-22 11:39:46 +00004768#endif /* if !OS_VXWORKS */
4769 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004770}
danielk197717b90b52008-06-06 11:11:25 +00004771
4772/*
danddb0ac42010-07-14 14:48:58 +00004773** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004774** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004775** and a value suitable for passing as the third argument to open(2) is
4776** written to *pMode. If an IO error occurs, an SQLite error code is
4777** returned and the value of *pMode is not modified.
4778**
4779** If the file being opened is a temporary file, it is always created with
4780** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004781** is a database or master journal file, it is created with the permissions
4782** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004783**
drh8ab58662010-07-15 18:38:39 +00004784** Finally, if the file being opened is a WAL or regular journal file, then
4785** this function queries the file-system for the permissions on the
4786** corresponding database file and sets *pMode to this value. Whenever
4787** possible, WAL and journal files are created using the same permissions
4788** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004789*/
4790static int findCreateFileMode(
4791 const char *zPath, /* Path of file (possibly) being created */
4792 int flags, /* Flags passed as 4th argument to xOpen() */
4793 mode_t *pMode /* OUT: Permissions to open file with */
4794){
4795 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004796 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004797 char zDb[MAX_PATHNAME+1]; /* Database file path */
4798 int nDb; /* Number of valid bytes in zDb */
4799 struct stat sStat; /* Output of stat() on database file */
4800
dana0c989d2010-11-05 18:07:37 +00004801 /* zPath is a path to a WAL or journal file. The following block derives
4802 ** the path to the associated database file from zPath. This block handles
4803 ** the following naming conventions:
4804 **
4805 ** "<path to db>-journal"
4806 ** "<path to db>-wal"
4807 ** "<path to db>-journal-NNNN"
4808 ** "<path to db>-wal-NNNN"
4809 **
4810 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4811 ** used by the test_multiplex.c module.
4812 */
4813 nDb = sqlite3Strlen30(zPath) - 1;
4814 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4815 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004816 memcpy(zDb, zPath, nDb);
4817 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004818
danddb0ac42010-07-14 14:48:58 +00004819 if( 0==stat(zDb, &sStat) ){
4820 *pMode = sStat.st_mode & 0777;
4821 }else{
4822 rc = SQLITE_IOERR_FSTAT;
4823 }
4824 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4825 *pMode = 0600;
4826 }else{
4827 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4828 }
4829 return rc;
4830}
4831
4832/*
danielk1977ad94b582007-08-20 06:44:22 +00004833** Open the file zPath.
4834**
danielk1977b4b47412007-08-17 15:53:36 +00004835** Previously, the SQLite OS layer used three functions in place of this
4836** one:
4837**
4838** sqlite3OsOpenReadWrite();
4839** sqlite3OsOpenReadOnly();
4840** sqlite3OsOpenExclusive();
4841**
4842** These calls correspond to the following combinations of flags:
4843**
4844** ReadWrite() -> (READWRITE | CREATE)
4845** ReadOnly() -> (READONLY)
4846** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4847**
4848** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4849** true, the file was configured to be automatically deleted when the
4850** file handle closed. To achieve the same effect using this new
4851** interface, add the DELETEONCLOSE flag to those specified above for
4852** OpenExclusive().
4853*/
4854static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004855 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4856 const char *zPath, /* Pathname of file to be opened */
4857 sqlite3_file *pFile, /* The file descriptor to be filled in */
4858 int flags, /* Input flags to control the opening */
4859 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004860){
dan08da86a2009-08-21 17:18:03 +00004861 unixFile *p = (unixFile *)pFile;
4862 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004863 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004864 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004865 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004866 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004867 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004868
4869 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4870 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4871 int isCreate = (flags & SQLITE_OPEN_CREATE);
4872 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4873 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004874#if SQLITE_ENABLE_LOCKING_STYLE
4875 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4876#endif
danielk1977b4b47412007-08-17 15:53:36 +00004877
danielk1977fee2d252007-08-18 10:59:19 +00004878 /* If creating a master or main-file journal, this function will open
4879 ** a file-descriptor on the directory too. The first time unixSync()
4880 ** is called the directory file descriptor will be fsync()ed and close()d.
4881 */
danddb0ac42010-07-14 14:48:58 +00004882 int isOpenDirectory = (isCreate && (
4883 eType==SQLITE_OPEN_MASTER_JOURNAL
4884 || eType==SQLITE_OPEN_MAIN_JOURNAL
4885 || eType==SQLITE_OPEN_WAL
4886 ));
danielk1977fee2d252007-08-18 10:59:19 +00004887
danielk197717b90b52008-06-06 11:11:25 +00004888 /* If argument zPath is a NULL pointer, this function is required to open
4889 ** a temporary file. Use this buffer to store the file name in.
4890 */
4891 char zTmpname[MAX_PATHNAME+1];
4892 const char *zName = zPath;
4893
danielk1977fee2d252007-08-18 10:59:19 +00004894 /* Check the following statements are true:
4895 **
4896 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4897 ** (b) if CREATE is set, then READWRITE must also be set, and
4898 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004899 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004900 */
danielk1977b4b47412007-08-17 15:53:36 +00004901 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004902 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004903 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004904 assert(isDelete==0 || isCreate);
4905
danddb0ac42010-07-14 14:48:58 +00004906 /* The main DB, main journal, WAL file and master journal are never
4907 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004908 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4909 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4910 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004911 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004912
danielk1977fee2d252007-08-18 10:59:19 +00004913 /* Assert that the upper layer has set one of the "file-type" flags. */
4914 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4915 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4916 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004917 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004918 );
4919
dan08da86a2009-08-21 17:18:03 +00004920 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004921
dan08da86a2009-08-21 17:18:03 +00004922 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004923 UnixUnusedFd *pUnused;
4924 pUnused = findReusableFd(zName, flags);
4925 if( pUnused ){
4926 fd = pUnused->fd;
4927 }else{
dan6aa657f2009-08-24 18:57:58 +00004928 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004929 if( !pUnused ){
4930 return SQLITE_NOMEM;
4931 }
4932 }
4933 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004934 }else if( !zName ){
4935 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004936 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004937 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004938 if( rc!=SQLITE_OK ){
4939 return rc;
4940 }
4941 zName = zTmpname;
4942 }
4943
dan08da86a2009-08-21 17:18:03 +00004944 /* Determine the value of the flags parameter passed to POSIX function
4945 ** open(). These must be calculated even if open() is not called, as
4946 ** they may be stored as part of the file handle and used by the
4947 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004948 if( isReadonly ) openFlags |= O_RDONLY;
4949 if( isReadWrite ) openFlags |= O_RDWR;
4950 if( isCreate ) openFlags |= O_CREAT;
4951 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4952 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004953
danielk1977b4b47412007-08-17 15:53:36 +00004954 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004955 mode_t openMode; /* Permissions to create file with */
4956 rc = findCreateFileMode(zName, flags, &openMode);
4957 if( rc!=SQLITE_OK ){
4958 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004959 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004960 return rc;
4961 }
drhad4f1e52011-03-04 15:43:57 +00004962 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004963 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004964 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4965 /* Failed to open the file for read/write access. Try read-only. */
4966 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004967 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004968 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004969 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00004970 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00004971 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004972 }
4973 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004974 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004975 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004976 }
danielk1977b4b47412007-08-17 15:53:36 +00004977 }
dan08da86a2009-08-21 17:18:03 +00004978 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004979 if( pOutFlags ){
4980 *pOutFlags = flags;
4981 }
4982
dane946c392009-08-22 11:39:46 +00004983 if( p->pUnused ){
4984 p->pUnused->fd = fd;
4985 p->pUnused->flags = flags;
4986 }
4987
danielk1977b4b47412007-08-17 15:53:36 +00004988 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004989#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004990 zPath = zName;
4991#else
danielk197717b90b52008-06-06 11:11:25 +00004992 unlink(zName);
chw97185482008-11-17 08:05:31 +00004993#endif
danielk1977b4b47412007-08-17 15:53:36 +00004994 }
drh41022642008-11-21 00:24:42 +00004995#if SQLITE_ENABLE_LOCKING_STYLE
4996 else{
dan08da86a2009-08-21 17:18:03 +00004997 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004998 }
4999#endif
5000
danielk1977fee2d252007-08-18 10:59:19 +00005001 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005002 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005003 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005004 /* It is safe to close fd at this point, because it is guaranteed not
5005 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005006 ** it would not be safe to close as this would release any locks held
5007 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005008 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005009 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005010 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005011 }
5012 }
danielk1977e339d652008-06-28 11:23:00 +00005013
5014#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005015 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005016#endif
5017
drhda0e7682008-07-30 15:27:54 +00005018 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005019
drh7ed97b92010-01-20 13:07:21 +00005020
5021#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5022 struct statfs fsInfo;
5023 if( fstatfs(fd, &fsInfo) == -1 ){
5024 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005025 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5026 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005027 return SQLITE_IOERR_ACCESS;
5028 }
5029 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5030 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5031 }
5032#endif
5033
5034#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005035#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005036 isAutoProxy = 1;
5037#endif
5038 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005039 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5040 int useProxy = 0;
5041
dan08da86a2009-08-21 17:18:03 +00005042 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5043 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005044 if( envforce!=NULL ){
5045 useProxy = atoi(envforce)>0;
5046 }else{
5047 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005048 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005049 /* In theory, the close(fd) call is sub-optimal. If the file opened
5050 ** with fd is a database file, and there are other connections open
5051 ** on that file that are currently holding advisory locks on it,
5052 ** then the call to close() will cancel those locks. In practice,
5053 ** we're assuming that statfs() doesn't fail very often. At least
5054 ** not while other file descriptors opened by the same process on
5055 ** the same file are working. */
5056 p->lastErrno = errno;
5057 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005058 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005059 }
drh0e9365c2011-03-02 02:08:13 +00005060 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005061 rc = SQLITE_IOERR_ACCESS;
5062 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005063 }
5064 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5065 }
5066 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005067 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5068 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005069 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005070 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005071 if( rc!=SQLITE_OK ){
5072 /* Use unixClose to clean up the resources added in fillInUnixFile
5073 ** and clear all the structure's references. Specifically,
5074 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5075 */
5076 unixClose(pFile);
5077 return rc;
5078 }
aswiftaebf4132008-11-21 00:10:35 +00005079 }
dane946c392009-08-22 11:39:46 +00005080 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005081 }
5082 }
5083#endif
5084
drh77197112011-03-15 19:08:48 +00005085 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5086 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005087open_finished:
5088 if( rc!=SQLITE_OK ){
5089 sqlite3_free(p->pUnused);
5090 }
5091 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005092}
5093
dane946c392009-08-22 11:39:46 +00005094
danielk1977b4b47412007-08-17 15:53:36 +00005095/*
danielk1977fee2d252007-08-18 10:59:19 +00005096** Delete the file at zPath. If the dirSync argument is true, fsync()
5097** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005098*/
drh6b9d6dd2008-12-03 19:34:47 +00005099static int unixDelete(
5100 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5101 const char *zPath, /* Name of file to be deleted */
5102 int dirSync /* If true, fsync() directory after deleting file */
5103){
danielk1977fee2d252007-08-18 10:59:19 +00005104 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005105 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005106 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005107 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005108 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005109 }
danielk1977d39fa702008-10-16 13:27:40 +00005110#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005111 if( dirSync ){
5112 int fd;
5113 rc = openDirectory(zPath, &fd);
5114 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005115#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005116 if( fsync(fd)==-1 )
5117#else
5118 if( fsync(fd) )
5119#endif
5120 {
dane18d4952011-02-21 11:46:24 +00005121 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005122 }
drh0e9365c2011-03-02 02:08:13 +00005123 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005124 }
5125 }
danielk1977d138dd82008-10-15 16:02:48 +00005126#endif
danielk1977fee2d252007-08-18 10:59:19 +00005127 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005128}
5129
danielk197790949c22007-08-17 16:50:38 +00005130/*
5131** Test the existance of or access permissions of file zPath. The
5132** test performed depends on the value of flags:
5133**
5134** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5135** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5136** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5137**
5138** Otherwise return 0.
5139*/
danielk1977861f7452008-06-05 11:39:11 +00005140static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005141 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5142 const char *zPath, /* Path of the file to examine */
5143 int flags, /* What do we want to learn about the zPath file? */
5144 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005145){
rse25c0d1a2007-09-20 08:38:14 +00005146 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005147 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005148 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005149 switch( flags ){
5150 case SQLITE_ACCESS_EXISTS:
5151 amode = F_OK;
5152 break;
5153 case SQLITE_ACCESS_READWRITE:
5154 amode = W_OK|R_OK;
5155 break;
drh50d3f902007-08-27 21:10:36 +00005156 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005157 amode = R_OK;
5158 break;
5159
5160 default:
5161 assert(!"Invalid flags argument");
5162 }
drh99ab3b12011-03-02 15:09:07 +00005163 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005164 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5165 struct stat buf;
5166 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5167 *pResOut = 0;
5168 }
5169 }
danielk1977861f7452008-06-05 11:39:11 +00005170 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005171}
5172
danielk1977b4b47412007-08-17 15:53:36 +00005173
5174/*
5175** Turn a relative pathname into a full pathname. The relative path
5176** is stored as a nul-terminated string in the buffer pointed to by
5177** zPath.
5178**
5179** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5180** (in this case, MAX_PATHNAME bytes). The full-path is written to
5181** this buffer before returning.
5182*/
danielk1977adfb9b02007-09-17 07:02:56 +00005183static int unixFullPathname(
5184 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5185 const char *zPath, /* Possibly relative input path */
5186 int nOut, /* Size of output buffer in bytes */
5187 char *zOut /* Output buffer */
5188){
danielk1977843e65f2007-09-01 16:16:15 +00005189
5190 /* It's odd to simulate an io-error here, but really this is just
5191 ** using the io-error infrastructure to test that SQLite handles this
5192 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005193 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005194 */
5195 SimulateIOError( return SQLITE_ERROR );
5196
drh153c62c2007-08-24 03:51:33 +00005197 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005198 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005199
drh3c7f2dc2007-12-06 13:26:20 +00005200 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005201 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005202 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005203 }else{
5204 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005205 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005206 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005207 }
drhea678832008-12-10 19:26:22 +00005208 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005209 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005210 }
5211 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005212}
5213
drh0ccebe72005-06-07 22:22:50 +00005214
drh761df872006-12-21 01:29:22 +00005215#ifndef SQLITE_OMIT_LOAD_EXTENSION
5216/*
5217** Interfaces for opening a shared library, finding entry points
5218** within the shared library, and closing the shared library.
5219*/
5220#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005221static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5222 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005223 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5224}
danielk197795c8a542007-09-01 06:51:27 +00005225
5226/*
5227** SQLite calls this function immediately after a call to unixDlSym() or
5228** unixDlOpen() fails (returns a null pointer). If a more detailed error
5229** message is available, it is written to zBufOut. If no error message
5230** is available, zBufOut is left unmodified and SQLite uses a default
5231** error message.
5232*/
danielk1977397d65f2008-11-19 11:35:39 +00005233static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005234 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005235 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005236 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005237 zErr = dlerror();
5238 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005239 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005240 }
drh6c7d5c52008-11-21 20:32:33 +00005241 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005242}
drh1875f7a2008-12-08 18:19:17 +00005243static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5244 /*
5245 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5246 ** cast into a pointer to a function. And yet the library dlsym() routine
5247 ** returns a void* which is really a pointer to a function. So how do we
5248 ** use dlsym() with -pedantic-errors?
5249 **
5250 ** Variable x below is defined to be a pointer to a function taking
5251 ** parameters void* and const char* and returning a pointer to a function.
5252 ** We initialize x by assigning it a pointer to the dlsym() function.
5253 ** (That assignment requires a cast.) Then we call the function that
5254 ** x points to.
5255 **
5256 ** This work-around is unlikely to work correctly on any system where
5257 ** you really cannot cast a function pointer into void*. But then, on the
5258 ** other hand, dlsym() will not work on such a system either, so we have
5259 ** not really lost anything.
5260 */
5261 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005262 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005263 x = (void(*(*)(void*,const char*))(void))dlsym;
5264 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005265}
danielk1977397d65f2008-11-19 11:35:39 +00005266static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5267 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005268 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005269}
danielk1977b4b47412007-08-17 15:53:36 +00005270#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5271 #define unixDlOpen 0
5272 #define unixDlError 0
5273 #define unixDlSym 0
5274 #define unixDlClose 0
5275#endif
5276
5277/*
danielk197790949c22007-08-17 16:50:38 +00005278** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005279*/
danielk1977397d65f2008-11-19 11:35:39 +00005280static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5281 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005282 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005283
drhbbd42a62004-05-22 17:41:58 +00005284 /* We have to initialize zBuf to prevent valgrind from reporting
5285 ** errors. The reports issued by valgrind are incorrect - we would
5286 ** prefer that the randomness be increased by making use of the
5287 ** uninitialized space in zBuf - but valgrind errors tend to worry
5288 ** some users. Rather than argue, it seems easier just to initialize
5289 ** the whole array and silence valgrind, even if that means less randomness
5290 ** in the random seed.
5291 **
5292 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005293 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005294 ** tests repeatable.
5295 */
danielk1977b4b47412007-08-17 15:53:36 +00005296 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005297#if !defined(SQLITE_TEST)
5298 {
drh842b8642005-01-21 17:53:17 +00005299 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005300 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005301 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005302 time_t t;
5303 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005304 memcpy(zBuf, &t, sizeof(t));
5305 pid = getpid();
5306 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005307 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005308 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005309 }else{
drhe562be52011-03-02 18:01:10 +00005310 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005311 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005312 }
drhbbd42a62004-05-22 17:41:58 +00005313 }
5314#endif
drh72cbd072008-10-14 17:58:38 +00005315 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005316}
5317
danielk1977b4b47412007-08-17 15:53:36 +00005318
drhbbd42a62004-05-22 17:41:58 +00005319/*
5320** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005321** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005322** The return value is the number of microseconds of sleep actually
5323** requested from the underlying operating system, a number which
5324** might be greater than or equal to the argument, but not less
5325** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005326*/
danielk1977397d65f2008-11-19 11:35:39 +00005327static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005328#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005329 struct timespec sp;
5330
5331 sp.tv_sec = microseconds / 1000000;
5332 sp.tv_nsec = (microseconds % 1000000) * 1000;
5333 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005334 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005335 return microseconds;
5336#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005337 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005338 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005339 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005340#else
danielk1977b4b47412007-08-17 15:53:36 +00005341 int seconds = (microseconds+999999)/1000000;
5342 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005343 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005344 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005345#endif
drh88f474a2006-01-02 20:00:12 +00005346}
5347
5348/*
drh6b9d6dd2008-12-03 19:34:47 +00005349** The following variable, if set to a non-zero value, is interpreted as
5350** the number of seconds since 1970 and is used to set the result of
5351** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005352*/
5353#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005354int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005355#endif
5356
5357/*
drhb7e8ea22010-05-03 14:32:30 +00005358** Find the current time (in Universal Coordinated Time). Write into *piNow
5359** the current time and date as a Julian Day number times 86_400_000. In
5360** other words, write into *piNow the number of milliseconds since the Julian
5361** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5362** proleptic Gregorian calendar.
5363**
5364** On success, return 0. Return 1 if the time and date cannot be found.
5365*/
5366static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5367 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5368#if defined(NO_GETTOD)
5369 time_t t;
5370 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005371 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005372#elif OS_VXWORKS
5373 struct timespec sNow;
5374 clock_gettime(CLOCK_REALTIME, &sNow);
5375 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5376#else
5377 struct timeval sNow;
5378 gettimeofday(&sNow, 0);
5379 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5380#endif
5381
5382#ifdef SQLITE_TEST
5383 if( sqlite3_current_time ){
5384 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5385 }
5386#endif
5387 UNUSED_PARAMETER(NotUsed);
5388 return 0;
5389}
5390
5391/*
drhbbd42a62004-05-22 17:41:58 +00005392** Find the current time (in Universal Coordinated Time). Write the
5393** current time and date as a Julian Day number into *prNow and
5394** return 0. Return 1 if the time and date cannot be found.
5395*/
danielk1977397d65f2008-11-19 11:35:39 +00005396static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005397 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005398 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005399 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005400 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005401 return 0;
5402}
danielk1977b4b47412007-08-17 15:53:36 +00005403
drh6b9d6dd2008-12-03 19:34:47 +00005404/*
5405** We added the xGetLastError() method with the intention of providing
5406** better low-level error messages when operating-system problems come up
5407** during SQLite operation. But so far, none of that has been implemented
5408** in the core. So this routine is never called. For now, it is merely
5409** a place-holder.
5410*/
danielk1977397d65f2008-11-19 11:35:39 +00005411static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5412 UNUSED_PARAMETER(NotUsed);
5413 UNUSED_PARAMETER(NotUsed2);
5414 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005415 return 0;
5416}
5417
drhf2424c52010-04-26 00:04:55 +00005418
5419/*
drh734c9862008-11-28 15:37:20 +00005420************************ End of sqlite3_vfs methods ***************************
5421******************************************************************************/
5422
drh715ff302008-12-03 22:32:44 +00005423/******************************************************************************
5424************************** Begin Proxy Locking ********************************
5425**
5426** Proxy locking is a "uber-locking-method" in this sense: It uses the
5427** other locking methods on secondary lock files. Proxy locking is a
5428** meta-layer over top of the primitive locking implemented above. For
5429** this reason, the division that implements of proxy locking is deferred
5430** until late in the file (here) after all of the other I/O methods have
5431** been defined - so that the primitive locking methods are available
5432** as services to help with the implementation of proxy locking.
5433**
5434****
5435**
5436** The default locking schemes in SQLite use byte-range locks on the
5437** database file to coordinate safe, concurrent access by multiple readers
5438** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5439** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5440** as POSIX read & write locks over fixed set of locations (via fsctl),
5441** on AFP and SMB only exclusive byte-range locks are available via fsctl
5442** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5443** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5444** address in the shared range is taken for a SHARED lock, the entire
5445** shared range is taken for an EXCLUSIVE lock):
5446**
5447** PENDING_BYTE 0x40000000
5448** RESERVED_BYTE 0x40000001
5449** SHARED_RANGE 0x40000002 -> 0x40000200
5450**
5451** This works well on the local file system, but shows a nearly 100x
5452** slowdown in read performance on AFP because the AFP client disables
5453** the read cache when byte-range locks are present. Enabling the read
5454** cache exposes a cache coherency problem that is present on all OS X
5455** supported network file systems. NFS and AFP both observe the
5456** close-to-open semantics for ensuring cache coherency
5457** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5458** address the requirements for concurrent database access by multiple
5459** readers and writers
5460** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5461**
5462** To address the performance and cache coherency issues, proxy file locking
5463** changes the way database access is controlled by limiting access to a
5464** single host at a time and moving file locks off of the database file
5465** and onto a proxy file on the local file system.
5466**
5467**
5468** Using proxy locks
5469** -----------------
5470**
5471** C APIs
5472**
5473** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5474** <proxy_path> | ":auto:");
5475** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5476**
5477**
5478** SQL pragmas
5479**
5480** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5481** PRAGMA [database.]lock_proxy_file
5482**
5483** Specifying ":auto:" means that if there is a conch file with a matching
5484** host ID in it, the proxy path in the conch file will be used, otherwise
5485** a proxy path based on the user's temp dir
5486** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5487** actual proxy file name is generated from the name and path of the
5488** database file. For example:
5489**
5490** For database path "/Users/me/foo.db"
5491** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5492**
5493** Once a lock proxy is configured for a database connection, it can not
5494** be removed, however it may be switched to a different proxy path via
5495** the above APIs (assuming the conch file is not being held by another
5496** connection or process).
5497**
5498**
5499** How proxy locking works
5500** -----------------------
5501**
5502** Proxy file locking relies primarily on two new supporting files:
5503**
5504** * conch file to limit access to the database file to a single host
5505** at a time
5506**
5507** * proxy file to act as a proxy for the advisory locks normally
5508** taken on the database
5509**
5510** The conch file - to use a proxy file, sqlite must first "hold the conch"
5511** by taking an sqlite-style shared lock on the conch file, reading the
5512** contents and comparing the host's unique host ID (see below) and lock
5513** proxy path against the values stored in the conch. The conch file is
5514** stored in the same directory as the database file and the file name
5515** is patterned after the database file name as ".<databasename>-conch".
5516** If the conch file does not exist, or it's contents do not match the
5517** host ID and/or proxy path, then the lock is escalated to an exclusive
5518** lock and the conch file contents is updated with the host ID and proxy
5519** path and the lock is downgraded to a shared lock again. If the conch
5520** is held by another process (with a shared lock), the exclusive lock
5521** will fail and SQLITE_BUSY is returned.
5522**
5523** The proxy file - a single-byte file used for all advisory file locks
5524** normally taken on the database file. This allows for safe sharing
5525** of the database file for multiple readers and writers on the same
5526** host (the conch ensures that they all use the same local lock file).
5527**
drh715ff302008-12-03 22:32:44 +00005528** Requesting the lock proxy does not immediately take the conch, it is
5529** only taken when the first request to lock database file is made.
5530** This matches the semantics of the traditional locking behavior, where
5531** opening a connection to a database file does not take a lock on it.
5532** The shared lock and an open file descriptor are maintained until
5533** the connection to the database is closed.
5534**
5535** The proxy file and the lock file are never deleted so they only need
5536** to be created the first time they are used.
5537**
5538** Configuration options
5539** ---------------------
5540**
5541** SQLITE_PREFER_PROXY_LOCKING
5542**
5543** Database files accessed on non-local file systems are
5544** automatically configured for proxy locking, lock files are
5545** named automatically using the same logic as
5546** PRAGMA lock_proxy_file=":auto:"
5547**
5548** SQLITE_PROXY_DEBUG
5549**
5550** Enables the logging of error messages during host id file
5551** retrieval and creation
5552**
drh715ff302008-12-03 22:32:44 +00005553** LOCKPROXYDIR
5554**
5555** Overrides the default directory used for lock proxy files that
5556** are named automatically via the ":auto:" setting
5557**
5558** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5559**
5560** Permissions to use when creating a directory for storing the
5561** lock proxy files, only used when LOCKPROXYDIR is not set.
5562**
5563**
5564** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5565** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5566** force proxy locking to be used for every database file opened, and 0
5567** will force automatic proxy locking to be disabled for all database
5568** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5569** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5570*/
5571
5572/*
5573** Proxy locking is only available on MacOSX
5574*/
drhd2cb50b2009-01-09 21:41:17 +00005575#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005576
drh715ff302008-12-03 22:32:44 +00005577/*
5578** The proxyLockingContext has the path and file structures for the remote
5579** and local proxy files in it
5580*/
5581typedef struct proxyLockingContext proxyLockingContext;
5582struct proxyLockingContext {
5583 unixFile *conchFile; /* Open conch file */
5584 char *conchFilePath; /* Name of the conch file */
5585 unixFile *lockProxy; /* Open proxy lock file */
5586 char *lockProxyPath; /* Name of the proxy lock file */
5587 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005588 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005589 void *oldLockingContext; /* Original lockingcontext to restore on close */
5590 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5591};
5592
drh7ed97b92010-01-20 13:07:21 +00005593/*
5594** The proxy lock file path for the database at dbPath is written into lPath,
5595** which must point to valid, writable memory large enough for a maxLen length
5596** file path.
drh715ff302008-12-03 22:32:44 +00005597*/
drh715ff302008-12-03 22:32:44 +00005598static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5599 int len;
5600 int dbLen;
5601 int i;
5602
5603#ifdef LOCKPROXYDIR
5604 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5605#else
5606# ifdef _CS_DARWIN_USER_TEMP_DIR
5607 {
drh7ed97b92010-01-20 13:07:21 +00005608 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005609 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5610 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005611 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005612 }
drh7ed97b92010-01-20 13:07:21 +00005613 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005614 }
5615# else
5616 len = strlcpy(lPath, "/tmp/", maxLen);
5617# endif
5618#endif
5619
5620 if( lPath[len-1]!='/' ){
5621 len = strlcat(lPath, "/", maxLen);
5622 }
5623
5624 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005625 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005626 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005627 char c = dbPath[i];
5628 lPath[i+len] = (c=='/')?'_':c;
5629 }
5630 lPath[i+len]='\0';
5631 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005632 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005633 return SQLITE_OK;
5634}
5635
drh7ed97b92010-01-20 13:07:21 +00005636/*
5637 ** Creates the lock file and any missing directories in lockPath
5638 */
5639static int proxyCreateLockPath(const char *lockPath){
5640 int i, len;
5641 char buf[MAXPATHLEN];
5642 int start = 0;
5643
5644 assert(lockPath!=NULL);
5645 /* try to create all the intermediate directories */
5646 len = (int)strlen(lockPath);
5647 buf[0] = lockPath[0];
5648 for( i=1; i<len; i++ ){
5649 if( lockPath[i] == '/' && (i - start > 0) ){
5650 /* only mkdir if leaf dir != "." or "/" or ".." */
5651 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5652 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5653 buf[i]='\0';
5654 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5655 int err=errno;
5656 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005657 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005658 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005659 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005660 return err;
5661 }
5662 }
5663 }
5664 start=i+1;
5665 }
5666 buf[i] = lockPath[i];
5667 }
drh308c2a52010-05-14 11:30:18 +00005668 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005669 return 0;
5670}
5671
drh715ff302008-12-03 22:32:44 +00005672/*
5673** Create a new VFS file descriptor (stored in memory obtained from
5674** sqlite3_malloc) and open the file named "path" in the file descriptor.
5675**
5676** The caller is responsible not only for closing the file descriptor
5677** but also for freeing the memory associated with the file descriptor.
5678*/
drh7ed97b92010-01-20 13:07:21 +00005679static int proxyCreateUnixFile(
5680 const char *path, /* path for the new unixFile */
5681 unixFile **ppFile, /* unixFile created and returned by ref */
5682 int islockfile /* if non zero missing dirs will be created */
5683) {
5684 int fd = -1;
5685 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005686 unixFile *pNew;
5687 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005688 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005689 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005690 int terrno = 0;
5691 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005692
drh7ed97b92010-01-20 13:07:21 +00005693 /* 1. first try to open/create the file
5694 ** 2. if that fails, and this is a lock file (not-conch), try creating
5695 ** the parent directories and then try again.
5696 ** 3. if that fails, try to open the file read-only
5697 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5698 */
5699 pUnused = findReusableFd(path, openFlags);
5700 if( pUnused ){
5701 fd = pUnused->fd;
5702 }else{
5703 pUnused = sqlite3_malloc(sizeof(*pUnused));
5704 if( !pUnused ){
5705 return SQLITE_NOMEM;
5706 }
5707 }
5708 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005709 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005710 terrno = errno;
5711 if( fd<0 && errno==ENOENT && islockfile ){
5712 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005713 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005714 }
5715 }
5716 }
5717 if( fd<0 ){
5718 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005719 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005720 terrno = errno;
5721 }
5722 if( fd<0 ){
5723 if( islockfile ){
5724 return SQLITE_BUSY;
5725 }
5726 switch (terrno) {
5727 case EACCES:
5728 return SQLITE_PERM;
5729 case EIO:
5730 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5731 default:
drh9978c972010-02-23 17:36:32 +00005732 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005733 }
5734 }
5735
5736 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5737 if( pNew==NULL ){
5738 rc = SQLITE_NOMEM;
5739 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005740 }
5741 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005742 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005743 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005744 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005745 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005746 pUnused->fd = fd;
5747 pUnused->flags = openFlags;
5748 pNew->pUnused = pUnused;
5749
drh77197112011-03-15 19:08:48 +00005750 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005751 if( rc==SQLITE_OK ){
5752 *ppFile = pNew;
5753 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005754 }
drh7ed97b92010-01-20 13:07:21 +00005755end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005756 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005757 sqlite3_free(pNew);
5758 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005759 return rc;
5760}
5761
drh7ed97b92010-01-20 13:07:21 +00005762#ifdef SQLITE_TEST
5763/* simulate multiple hosts by creating unique hostid file paths */
5764int sqlite3_hostid_num = 0;
5765#endif
5766
5767#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5768
drh0ab216a2010-07-02 17:10:40 +00005769/* Not always defined in the headers as it ought to be */
5770extern int gethostuuid(uuid_t id, const struct timespec *wait);
5771
drh7ed97b92010-01-20 13:07:21 +00005772/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5773** bytes of writable memory.
5774*/
5775static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005776 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5777 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005778#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5779 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005780 {
5781 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5782 if( gethostuuid(pHostID, &timeout) ){
5783 int err = errno;
5784 if( pError ){
5785 *pError = err;
5786 }
5787 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005788 }
drh7ed97b92010-01-20 13:07:21 +00005789 }
drhe8b0c9b2010-09-25 14:13:17 +00005790#endif
drh7ed97b92010-01-20 13:07:21 +00005791#ifdef SQLITE_TEST
5792 /* simulate multiple hosts by creating unique hostid file paths */
5793 if( sqlite3_hostid_num != 0){
5794 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5795 }
5796#endif
5797
5798 return SQLITE_OK;
5799}
5800
5801/* The conch file contains the header, host id and lock file path
5802 */
5803#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5804#define PROXY_HEADERLEN 1 /* conch file header length */
5805#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5806#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5807
5808/*
5809** Takes an open conch file, copies the contents to a new path and then moves
5810** it back. The newly created file's file descriptor is assigned to the
5811** conch file structure and finally the original conch file descriptor is
5812** closed. Returns zero if successful.
5813*/
5814static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5815 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5816 unixFile *conchFile = pCtx->conchFile;
5817 char tPath[MAXPATHLEN];
5818 char buf[PROXY_MAXCONCHLEN];
5819 char *cPath = pCtx->conchFilePath;
5820 size_t readLen = 0;
5821 size_t pathLen = 0;
5822 char errmsg[64] = "";
5823 int fd = -1;
5824 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005825 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005826
5827 /* create a new path by replace the trailing '-conch' with '-break' */
5828 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5829 if( pathLen>MAXPATHLEN || pathLen<6 ||
5830 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005831 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005832 goto end_breaklock;
5833 }
5834 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005835 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005836 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005837 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005838 goto end_breaklock;
5839 }
5840 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005841 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5842 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005843 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005844 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005845 goto end_breaklock;
5846 }
drhe562be52011-03-02 18:01:10 +00005847 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005848 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005849 goto end_breaklock;
5850 }
5851 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005852 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005853 goto end_breaklock;
5854 }
5855 rc = 0;
5856 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005857 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005858 conchFile->h = fd;
5859 conchFile->openFlags = O_RDWR | O_CREAT;
5860
5861end_breaklock:
5862 if( rc ){
5863 if( fd>=0 ){
5864 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005865 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005866 }
5867 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5868 }
5869 return rc;
5870}
5871
5872/* Take the requested lock on the conch file and break a stale lock if the
5873** host id matches.
5874*/
5875static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5876 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5877 unixFile *conchFile = pCtx->conchFile;
5878 int rc = SQLITE_OK;
5879 int nTries = 0;
5880 struct timespec conchModTime;
5881
5882 do {
5883 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5884 nTries ++;
5885 if( rc==SQLITE_BUSY ){
5886 /* If the lock failed (busy):
5887 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5888 * 2nd try: fail if the mod time changed or host id is different, wait
5889 * 10 sec and try again
5890 * 3rd try: break the lock unless the mod time has changed.
5891 */
5892 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005893 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005894 pFile->lastErrno = errno;
5895 return SQLITE_IOERR_LOCK;
5896 }
5897
5898 if( nTries==1 ){
5899 conchModTime = buf.st_mtimespec;
5900 usleep(500000); /* wait 0.5 sec and try the lock again*/
5901 continue;
5902 }
5903
5904 assert( nTries>1 );
5905 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5906 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5907 return SQLITE_BUSY;
5908 }
5909
5910 if( nTries==2 ){
5911 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005912 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005913 if( len<0 ){
5914 pFile->lastErrno = errno;
5915 return SQLITE_IOERR_LOCK;
5916 }
5917 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5918 /* don't break the lock if the host id doesn't match */
5919 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5920 return SQLITE_BUSY;
5921 }
5922 }else{
5923 /* don't break the lock on short read or a version mismatch */
5924 return SQLITE_BUSY;
5925 }
5926 usleep(10000000); /* wait 10 sec and try the lock again */
5927 continue;
5928 }
5929
5930 assert( nTries==3 );
5931 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5932 rc = SQLITE_OK;
5933 if( lockType==EXCLUSIVE_LOCK ){
5934 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5935 }
5936 if( !rc ){
5937 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5938 }
5939 }
5940 }
5941 } while( rc==SQLITE_BUSY && nTries<3 );
5942
5943 return rc;
5944}
5945
5946/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005947** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5948** lockPath means that the lockPath in the conch file will be used if the
5949** host IDs match, or a new lock path will be generated automatically
5950** and written to the conch file.
5951*/
5952static int proxyTakeConch(unixFile *pFile){
5953 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5954
drh7ed97b92010-01-20 13:07:21 +00005955 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005956 return SQLITE_OK;
5957 }else{
5958 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005959 uuid_t myHostID;
5960 int pError = 0;
5961 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005962 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005963 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005964 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005965 int createConch = 0;
5966 int hostIdMatch = 0;
5967 int readLen = 0;
5968 int tryOldLockPath = 0;
5969 int forceNewLockPath = 0;
5970
drh308c2a52010-05-14 11:30:18 +00005971 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5972 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005973
drh7ed97b92010-01-20 13:07:21 +00005974 rc = proxyGetHostID(myHostID, &pError);
5975 if( (rc&0xff)==SQLITE_IOERR ){
5976 pFile->lastErrno = pError;
5977 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005978 }
drh7ed97b92010-01-20 13:07:21 +00005979 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005980 if( rc!=SQLITE_OK ){
5981 goto end_takeconch;
5982 }
drh7ed97b92010-01-20 13:07:21 +00005983 /* read the existing conch file */
5984 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5985 if( readLen<0 ){
5986 /* I/O error: lastErrno set by seekAndRead */
5987 pFile->lastErrno = conchFile->lastErrno;
5988 rc = SQLITE_IOERR_READ;
5989 goto end_takeconch;
5990 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5991 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5992 /* a short read or version format mismatch means we need to create a new
5993 ** conch file.
5994 */
5995 createConch = 1;
5996 }
5997 /* if the host id matches and the lock path already exists in the conch
5998 ** we'll try to use the path there, if we can't open that path, we'll
5999 ** retry with a new auto-generated path
6000 */
6001 do { /* in case we need to try again for an :auto: named lock file */
6002
6003 if( !createConch && !forceNewLockPath ){
6004 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6005 PROXY_HOSTIDLEN);
6006 /* if the conch has data compare the contents */
6007 if( !pCtx->lockProxyPath ){
6008 /* for auto-named local lock file, just check the host ID and we'll
6009 ** use the local lock file path that's already in there
6010 */
6011 if( hostIdMatch ){
6012 size_t pathLen = (readLen - PROXY_PATHINDEX);
6013
6014 if( pathLen>=MAXPATHLEN ){
6015 pathLen=MAXPATHLEN-1;
6016 }
6017 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6018 lockPath[pathLen] = 0;
6019 tempLockPath = lockPath;
6020 tryOldLockPath = 1;
6021 /* create a copy of the lock path if the conch is taken */
6022 goto end_takeconch;
6023 }
6024 }else if( hostIdMatch
6025 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6026 readLen-PROXY_PATHINDEX)
6027 ){
6028 /* conch host and lock path match */
6029 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006030 }
drh7ed97b92010-01-20 13:07:21 +00006031 }
6032
6033 /* if the conch isn't writable and doesn't match, we can't take it */
6034 if( (conchFile->openFlags&O_RDWR) == 0 ){
6035 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006036 goto end_takeconch;
6037 }
drh7ed97b92010-01-20 13:07:21 +00006038
6039 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006040 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006041 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6042 tempLockPath = lockPath;
6043 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006044 }
drh7ed97b92010-01-20 13:07:21 +00006045
6046 /* update conch with host and path (this will fail if other process
6047 ** has a shared lock already), if the host id matches, use the big
6048 ** stick.
drh715ff302008-12-03 22:32:44 +00006049 */
drh7ed97b92010-01-20 13:07:21 +00006050 futimes(conchFile->h, NULL);
6051 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006052 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006053 /* We are trying for an exclusive lock but another thread in this
6054 ** same process is still holding a shared lock. */
6055 rc = SQLITE_BUSY;
6056 } else {
6057 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006058 }
drh715ff302008-12-03 22:32:44 +00006059 }else{
drh7ed97b92010-01-20 13:07:21 +00006060 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006061 }
drh7ed97b92010-01-20 13:07:21 +00006062 if( rc==SQLITE_OK ){
6063 char writeBuffer[PROXY_MAXCONCHLEN];
6064 int writeSize = 0;
6065
6066 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6067 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6068 if( pCtx->lockProxyPath!=NULL ){
6069 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6070 }else{
6071 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6072 }
6073 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006074 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006075 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6076 fsync(conchFile->h);
6077 /* If we created a new conch file (not just updated the contents of a
6078 ** valid conch file), try to match the permissions of the database
6079 */
6080 if( rc==SQLITE_OK && createConch ){
6081 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006082 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006083 if( err==0 ){
6084 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6085 S_IROTH|S_IWOTH);
6086 /* try to match the database file R/W permissions, ignore failure */
6087#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006088 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006089#else
drhff812312011-02-23 13:33:46 +00006090 do{
drhe562be52011-03-02 18:01:10 +00006091 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006092 }while( rc==(-1) && errno==EINTR );
6093 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006094 int code = errno;
6095 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6096 cmode, code, strerror(code));
6097 } else {
6098 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6099 }
6100 }else{
6101 int code = errno;
6102 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6103 err, code, strerror(code));
6104#endif
6105 }
drh715ff302008-12-03 22:32:44 +00006106 }
6107 }
drh7ed97b92010-01-20 13:07:21 +00006108 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6109
6110 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006111 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006112 if( rc==SQLITE_OK && pFile->openFlags ){
6113 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006114 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006115 }
6116 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006117 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006118 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006119 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006120 if( fd>=0 ){
6121 pFile->h = fd;
6122 }else{
drh9978c972010-02-23 17:36:32 +00006123 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006124 during locking */
6125 }
6126 }
6127 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6128 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6129 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6130 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6131 /* we couldn't create the proxy lock file with the old lock file path
6132 ** so try again via auto-naming
6133 */
6134 forceNewLockPath = 1;
6135 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006136 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006137 }
6138 }
6139 if( rc==SQLITE_OK ){
6140 /* Need to make a copy of path if we extracted the value
6141 ** from the conch file or the path was allocated on the stack
6142 */
6143 if( tempLockPath ){
6144 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6145 if( !pCtx->lockProxyPath ){
6146 rc = SQLITE_NOMEM;
6147 }
6148 }
6149 }
6150 if( rc==SQLITE_OK ){
6151 pCtx->conchHeld = 1;
6152
6153 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6154 afpLockingContext *afpCtx;
6155 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6156 afpCtx->dbPath = pCtx->lockProxyPath;
6157 }
6158 } else {
6159 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6160 }
drh308c2a52010-05-14 11:30:18 +00006161 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6162 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006163 return rc;
drh308c2a52010-05-14 11:30:18 +00006164 } while (1); /* in case we need to retry the :auto: lock file -
6165 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006166 }
6167}
6168
6169/*
6170** If pFile holds a lock on a conch file, then release that lock.
6171*/
6172static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006173 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006174 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6175 unixFile *conchFile; /* Name of the conch file */
6176
6177 pCtx = (proxyLockingContext *)pFile->lockingContext;
6178 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006179 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006180 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006181 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006182 if( pCtx->conchHeld>0 ){
6183 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6184 }
drh715ff302008-12-03 22:32:44 +00006185 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006186 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6187 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006188 return rc;
6189}
6190
6191/*
6192** Given the name of a database file, compute the name of its conch file.
6193** Store the conch filename in memory obtained from sqlite3_malloc().
6194** Make *pConchPath point to the new name. Return SQLITE_OK on success
6195** or SQLITE_NOMEM if unable to obtain memory.
6196**
6197** The caller is responsible for ensuring that the allocated memory
6198** space is eventually freed.
6199**
6200** *pConchPath is set to NULL if a memory allocation error occurs.
6201*/
6202static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6203 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006204 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006205 char *conchPath; /* buffer in which to construct conch name */
6206
6207 /* Allocate space for the conch filename and initialize the name to
6208 ** the name of the original database file. */
6209 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6210 if( conchPath==0 ){
6211 return SQLITE_NOMEM;
6212 }
6213 memcpy(conchPath, dbPath, len+1);
6214
6215 /* now insert a "." before the last / character */
6216 for( i=(len-1); i>=0; i-- ){
6217 if( conchPath[i]=='/' ){
6218 i++;
6219 break;
6220 }
6221 }
6222 conchPath[i]='.';
6223 while ( i<len ){
6224 conchPath[i+1]=dbPath[i];
6225 i++;
6226 }
6227
6228 /* append the "-conch" suffix to the file */
6229 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006230 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006231
6232 return SQLITE_OK;
6233}
6234
6235
6236/* Takes a fully configured proxy locking-style unix file and switches
6237** the local lock file path
6238*/
6239static int switchLockProxyPath(unixFile *pFile, const char *path) {
6240 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6241 char *oldPath = pCtx->lockProxyPath;
6242 int rc = SQLITE_OK;
6243
drh308c2a52010-05-14 11:30:18 +00006244 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006245 return SQLITE_BUSY;
6246 }
6247
6248 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6249 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6250 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6251 return SQLITE_OK;
6252 }else{
6253 unixFile *lockProxy = pCtx->lockProxy;
6254 pCtx->lockProxy=NULL;
6255 pCtx->conchHeld = 0;
6256 if( lockProxy!=NULL ){
6257 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6258 if( rc ) return rc;
6259 sqlite3_free(lockProxy);
6260 }
6261 sqlite3_free(oldPath);
6262 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6263 }
6264
6265 return rc;
6266}
6267
6268/*
6269** pFile is a file that has been opened by a prior xOpen call. dbPath
6270** is a string buffer at least MAXPATHLEN+1 characters in size.
6271**
6272** This routine find the filename associated with pFile and writes it
6273** int dbPath.
6274*/
6275static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006276#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006277 if( pFile->pMethod == &afpIoMethods ){
6278 /* afp style keeps a reference to the db path in the filePath field
6279 ** of the struct */
drhea678832008-12-10 19:26:22 +00006280 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006281 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6282 } else
drh715ff302008-12-03 22:32:44 +00006283#endif
6284 if( pFile->pMethod == &dotlockIoMethods ){
6285 /* dot lock style uses the locking context to store the dot lock
6286 ** file path */
6287 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6288 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6289 }else{
6290 /* all other styles use the locking context to store the db file path */
6291 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006292 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006293 }
6294 return SQLITE_OK;
6295}
6296
6297/*
6298** Takes an already filled in unix file and alters it so all file locking
6299** will be performed on the local proxy lock file. The following fields
6300** are preserved in the locking context so that they can be restored and
6301** the unix structure properly cleaned up at close time:
6302** ->lockingContext
6303** ->pMethod
6304*/
6305static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6306 proxyLockingContext *pCtx;
6307 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6308 char *lockPath=NULL;
6309 int rc = SQLITE_OK;
6310
drh308c2a52010-05-14 11:30:18 +00006311 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006312 return SQLITE_BUSY;
6313 }
6314 proxyGetDbPathForUnixFile(pFile, dbPath);
6315 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6316 lockPath=NULL;
6317 }else{
6318 lockPath=(char *)path;
6319 }
6320
drh308c2a52010-05-14 11:30:18 +00006321 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6322 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006323
6324 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6325 if( pCtx==0 ){
6326 return SQLITE_NOMEM;
6327 }
6328 memset(pCtx, 0, sizeof(*pCtx));
6329
6330 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6331 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006332 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6333 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6334 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6335 ** (c) the file system is read-only, then enable no-locking access.
6336 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6337 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6338 */
6339 struct statfs fsInfo;
6340 struct stat conchInfo;
6341 int goLockless = 0;
6342
drh99ab3b12011-03-02 15:09:07 +00006343 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006344 int err = errno;
6345 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6346 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6347 }
6348 }
6349 if( goLockless ){
6350 pCtx->conchHeld = -1; /* read only FS/ lockless */
6351 rc = SQLITE_OK;
6352 }
6353 }
drh715ff302008-12-03 22:32:44 +00006354 }
6355 if( rc==SQLITE_OK && lockPath ){
6356 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6357 }
6358
6359 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006360 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6361 if( pCtx->dbPath==NULL ){
6362 rc = SQLITE_NOMEM;
6363 }
6364 }
6365 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006366 /* all memory is allocated, proxys are created and assigned,
6367 ** switch the locking context and pMethod then return.
6368 */
drh715ff302008-12-03 22:32:44 +00006369 pCtx->oldLockingContext = pFile->lockingContext;
6370 pFile->lockingContext = pCtx;
6371 pCtx->pOldMethod = pFile->pMethod;
6372 pFile->pMethod = &proxyIoMethods;
6373 }else{
6374 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006375 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006376 sqlite3_free(pCtx->conchFile);
6377 }
drhd56b1212010-08-11 06:14:15 +00006378 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006379 sqlite3_free(pCtx->conchFilePath);
6380 sqlite3_free(pCtx);
6381 }
drh308c2a52010-05-14 11:30:18 +00006382 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6383 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006384 return rc;
6385}
6386
6387
6388/*
6389** This routine handles sqlite3_file_control() calls that are specific
6390** to proxy locking.
6391*/
6392static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6393 switch( op ){
6394 case SQLITE_GET_LOCKPROXYFILE: {
6395 unixFile *pFile = (unixFile*)id;
6396 if( pFile->pMethod == &proxyIoMethods ){
6397 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6398 proxyTakeConch(pFile);
6399 if( pCtx->lockProxyPath ){
6400 *(const char **)pArg = pCtx->lockProxyPath;
6401 }else{
6402 *(const char **)pArg = ":auto: (not held)";
6403 }
6404 } else {
6405 *(const char **)pArg = NULL;
6406 }
6407 return SQLITE_OK;
6408 }
6409 case SQLITE_SET_LOCKPROXYFILE: {
6410 unixFile *pFile = (unixFile*)id;
6411 int rc = SQLITE_OK;
6412 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6413 if( pArg==NULL || (const char *)pArg==0 ){
6414 if( isProxyStyle ){
6415 /* turn off proxy locking - not supported */
6416 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6417 }else{
6418 /* turn off proxy locking - already off - NOOP */
6419 rc = SQLITE_OK;
6420 }
6421 }else{
6422 const char *proxyPath = (const char *)pArg;
6423 if( isProxyStyle ){
6424 proxyLockingContext *pCtx =
6425 (proxyLockingContext*)pFile->lockingContext;
6426 if( !strcmp(pArg, ":auto:")
6427 || (pCtx->lockProxyPath &&
6428 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6429 ){
6430 rc = SQLITE_OK;
6431 }else{
6432 rc = switchLockProxyPath(pFile, proxyPath);
6433 }
6434 }else{
6435 /* turn on proxy file locking */
6436 rc = proxyTransformUnixFile(pFile, proxyPath);
6437 }
6438 }
6439 return rc;
6440 }
6441 default: {
6442 assert( 0 ); /* The call assures that only valid opcodes are sent */
6443 }
6444 }
6445 /*NOTREACHED*/
6446 return SQLITE_ERROR;
6447}
6448
6449/*
6450** Within this division (the proxying locking implementation) the procedures
6451** above this point are all utilities. The lock-related methods of the
6452** proxy-locking sqlite3_io_method object follow.
6453*/
6454
6455
6456/*
6457** This routine checks if there is a RESERVED lock held on the specified
6458** file by this or any other process. If such a lock is held, set *pResOut
6459** to a non-zero value otherwise *pResOut is set to zero. The return value
6460** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6461*/
6462static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6463 unixFile *pFile = (unixFile*)id;
6464 int rc = proxyTakeConch(pFile);
6465 if( rc==SQLITE_OK ){
6466 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006467 if( pCtx->conchHeld>0 ){
6468 unixFile *proxy = pCtx->lockProxy;
6469 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6470 }else{ /* conchHeld < 0 is lockless */
6471 pResOut=0;
6472 }
drh715ff302008-12-03 22:32:44 +00006473 }
6474 return rc;
6475}
6476
6477/*
drh308c2a52010-05-14 11:30:18 +00006478** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006479** of the following:
6480**
6481** (1) SHARED_LOCK
6482** (2) RESERVED_LOCK
6483** (3) PENDING_LOCK
6484** (4) EXCLUSIVE_LOCK
6485**
6486** Sometimes when requesting one lock state, additional lock states
6487** are inserted in between. The locking might fail on one of the later
6488** transitions leaving the lock state different from what it started but
6489** still short of its goal. The following chart shows the allowed
6490** transitions and the inserted intermediate states:
6491**
6492** UNLOCKED -> SHARED
6493** SHARED -> RESERVED
6494** SHARED -> (PENDING) -> EXCLUSIVE
6495** RESERVED -> (PENDING) -> EXCLUSIVE
6496** PENDING -> EXCLUSIVE
6497**
6498** This routine will only increase a lock. Use the sqlite3OsUnlock()
6499** routine to lower a locking level.
6500*/
drh308c2a52010-05-14 11:30:18 +00006501static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006502 unixFile *pFile = (unixFile*)id;
6503 int rc = proxyTakeConch(pFile);
6504 if( rc==SQLITE_OK ){
6505 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006506 if( pCtx->conchHeld>0 ){
6507 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006508 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6509 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006510 }else{
6511 /* conchHeld < 0 is lockless */
6512 }
drh715ff302008-12-03 22:32:44 +00006513 }
6514 return rc;
6515}
6516
6517
6518/*
drh308c2a52010-05-14 11:30:18 +00006519** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006520** must be either NO_LOCK or SHARED_LOCK.
6521**
6522** If the locking level of the file descriptor is already at or below
6523** the requested locking level, this routine is a no-op.
6524*/
drh308c2a52010-05-14 11:30:18 +00006525static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006526 unixFile *pFile = (unixFile*)id;
6527 int rc = proxyTakeConch(pFile);
6528 if( rc==SQLITE_OK ){
6529 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006530 if( pCtx->conchHeld>0 ){
6531 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006532 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6533 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006534 }else{
6535 /* conchHeld < 0 is lockless */
6536 }
drh715ff302008-12-03 22:32:44 +00006537 }
6538 return rc;
6539}
6540
6541/*
6542** Close a file that uses proxy locks.
6543*/
6544static int proxyClose(sqlite3_file *id) {
6545 if( id ){
6546 unixFile *pFile = (unixFile*)id;
6547 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6548 unixFile *lockProxy = pCtx->lockProxy;
6549 unixFile *conchFile = pCtx->conchFile;
6550 int rc = SQLITE_OK;
6551
6552 if( lockProxy ){
6553 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6554 if( rc ) return rc;
6555 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6556 if( rc ) return rc;
6557 sqlite3_free(lockProxy);
6558 pCtx->lockProxy = 0;
6559 }
6560 if( conchFile ){
6561 if( pCtx->conchHeld ){
6562 rc = proxyReleaseConch(pFile);
6563 if( rc ) return rc;
6564 }
6565 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6566 if( rc ) return rc;
6567 sqlite3_free(conchFile);
6568 }
drhd56b1212010-08-11 06:14:15 +00006569 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006570 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006571 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006572 /* restore the original locking context and pMethod then close it */
6573 pFile->lockingContext = pCtx->oldLockingContext;
6574 pFile->pMethod = pCtx->pOldMethod;
6575 sqlite3_free(pCtx);
6576 return pFile->pMethod->xClose(id);
6577 }
6578 return SQLITE_OK;
6579}
6580
6581
6582
drhd2cb50b2009-01-09 21:41:17 +00006583#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006584/*
6585** The proxy locking style is intended for use with AFP filesystems.
6586** And since AFP is only supported on MacOSX, the proxy locking is also
6587** restricted to MacOSX.
6588**
6589**
6590******************* End of the proxy lock implementation **********************
6591******************************************************************************/
6592
drh734c9862008-11-28 15:37:20 +00006593/*
danielk1977e339d652008-06-28 11:23:00 +00006594** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006595**
6596** This routine registers all VFS implementations for unix-like operating
6597** systems. This routine, and the sqlite3_os_end() routine that follows,
6598** should be the only routines in this file that are visible from other
6599** files.
drh6b9d6dd2008-12-03 19:34:47 +00006600**
6601** This routine is called once during SQLite initialization and by a
6602** single thread. The memory allocation and mutex subsystems have not
6603** necessarily been initialized when this routine is called, and so they
6604** should not be used.
drh153c62c2007-08-24 03:51:33 +00006605*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006606int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006607 /*
6608 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006609 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6610 ** to the "finder" function. (pAppData is a pointer to a pointer because
6611 ** silly C90 rules prohibit a void* from being cast to a function pointer
6612 ** and so we have to go through the intermediate pointer to avoid problems
6613 ** when compiling with -pedantic-errors on GCC.)
6614 **
6615 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006616 ** finder-function. The finder-function returns a pointer to the
6617 ** sqlite_io_methods object that implements the desired locking
6618 ** behaviors. See the division above that contains the IOMETHODS
6619 ** macro for addition information on finder-functions.
6620 **
6621 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6622 ** object. But the "autolockIoFinder" available on MacOSX does a little
6623 ** more than that; it looks at the filesystem type that hosts the
6624 ** database file and tries to choose an locking method appropriate for
6625 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006626 */
drh7708e972008-11-29 00:56:52 +00006627 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006628 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006629 sizeof(unixFile), /* szOsFile */ \
6630 MAX_PATHNAME, /* mxPathname */ \
6631 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006632 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006633 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006634 unixOpen, /* xOpen */ \
6635 unixDelete, /* xDelete */ \
6636 unixAccess, /* xAccess */ \
6637 unixFullPathname, /* xFullPathname */ \
6638 unixDlOpen, /* xDlOpen */ \
6639 unixDlError, /* xDlError */ \
6640 unixDlSym, /* xDlSym */ \
6641 unixDlClose, /* xDlClose */ \
6642 unixRandomness, /* xRandomness */ \
6643 unixSleep, /* xSleep */ \
6644 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006645 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006646 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006647 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006648 unixGetSystemCall, /* xGetSystemCall */ \
6649 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006650 }
6651
drh6b9d6dd2008-12-03 19:34:47 +00006652 /*
6653 ** All default VFSes for unix are contained in the following array.
6654 **
6655 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6656 ** by the SQLite core when the VFS is registered. So the following
6657 ** array cannot be const.
6658 */
danielk1977e339d652008-06-28 11:23:00 +00006659 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006660#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006661 UNIXVFS("unix", autolockIoFinder ),
6662#else
6663 UNIXVFS("unix", posixIoFinder ),
6664#endif
6665 UNIXVFS("unix-none", nolockIoFinder ),
6666 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006667 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006668#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006669 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006670#endif
6671#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006672 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006673#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006674 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006675#endif
chw78a13182009-04-07 05:35:03 +00006676#endif
drhd2cb50b2009-01-09 21:41:17 +00006677#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006678 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006679 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006680 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006681#endif
drh153c62c2007-08-24 03:51:33 +00006682 };
drh6b9d6dd2008-12-03 19:34:47 +00006683 unsigned int i; /* Loop counter */
6684
6685 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006686 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006687 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006688 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006689 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006690}
danielk1977e339d652008-06-28 11:23:00 +00006691
6692/*
drh6b9d6dd2008-12-03 19:34:47 +00006693** Shutdown the operating system interface.
6694**
6695** Some operating systems might need to do some cleanup in this routine,
6696** to release dynamically allocated objects. But not on unix.
6697** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006698*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006699int sqlite3_os_end(void){
6700 return SQLITE_OK;
6701}
drhdce8bdb2007-08-16 13:01:44 +00006702
danielk197729bafea2008-06-26 10:41:19 +00006703#endif /* SQLITE_OS_UNIX */