blob: f4e689fa9f58f8d959b5d6df33c4dd8daea9bc31 [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
374#define osFallocate ((int(*)(int,off_t,off_t)aSyscall[15].pCurrent)
375
376}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000377
378/*
379** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000380** "unix" VFSes. Return SQLITE_OK opon successfully updating the
381** system call pointer, or SQLITE_NOTFOUND if there is no configurable
382** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000383*/
384static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000385 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
386 const char *zName, /* Name of system call to override */
387 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000388){
drh58ad5802011-03-23 22:02:23 +0000389 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000390 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000391
392 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000393 if( zName==0 ){
394 /* If no zName is given, restore all system calls to their default
395 ** settings and return NULL
396 */
397 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
398 if( aSyscall[i].pDefault ){
399 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh1df30962011-03-02 19:06:42 +0000400 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000401 }
402 }
403 }else{
404 /* If zName is specified, operate on only the one system call
405 ** specified.
406 */
407 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
408 if( strcmp(zName, aSyscall[i].zName)==0 ){
409 if( aSyscall[i].pDefault==0 ){
410 aSyscall[i].pDefault = aSyscall[i].pCurrent;
411 }
drh1df30962011-03-02 19:06:42 +0000412 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000413 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
414 aSyscall[i].pCurrent = pNewFunc;
415 break;
416 }
417 }
418 }
419 return rc;
420}
421
drh1df30962011-03-02 19:06:42 +0000422/*
423** Return the value of a system call. Return NULL if zName is not a
424** recognized system call name. NULL is also returned if the system call
425** is currently undefined.
426*/
drh58ad5802011-03-23 22:02:23 +0000427static sqlite3_syscall_ptr unixGetSystemCall(
428 sqlite3_vfs *pNotUsed,
429 const char *zName
430){
431 unsigned int i;
432
433 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000434 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
435 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
436 }
437 return 0;
438}
439
440/*
441** Return the name of the first system call after zName. If zName==NULL
442** then return the name of the first system call. Return NULL if zName
443** is the last system call or if zName is not the name of a valid
444** system call.
445*/
446static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
drh58ad5802011-03-23 22:02:23 +0000447 unsigned int i;
448
449 UNUSED_PARAMETER(p);
drh1df30962011-03-02 19:06:42 +0000450 if( zName==0 ){
451 i = -1;
452 }else{
453 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0])-1; i++){
454 if( strcmp(zName, aSyscall[0].zName)==0 ) break;
455 }
456 }
457 for(i++; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
458 if( aSyscall[0].pCurrent!=0 ) return aSyscall[0].zName;
459 }
460 return 0;
461}
462
drhad4f1e52011-03-04 15:43:57 +0000463/*
464** Retry open() calls that fail due to EINTR
465*/
466static int robust_open(const char *z, int f, int m){
467 int rc;
468 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
469 return rc;
470}
danielk197713adf8a2004-06-03 16:08:41 +0000471
drh107886a2008-11-21 22:21:50 +0000472/*
dan9359c7b2009-08-21 08:29:10 +0000473** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000474** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000475** vxworksFileId objects used by this file, all of which may be
476** shared by multiple threads.
477**
478** Function unixMutexHeld() is used to assert() that the global mutex
479** is held when required. This function is only used as part of assert()
480** statements. e.g.
481**
482** unixEnterMutex()
483** assert( unixMutexHeld() );
484** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000485*/
486static void unixEnterMutex(void){
487 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
488}
489static void unixLeaveMutex(void){
490 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
491}
dan9359c7b2009-08-21 08:29:10 +0000492#ifdef SQLITE_DEBUG
493static int unixMutexHeld(void) {
494 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
495}
496#endif
drh107886a2008-11-21 22:21:50 +0000497
drh734c9862008-11-28 15:37:20 +0000498
499#ifdef SQLITE_DEBUG
500/*
501** Helper function for printing out trace information from debugging
502** binaries. This returns the string represetation of the supplied
503** integer lock-type.
504*/
drh308c2a52010-05-14 11:30:18 +0000505static const char *azFileLock(int eFileLock){
506 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000507 case NO_LOCK: return "NONE";
508 case SHARED_LOCK: return "SHARED";
509 case RESERVED_LOCK: return "RESERVED";
510 case PENDING_LOCK: return "PENDING";
511 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000512 }
513 return "ERROR";
514}
515#endif
516
517#ifdef SQLITE_LOCK_TRACE
518/*
519** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000520**
drh734c9862008-11-28 15:37:20 +0000521** This routine is used for troubleshooting locks on multithreaded
522** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
523** command-line option on the compiler. This code is normally
524** turned off.
525*/
526static int lockTrace(int fd, int op, struct flock *p){
527 char *zOpName, *zType;
528 int s;
529 int savedErrno;
530 if( op==F_GETLK ){
531 zOpName = "GETLK";
532 }else if( op==F_SETLK ){
533 zOpName = "SETLK";
534 }else{
drh99ab3b12011-03-02 15:09:07 +0000535 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000536 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
537 return s;
538 }
539 if( p->l_type==F_RDLCK ){
540 zType = "RDLCK";
541 }else if( p->l_type==F_WRLCK ){
542 zType = "WRLCK";
543 }else if( p->l_type==F_UNLCK ){
544 zType = "UNLCK";
545 }else{
546 assert( 0 );
547 }
548 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000549 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000550 savedErrno = errno;
551 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
552 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
553 (int)p->l_pid, s);
554 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
555 struct flock l2;
556 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000557 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000558 if( l2.l_type==F_RDLCK ){
559 zType = "RDLCK";
560 }else if( l2.l_type==F_WRLCK ){
561 zType = "WRLCK";
562 }else if( l2.l_type==F_UNLCK ){
563 zType = "UNLCK";
564 }else{
565 assert( 0 );
566 }
567 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
568 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
569 }
570 errno = savedErrno;
571 return s;
572}
drh99ab3b12011-03-02 15:09:07 +0000573#undef osFcntl
574#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000575#endif /* SQLITE_LOCK_TRACE */
576
drhff812312011-02-23 13:33:46 +0000577/*
578** Retry ftruncate() calls that fail due to EINTR
579*/
drhff812312011-02-23 13:33:46 +0000580static int robust_ftruncate(int h, sqlite3_int64 sz){
581 int rc;
drh99ab3b12011-03-02 15:09:07 +0000582 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000583 return rc;
584}
drh734c9862008-11-28 15:37:20 +0000585
586/*
587** This routine translates a standard POSIX errno code into something
588** useful to the clients of the sqlite3 functions. Specifically, it is
589** intended to translate a variety of "try again" errors into SQLITE_BUSY
590** and a variety of "please close the file descriptor NOW" errors into
591** SQLITE_IOERR
592**
593** Errors during initialization of locks, or file system support for locks,
594** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
595*/
596static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
597 switch (posixError) {
598 case 0:
599 return SQLITE_OK;
600
601 case EAGAIN:
602 case ETIMEDOUT:
603 case EBUSY:
604 case EINTR:
605 case ENOLCK:
606 /* random NFS retry error, unless during file system support
607 * introspection, in which it actually means what it says */
608 return SQLITE_BUSY;
609
610 case EACCES:
611 /* EACCES is like EAGAIN during locking operations, but not any other time*/
612 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
613 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
614 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
615 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
616 return SQLITE_BUSY;
617 }
618 /* else fall through */
619 case EPERM:
620 return SQLITE_PERM;
621
622 case EDEADLK:
623 return SQLITE_IOERR_BLOCKED;
624
625#if EOPNOTSUPP!=ENOTSUP
626 case EOPNOTSUPP:
627 /* something went terribly awry, unless during file system support
628 * introspection, in which it actually means what it says */
629#endif
630#ifdef ENOTSUP
631 case ENOTSUP:
632 /* invalid fd, unless during file system support introspection, in which
633 * it actually means what it says */
634#endif
635 case EIO:
636 case EBADF:
637 case EINVAL:
638 case ENOTCONN:
639 case ENODEV:
640 case ENXIO:
641 case ENOENT:
642 case ESTALE:
643 case ENOSYS:
644 /* these should force the client to close the file and reconnect */
645
646 default:
647 return sqliteIOErr;
648 }
649}
650
651
652
653/******************************************************************************
654****************** Begin Unique File ID Utility Used By VxWorks ***************
655**
656** On most versions of unix, we can get a unique ID for a file by concatenating
657** the device number and the inode number. But this does not work on VxWorks.
658** On VxWorks, a unique file id must be based on the canonical filename.
659**
660** A pointer to an instance of the following structure can be used as a
661** unique file ID in VxWorks. Each instance of this structure contains
662** a copy of the canonical filename. There is also a reference count.
663** The structure is reclaimed when the number of pointers to it drops to
664** zero.
665**
666** There are never very many files open at one time and lookups are not
667** a performance-critical path, so it is sufficient to put these
668** structures on a linked list.
669*/
670struct vxworksFileId {
671 struct vxworksFileId *pNext; /* Next in a list of them all */
672 int nRef; /* Number of references to this one */
673 int nName; /* Length of the zCanonicalName[] string */
674 char *zCanonicalName; /* Canonical filename */
675};
676
677#if OS_VXWORKS
678/*
drh9b35ea62008-11-29 02:20:26 +0000679** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000680** variable:
681*/
682static struct vxworksFileId *vxworksFileList = 0;
683
684/*
685** Simplify a filename into its canonical form
686** by making the following changes:
687**
688** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000689** * convert /./ into just /
690** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000691**
692** Changes are made in-place. Return the new name length.
693**
694** The original filename is in z[0..n-1]. Return the number of
695** characters in the simplified name.
696*/
697static int vxworksSimplifyName(char *z, int n){
698 int i, j;
699 while( n>1 && z[n-1]=='/' ){ n--; }
700 for(i=j=0; i<n; i++){
701 if( z[i]=='/' ){
702 if( z[i+1]=='/' ) continue;
703 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
704 i += 1;
705 continue;
706 }
707 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
708 while( j>0 && z[j-1]!='/' ){ j--; }
709 if( j>0 ){ j--; }
710 i += 2;
711 continue;
712 }
713 }
714 z[j++] = z[i];
715 }
716 z[j] = 0;
717 return j;
718}
719
720/*
721** Find a unique file ID for the given absolute pathname. Return
722** a pointer to the vxworksFileId object. This pointer is the unique
723** file ID.
724**
725** The nRef field of the vxworksFileId object is incremented before
726** the object is returned. A new vxworksFileId object is created
727** and added to the global list if necessary.
728**
729** If a memory allocation error occurs, return NULL.
730*/
731static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
732 struct vxworksFileId *pNew; /* search key and new file ID */
733 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
734 int n; /* Length of zAbsoluteName string */
735
736 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000737 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000738 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
739 if( pNew==0 ) return 0;
740 pNew->zCanonicalName = (char*)&pNew[1];
741 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
742 n = vxworksSimplifyName(pNew->zCanonicalName, n);
743
744 /* Search for an existing entry that matching the canonical name.
745 ** If found, increment the reference count and return a pointer to
746 ** the existing file ID.
747 */
748 unixEnterMutex();
749 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
750 if( pCandidate->nName==n
751 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
752 ){
753 sqlite3_free(pNew);
754 pCandidate->nRef++;
755 unixLeaveMutex();
756 return pCandidate;
757 }
758 }
759
760 /* No match was found. We will make a new file ID */
761 pNew->nRef = 1;
762 pNew->nName = n;
763 pNew->pNext = vxworksFileList;
764 vxworksFileList = pNew;
765 unixLeaveMutex();
766 return pNew;
767}
768
769/*
770** Decrement the reference count on a vxworksFileId object. Free
771** the object when the reference count reaches zero.
772*/
773static void vxworksReleaseFileId(struct vxworksFileId *pId){
774 unixEnterMutex();
775 assert( pId->nRef>0 );
776 pId->nRef--;
777 if( pId->nRef==0 ){
778 struct vxworksFileId **pp;
779 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
780 assert( *pp==pId );
781 *pp = pId->pNext;
782 sqlite3_free(pId);
783 }
784 unixLeaveMutex();
785}
786#endif /* OS_VXWORKS */
787/*************** End of Unique File ID Utility Used By VxWorks ****************
788******************************************************************************/
789
790
791/******************************************************************************
792*************************** Posix Advisory Locking ****************************
793**
drh9b35ea62008-11-29 02:20:26 +0000794** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000795** section 6.5.2.2 lines 483 through 490 specify that when a process
796** sets or clears a lock, that operation overrides any prior locks set
797** by the same process. It does not explicitly say so, but this implies
798** that it overrides locks set by the same process using a different
799** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000800**
801** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000802** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
803**
804** Suppose ./file1 and ./file2 are really the same file (because
805** one is a hard or symbolic link to the other) then if you set
806** an exclusive lock on fd1, then try to get an exclusive lock
807** on fd2, it works. I would have expected the second lock to
808** fail since there was already a lock on the file due to fd1.
809** But not so. Since both locks came from the same process, the
810** second overrides the first, even though they were on different
811** file descriptors opened on different file names.
812**
drh734c9862008-11-28 15:37:20 +0000813** This means that we cannot use POSIX locks to synchronize file access
814** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000815** to synchronize access for threads in separate processes, but not
816** threads within the same process.
817**
818** To work around the problem, SQLite has to manage file locks internally
819** on its own. Whenever a new database is opened, we have to find the
820** specific inode of the database file (the inode is determined by the
821** st_dev and st_ino fields of the stat structure that fstat() fills in)
822** and check for locks already existing on that inode. When locks are
823** created or removed, we have to look at our own internal record of the
824** locks to see if another thread has previously set a lock on that same
825** inode.
826**
drh9b35ea62008-11-29 02:20:26 +0000827** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
828** For VxWorks, we have to use the alternative unique ID system based on
829** canonical filename and implemented in the previous division.)
830**
danielk1977ad94b582007-08-20 06:44:22 +0000831** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000832** descriptor. It is now a structure that holds the integer file
833** descriptor and a pointer to a structure that describes the internal
834** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000835** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000836** point to the same locking structure. The locking structure keeps
837** a reference count (so we will know when to delete it) and a "cnt"
838** field that tells us its internal lock status. cnt==0 means the
839** file is unlocked. cnt==-1 means the file has an exclusive lock.
840** cnt>0 means there are cnt shared locks on the file.
841**
842** Any attempt to lock or unlock a file first checks the locking
843** structure. The fcntl() system call is only invoked to set a
844** POSIX lock if the internal lock structure transitions between
845** a locked and an unlocked state.
846**
drh734c9862008-11-28 15:37:20 +0000847** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000848**
849** If you close a file descriptor that points to a file that has locks,
850** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000851** released. To work around this problem, each unixInodeInfo object
852** maintains a count of the number of pending locks on tha inode.
853** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000854** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000855** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000856** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000857** be closed and that list is walked (and cleared) when the last lock
858** clears.
859**
drh9b35ea62008-11-29 02:20:26 +0000860** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000861**
drh9b35ea62008-11-29 02:20:26 +0000862** Many older versions of linux use the LinuxThreads library which is
863** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000864** A cannot be modified or overridden by a different thread B.
865** Only thread A can modify the lock. Locking behavior is correct
866** if the appliation uses the newer Native Posix Thread Library (NPTL)
867** on linux - with NPTL a lock created by thread A can override locks
868** in thread B. But there is no way to know at compile-time which
869** threading library is being used. So there is no way to know at
870** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000871** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000872** current process.
drh5fdae772004-06-29 03:29:00 +0000873**
drh8af6c222010-05-14 12:43:01 +0000874** SQLite used to support LinuxThreads. But support for LinuxThreads
875** was dropped beginning with version 3.7.0. SQLite will still work with
876** LinuxThreads provided that (1) there is no more than one connection
877** per database file in the same process and (2) database connections
878** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000879*/
880
881/*
882** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000883** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000884*/
885struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000886 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000887#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000888 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000889#else
drh107886a2008-11-21 22:21:50 +0000890 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000891#endif
892};
893
894/*
drhbbd42a62004-05-22 17:41:58 +0000895** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000896** inode. Or, on LinuxThreads, there is one of these structures for
897** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000898**
danielk1977ad94b582007-08-20 06:44:22 +0000899** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000900** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000901** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000902*/
drh8af6c222010-05-14 12:43:01 +0000903struct unixInodeInfo {
904 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000905 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000906 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
907 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000908 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000909 unixShmNode *pShmNode; /* Shared memory associated with this inode */
910 int nLock; /* Number of outstanding file locks */
911 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
912 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
913 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000914#if defined(SQLITE_ENABLE_LOCKING_STYLE)
915 unsigned long long sharedByte; /* for AFP simulated shared lock */
916#endif
drh6c7d5c52008-11-21 20:32:33 +0000917#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000918 sem_t *pSem; /* Named POSIX semaphore */
919 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000920#endif
drhbbd42a62004-05-22 17:41:58 +0000921};
922
drhda0e7682008-07-30 15:27:54 +0000923/*
drh8af6c222010-05-14 12:43:01 +0000924** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000925*/
drhd91c68f2010-05-14 14:52:25 +0000926static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000927
drh5fdae772004-06-29 03:29:00 +0000928/*
dane18d4952011-02-21 11:46:24 +0000929**
930** This function - unixLogError_x(), is only ever called via the macro
931** unixLogError().
932**
933** It is invoked after an error occurs in an OS function and errno has been
934** set. It logs a message using sqlite3_log() containing the current value of
935** errno and, if possible, the human-readable equivalent from strerror() or
936** strerror_r().
937**
938** The first argument passed to the macro should be the error code that
939** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
940** The two subsequent arguments should be the name of the OS function that
941** failed (e.g. "unlink", "open") and the the associated file-system path,
942** if any.
943*/
drh0e9365c2011-03-02 02:08:13 +0000944#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
945static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000946 int errcode, /* SQLite error code */
947 const char *zFunc, /* Name of OS function that failed */
948 const char *zPath, /* File path associated with error */
949 int iLine /* Source line number where error occurred */
950){
951 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000952 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000953
954 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
955 ** the strerror() function to obtain the human-readable error message
956 ** equivalent to errno. Otherwise, use strerror_r().
957 */
958#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
959 char aErr[80];
960 memset(aErr, 0, sizeof(aErr));
961 zErr = aErr;
962
963 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
964 ** assume that the system provides the the GNU version of strerror_r() that
965 ** returns a pointer to a buffer containing the error message. That pointer
966 ** may point to aErr[], or it may point to some static storage somewhere.
967 ** Otherwise, assume that the system provides the POSIX version of
968 ** strerror_r(), which always writes an error message into aErr[].
969 **
970 ** If the code incorrectly assumes that it is the POSIX version that is
971 ** available, the error message will often be an empty string. Not a
972 ** huge problem. Incorrectly concluding that the GNU version is available
973 ** could lead to a segfault though.
974 */
975#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
976 zErr =
977# endif
drh0e9365c2011-03-02 02:08:13 +0000978 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000979
980#elif SQLITE_THREADSAFE
981 /* This is a threadsafe build, but strerror_r() is not available. */
982 zErr = "";
983#else
984 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000985 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000986#endif
987
988 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000989 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000990 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000991 "os_unix.c:%d: (%d) %s(%s) - %s",
992 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000993 );
994
995 return errcode;
996}
997
drh0e9365c2011-03-02 02:08:13 +0000998/*
999** Close a file descriptor.
1000**
1001** We assume that close() almost always works, since it is only in a
1002** very sick application or on a very sick platform that it might fail.
1003** If it does fail, simply leak the file descriptor, but do log the
1004** error.
1005**
1006** Note that it is not safe to retry close() after EINTR since the
1007** file descriptor might have already been reused by another thread.
1008** So we don't even try to recover from an EINTR. Just log the error
1009** and move on.
1010*/
1011static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001012 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001013 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1014 pFile ? pFile->zPath : 0, lineno);
1015 }
1016}
dane18d4952011-02-21 11:46:24 +00001017
1018/*
danb0ac3e32010-06-16 10:55:42 +00001019** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001020*/
drh0e9365c2011-03-02 02:08:13 +00001021static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001022 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001023 UnixUnusedFd *p;
1024 UnixUnusedFd *pNext;
1025 for(p=pInode->pUnused; p; p=pNext){
1026 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001027 robust_close(pFile, p->fd, __LINE__);
1028 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001029 }
drh0e9365c2011-03-02 02:08:13 +00001030 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001031}
1032
1033/*
drh8af6c222010-05-14 12:43:01 +00001034** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001035**
1036** The mutex entered using the unixEnterMutex() function must be held
1037** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001038*/
danb0ac3e32010-06-16 10:55:42 +00001039static void releaseInodeInfo(unixFile *pFile){
1040 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001041 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001042 if( pInode ){
1043 pInode->nRef--;
1044 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001045 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001046 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001047 if( pInode->pPrev ){
1048 assert( pInode->pPrev->pNext==pInode );
1049 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001050 }else{
drh8af6c222010-05-14 12:43:01 +00001051 assert( inodeList==pInode );
1052 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001053 }
drh8af6c222010-05-14 12:43:01 +00001054 if( pInode->pNext ){
1055 assert( pInode->pNext->pPrev==pInode );
1056 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001057 }
drh8af6c222010-05-14 12:43:01 +00001058 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001059 }
drhbbd42a62004-05-22 17:41:58 +00001060 }
1061}
1062
1063/*
drh8af6c222010-05-14 12:43:01 +00001064** Given a file descriptor, locate the unixInodeInfo object that
1065** describes that file descriptor. Create a new one if necessary. The
1066** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001067**
dan9359c7b2009-08-21 08:29:10 +00001068** The mutex entered using the unixEnterMutex() function must be held
1069** when this function is called.
1070**
drh6c7d5c52008-11-21 20:32:33 +00001071** Return an appropriate error code.
1072*/
drh8af6c222010-05-14 12:43:01 +00001073static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001074 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001075 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001076){
1077 int rc; /* System call return code */
1078 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001079 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1080 struct stat statbuf; /* Low-level file information */
1081 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001082
dan9359c7b2009-08-21 08:29:10 +00001083 assert( unixMutexHeld() );
1084
drh6c7d5c52008-11-21 20:32:33 +00001085 /* Get low-level information about the file that we can used to
1086 ** create a unique name for the file.
1087 */
1088 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001089 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001090 if( rc!=0 ){
1091 pFile->lastErrno = errno;
1092#ifdef EOVERFLOW
1093 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1094#endif
1095 return SQLITE_IOERR;
1096 }
1097
drheb0d74f2009-02-03 15:27:02 +00001098#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001099 /* On OS X on an msdos filesystem, the inode number is reported
1100 ** incorrectly for zero-size files. See ticket #3260. To work
1101 ** around this problem (we consider it a bug in OS X, not SQLite)
1102 ** we always increase the file size to 1 by writing a single byte
1103 ** prior to accessing the inode number. The one byte written is
1104 ** an ASCII 'S' character which also happens to be the first byte
1105 ** in the header of every SQLite database. In this way, if there
1106 ** is a race condition such that another thread has already populated
1107 ** the first page of the database, no damage is done.
1108 */
drh7ed97b92010-01-20 13:07:21 +00001109 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001110 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001111 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001112 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001113 return SQLITE_IOERR;
1114 }
drh99ab3b12011-03-02 15:09:07 +00001115 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001116 if( rc!=0 ){
1117 pFile->lastErrno = errno;
1118 return SQLITE_IOERR;
1119 }
1120 }
drheb0d74f2009-02-03 15:27:02 +00001121#endif
drh6c7d5c52008-11-21 20:32:33 +00001122
drh8af6c222010-05-14 12:43:01 +00001123 memset(&fileId, 0, sizeof(fileId));
1124 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001125#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001126 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001127#else
drh8af6c222010-05-14 12:43:01 +00001128 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001129#endif
drh8af6c222010-05-14 12:43:01 +00001130 pInode = inodeList;
1131 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1132 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001133 }
drh8af6c222010-05-14 12:43:01 +00001134 if( pInode==0 ){
1135 pInode = sqlite3_malloc( sizeof(*pInode) );
1136 if( pInode==0 ){
1137 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001138 }
drh8af6c222010-05-14 12:43:01 +00001139 memset(pInode, 0, sizeof(*pInode));
1140 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1141 pInode->nRef = 1;
1142 pInode->pNext = inodeList;
1143 pInode->pPrev = 0;
1144 if( inodeList ) inodeList->pPrev = pInode;
1145 inodeList = pInode;
1146 }else{
1147 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001148 }
drh8af6c222010-05-14 12:43:01 +00001149 *ppInode = pInode;
1150 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001151}
drh6c7d5c52008-11-21 20:32:33 +00001152
aswift5b1a2562008-08-22 00:22:35 +00001153
1154/*
danielk197713adf8a2004-06-03 16:08:41 +00001155** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001156** file by this or any other process. If such a lock is held, set *pResOut
1157** to a non-zero value otherwise *pResOut is set to zero. The return value
1158** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001159*/
danielk1977861f7452008-06-05 11:39:11 +00001160static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001161 int rc = SQLITE_OK;
1162 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001163 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001164
danielk1977861f7452008-06-05 11:39:11 +00001165 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1166
drh054889e2005-11-30 03:20:31 +00001167 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001168 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001169
1170 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001171 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001172 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001173 }
1174
drh2ac3ee92004-06-07 16:27:46 +00001175 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001176 */
danielk197709480a92009-02-09 05:32:32 +00001177#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001178 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001179 struct flock lock;
1180 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001181 lock.l_start = RESERVED_BYTE;
1182 lock.l_len = 1;
1183 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001184 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001185 int tErrno = errno;
1186 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1187 pFile->lastErrno = tErrno;
1188 } else if( lock.l_type!=F_UNLCK ){
1189 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001190 }
1191 }
danielk197709480a92009-02-09 05:32:32 +00001192#endif
danielk197713adf8a2004-06-03 16:08:41 +00001193
drh6c7d5c52008-11-21 20:32:33 +00001194 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001195 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001196
aswift5b1a2562008-08-22 00:22:35 +00001197 *pResOut = reserved;
1198 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001199}
1200
1201/*
drha7e61d82011-03-12 17:02:57 +00001202** Attempt to set a system-lock on the file pFile. The lock is
1203** described by pLock.
1204**
drh77197112011-03-15 19:08:48 +00001205** If the pFile was opened read/write from unix-excl, then the only lock
1206** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001207** the first time any lock is attempted. All subsequent system locking
1208** operations become no-ops. Locking operations still happen internally,
1209** in order to coordinate access between separate database connections
1210** within this process, but all of that is handled in memory and the
1211** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001212**
1213** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1214** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1215** and is read-only.
drha7e61d82011-03-12 17:02:57 +00001216*/
1217static int unixFileLock(unixFile *pFile, struct flock *pLock){
1218 int rc;
drh3cb93392011-03-12 18:10:44 +00001219 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001220 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001221 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001222 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1223 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1224 ){
drh3cb93392011-03-12 18:10:44 +00001225 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001226 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001227 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001228 lock.l_whence = SEEK_SET;
1229 lock.l_start = SHARED_FIRST;
1230 lock.l_len = SHARED_SIZE;
1231 lock.l_type = F_WRLCK;
1232 rc = osFcntl(pFile->h, F_SETLK, &lock);
1233 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001234 pInode->bProcessLock = 1;
1235 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001236 }else{
1237 rc = 0;
1238 }
1239 }else{
1240 rc = osFcntl(pFile->h, F_SETLK, pLock);
1241 }
1242 return rc;
1243}
1244
1245/*
drh308c2a52010-05-14 11:30:18 +00001246** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001247** of the following:
1248**
drh2ac3ee92004-06-07 16:27:46 +00001249** (1) SHARED_LOCK
1250** (2) RESERVED_LOCK
1251** (3) PENDING_LOCK
1252** (4) EXCLUSIVE_LOCK
1253**
drhb3e04342004-06-08 00:47:47 +00001254** Sometimes when requesting one lock state, additional lock states
1255** are inserted in between. The locking might fail on one of the later
1256** transitions leaving the lock state different from what it started but
1257** still short of its goal. The following chart shows the allowed
1258** transitions and the inserted intermediate states:
1259**
1260** UNLOCKED -> SHARED
1261** SHARED -> RESERVED
1262** SHARED -> (PENDING) -> EXCLUSIVE
1263** RESERVED -> (PENDING) -> EXCLUSIVE
1264** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001265**
drha6abd042004-06-09 17:37:22 +00001266** This routine will only increase a lock. Use the sqlite3OsUnlock()
1267** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001268*/
drh308c2a52010-05-14 11:30:18 +00001269static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001270 /* The following describes the implementation of the various locks and
1271 ** lock transitions in terms of the POSIX advisory shared and exclusive
1272 ** lock primitives (called read-locks and write-locks below, to avoid
1273 ** confusion with SQLite lock names). The algorithms are complicated
1274 ** slightly in order to be compatible with windows systems simultaneously
1275 ** accessing the same database file, in case that is ever required.
1276 **
1277 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1278 ** byte', each single bytes at well known offsets, and the 'shared byte
1279 ** range', a range of 510 bytes at a well known offset.
1280 **
1281 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1282 ** byte'. If this is successful, a random byte from the 'shared byte
1283 ** range' is read-locked and the lock on the 'pending byte' released.
1284 **
danielk197790ba3bd2004-06-25 08:32:25 +00001285 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1286 ** A RESERVED lock is implemented by grabbing a write-lock on the
1287 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001288 **
1289 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001290 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1291 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1292 ** obtained, but existing SHARED locks are allowed to persist. A process
1293 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1294 ** This property is used by the algorithm for rolling back a journal file
1295 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001296 **
danielk197790ba3bd2004-06-25 08:32:25 +00001297 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1298 ** implemented by obtaining a write-lock on the entire 'shared byte
1299 ** range'. Since all other locks require a read-lock on one of the bytes
1300 ** within this range, this ensures that no other locks are held on the
1301 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001302 **
1303 ** The reason a single byte cannot be used instead of the 'shared byte
1304 ** range' is that some versions of windows do not support read-locks. By
1305 ** locking a random byte from a range, concurrent SHARED locks may exist
1306 ** even if the locking primitive used is always a write-lock.
1307 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001308 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001309 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001310 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001311 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001312 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001313 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001314
drh054889e2005-11-30 03:20:31 +00001315 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001316 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1317 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001318 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001319
1320 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001321 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001322 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 */
drh308c2a52010-05-14 11:30:18 +00001324 if( pFile->eFileLock>=eFileLock ){
1325 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1326 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001327 return SQLITE_OK;
1328 }
1329
drh0c2694b2009-09-03 16:23:44 +00001330 /* Make sure the locking sequence is correct.
1331 ** (1) We never move from unlocked to anything higher than shared lock.
1332 ** (2) SQLite never explicitly requests a pendig lock.
1333 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001334 */
drh308c2a52010-05-14 11:30:18 +00001335 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1336 assert( eFileLock!=PENDING_LOCK );
1337 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001338
drh8af6c222010-05-14 12:43:01 +00001339 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001340 */
drh6c7d5c52008-11-21 20:32:33 +00001341 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001342 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001343
danielk1977ad94b582007-08-20 06:44:22 +00001344 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001345 ** handle that precludes the requested lock, return BUSY.
1346 */
drh8af6c222010-05-14 12:43:01 +00001347 if( (pFile->eFileLock!=pInode->eFileLock &&
1348 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001349 ){
1350 rc = SQLITE_BUSY;
1351 goto end_lock;
1352 }
1353
1354 /* If a SHARED lock is requested, and some thread using this PID already
1355 ** has a SHARED or RESERVED lock, then increment reference counts and
1356 ** return SQLITE_OK.
1357 */
drh308c2a52010-05-14 11:30:18 +00001358 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001359 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001360 assert( eFileLock==SHARED_LOCK );
1361 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001362 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001363 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001364 pInode->nShared++;
1365 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001366 goto end_lock;
1367 }
1368
danielk19779a1d0ab2004-06-01 14:09:28 +00001369
drh3cde3bb2004-06-12 02:17:14 +00001370 /* A PENDING lock is needed before acquiring a SHARED lock and before
1371 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1372 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 */
drh0c2694b2009-09-03 16:23:44 +00001374 lock.l_len = 1L;
1375 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001376 if( eFileLock==SHARED_LOCK
1377 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001378 ){
drh308c2a52010-05-14 11:30:18 +00001379 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001380 lock.l_start = PENDING_BYTE;
drha7e61d82011-03-12 17:02:57 +00001381 s = unixFileLock(pFile, &lock);
drhe2396a12007-03-29 20:19:58 +00001382 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001383 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001384 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1385 if( IS_LOCK_ERROR(rc) ){
1386 pFile->lastErrno = tErrno;
1387 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 goto end_lock;
1389 }
drh3cde3bb2004-06-12 02:17:14 +00001390 }
1391
1392
1393 /* If control gets to this point, then actually go ahead and make
1394 ** operating system calls for the specified lock.
1395 */
drh308c2a52010-05-14 11:30:18 +00001396 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001397 assert( pInode->nShared==0 );
1398 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001399
drh2ac3ee92004-06-07 16:27:46 +00001400 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001401 lock.l_start = SHARED_FIRST;
1402 lock.l_len = SHARED_SIZE;
drha7e61d82011-03-12 17:02:57 +00001403 if( (s = unixFileLock(pFile, &lock))==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001404 tErrno = errno;
1405 }
drh2ac3ee92004-06-07 16:27:46 +00001406 /* Drop the temporary PENDING lock */
1407 lock.l_start = PENDING_BYTE;
1408 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001409 lock.l_type = F_UNLCK;
drha7e61d82011-03-12 17:02:57 +00001410 if( unixFileLock(pFile, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001411 if( s != -1 ){
1412 /* This could happen with a network mount */
1413 tErrno = errno;
1414 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1415 if( IS_LOCK_ERROR(rc) ){
1416 pFile->lastErrno = tErrno;
1417 }
1418 goto end_lock;
1419 }
drh2b4b5962005-06-15 17:47:55 +00001420 }
drhe2396a12007-03-29 20:19:58 +00001421 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001422 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1423 if( IS_LOCK_ERROR(rc) ){
1424 pFile->lastErrno = tErrno;
1425 }
drhbbd42a62004-05-22 17:41:58 +00001426 }else{
drh308c2a52010-05-14 11:30:18 +00001427 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001428 pInode->nLock++;
1429 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001430 }
drh8af6c222010-05-14 12:43:01 +00001431 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001432 /* We are trying for an exclusive lock but another thread in this
1433 ** same process is still holding a shared lock. */
1434 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001435 }else{
drh3cde3bb2004-06-12 02:17:14 +00001436 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001437 ** assumed that there is a SHARED or greater lock on the file
1438 ** already.
1439 */
drh308c2a52010-05-14 11:30:18 +00001440 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001441 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001442 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001443 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001444 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001445 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001446 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001447 lock.l_start = SHARED_FIRST;
1448 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001449 break;
1450 default:
1451 assert(0);
1452 }
drha7e61d82011-03-12 17:02:57 +00001453 s = unixFileLock(pFile, &lock);
drhe2396a12007-03-29 20:19:58 +00001454 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001455 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001456 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1457 if( IS_LOCK_ERROR(rc) ){
1458 pFile->lastErrno = tErrno;
1459 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001460 }
drhbbd42a62004-05-22 17:41:58 +00001461 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001462
drh8f941bc2009-01-14 23:03:40 +00001463
1464#ifndef NDEBUG
1465 /* Set up the transaction-counter change checking flags when
1466 ** transitioning from a SHARED to a RESERVED lock. The change
1467 ** from SHARED to RESERVED marks the beginning of a normal
1468 ** write operation (not a hot journal rollback).
1469 */
1470 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001471 && pFile->eFileLock<=SHARED_LOCK
1472 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001473 ){
1474 pFile->transCntrChng = 0;
1475 pFile->dbUpdate = 0;
1476 pFile->inNormalWrite = 1;
1477 }
1478#endif
1479
1480
danielk1977ecb2a962004-06-02 06:30:16 +00001481 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001482 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001483 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001484 }else if( eFileLock==EXCLUSIVE_LOCK ){
1485 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001486 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001487 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001488
1489end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001490 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001491 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1492 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001493 return rc;
1494}
1495
1496/*
dan08da86a2009-08-21 17:18:03 +00001497** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001498** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001499*/
1500static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001501 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001502 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001503 p->pNext = pInode->pUnused;
1504 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001505 pFile->h = -1;
1506 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001507}
1508
1509/*
drh308c2a52010-05-14 11:30:18 +00001510** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001511** must be either NO_LOCK or SHARED_LOCK.
1512**
1513** If the locking level of the file descriptor is already at or below
1514** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001515**
1516** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1517** the byte range is divided into 2 parts and the first part is unlocked then
1518** set to a read lock, then the other part is simply unlocked. This works
1519** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1520** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001521*/
drha7e61d82011-03-12 17:02:57 +00001522static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001523 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001524 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001525 struct flock lock;
1526 int rc = SQLITE_OK;
1527 int h;
drh0c2694b2009-09-03 16:23:44 +00001528 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001529
drh054889e2005-11-30 03:20:31 +00001530 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001531 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001532 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001533 getpid()));
drha6abd042004-06-09 17:37:22 +00001534
drh308c2a52010-05-14 11:30:18 +00001535 assert( eFileLock<=SHARED_LOCK );
1536 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001537 return SQLITE_OK;
1538 }
drh6c7d5c52008-11-21 20:32:33 +00001539 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001540 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001541 pInode = pFile->pInode;
1542 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001543 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001544 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001545 SimulateIOErrorBenign(1);
1546 SimulateIOError( h=(-1) )
1547 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001548
1549#ifndef NDEBUG
1550 /* When reducing a lock such that other processes can start
1551 ** reading the database file again, make sure that the
1552 ** transaction counter was updated if any part of the database
1553 ** file changed. If the transaction counter is not updated,
1554 ** other connections to the same file might not realize that
1555 ** the file has changed and hence might not know to flush their
1556 ** cache. The use of a stale cache can lead to database corruption.
1557 */
dan7c246102010-04-12 19:00:29 +00001558#if 0
drh8f941bc2009-01-14 23:03:40 +00001559 assert( pFile->inNormalWrite==0
1560 || pFile->dbUpdate==0
1561 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001562#endif
drh8f941bc2009-01-14 23:03:40 +00001563 pFile->inNormalWrite = 0;
1564#endif
1565
drh7ed97b92010-01-20 13:07:21 +00001566 /* downgrading to a shared lock on NFS involves clearing the write lock
1567 ** before establishing the readlock - to avoid a race condition we downgrade
1568 ** the lock in 2 blocks, so that part of the range will be covered by a
1569 ** write lock until the rest is covered by a read lock:
1570 ** 1: [WWWWW]
1571 ** 2: [....W]
1572 ** 3: [RRRRW]
1573 ** 4: [RRRR.]
1574 */
drh308c2a52010-05-14 11:30:18 +00001575 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001576
1577#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001578 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001579 assert( handleNFSUnlock==0 );
1580#endif
1581#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001582 if( handleNFSUnlock ){
1583 off_t divSize = SHARED_SIZE - 1;
1584
1585 lock.l_type = F_UNLCK;
1586 lock.l_whence = SEEK_SET;
1587 lock.l_start = SHARED_FIRST;
1588 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001589 if( unixFileLock(pFile,, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001590 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1592 if( IS_LOCK_ERROR(rc) ){
1593 pFile->lastErrno = tErrno;
1594 }
1595 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001596 }
drh7ed97b92010-01-20 13:07:21 +00001597 lock.l_type = F_RDLCK;
1598 lock.l_whence = SEEK_SET;
1599 lock.l_start = SHARED_FIRST;
1600 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001601 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001602 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001603 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1604 if( IS_LOCK_ERROR(rc) ){
1605 pFile->lastErrno = tErrno;
1606 }
1607 goto end_unlock;
1608 }
1609 lock.l_type = F_UNLCK;
1610 lock.l_whence = SEEK_SET;
1611 lock.l_start = SHARED_FIRST+divSize;
1612 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001613 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001614 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001615 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1616 if( IS_LOCK_ERROR(rc) ){
1617 pFile->lastErrno = tErrno;
1618 }
1619 goto end_unlock;
1620 }
drh30f776f2011-02-25 03:25:07 +00001621 }else
1622#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1623 {
drh7ed97b92010-01-20 13:07:21 +00001624 lock.l_type = F_RDLCK;
1625 lock.l_whence = SEEK_SET;
1626 lock.l_start = SHARED_FIRST;
1627 lock.l_len = SHARED_SIZE;
drha7e61d82011-03-12 17:02:57 +00001628 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001629 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001630 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1631 if( IS_LOCK_ERROR(rc) ){
1632 pFile->lastErrno = tErrno;
1633 }
1634 goto end_unlock;
1635 }
drh9c105bb2004-10-02 20:38:28 +00001636 }
1637 }
drhbbd42a62004-05-22 17:41:58 +00001638 lock.l_type = F_UNLCK;
1639 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001640 lock.l_start = PENDING_BYTE;
1641 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drha7e61d82011-03-12 17:02:57 +00001642 if( unixFileLock(pFile, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001643 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001644 }else{
drh0c2694b2009-09-03 16:23:44 +00001645 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001646 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1647 if( IS_LOCK_ERROR(rc) ){
1648 pFile->lastErrno = tErrno;
1649 }
drhcd731cf2009-03-28 23:23:02 +00001650 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001651 }
drhbbd42a62004-05-22 17:41:58 +00001652 }
drh308c2a52010-05-14 11:30:18 +00001653 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001654 /* Decrement the shared lock counter. Release the lock using an
1655 ** OS call only when all threads in this same process have released
1656 ** the lock.
1657 */
drh8af6c222010-05-14 12:43:01 +00001658 pInode->nShared--;
1659 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001660 lock.l_type = F_UNLCK;
1661 lock.l_whence = SEEK_SET;
1662 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001663 SimulateIOErrorBenign(1);
1664 SimulateIOError( h=(-1) )
1665 SimulateIOErrorBenign(0);
drha7e61d82011-03-12 17:02:57 +00001666 if( unixFileLock(pFile, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001667 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001668 }else{
drh0c2694b2009-09-03 16:23:44 +00001669 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001670 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001671 if( IS_LOCK_ERROR(rc) ){
1672 pFile->lastErrno = tErrno;
1673 }
drh8af6c222010-05-14 12:43:01 +00001674 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001675 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001676 }
drha6abd042004-06-09 17:37:22 +00001677 }
1678
drhbbd42a62004-05-22 17:41:58 +00001679 /* Decrement the count of locks against this same file. When the
1680 ** count reaches zero, close any other file descriptors whose close
1681 ** was deferred because of outstanding locks.
1682 */
drh8af6c222010-05-14 12:43:01 +00001683 pInode->nLock--;
1684 assert( pInode->nLock>=0 );
1685 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001686 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001687 }
1688 }
aswift5b1a2562008-08-22 00:22:35 +00001689
1690end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001691 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001692 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001693 return rc;
drhbbd42a62004-05-22 17:41:58 +00001694}
1695
1696/*
drh308c2a52010-05-14 11:30:18 +00001697** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001698** must be either NO_LOCK or SHARED_LOCK.
1699**
1700** If the locking level of the file descriptor is already at or below
1701** the requested locking level, this routine is a no-op.
1702*/
drh308c2a52010-05-14 11:30:18 +00001703static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001704 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001705}
1706
1707/*
danielk1977e339d652008-06-28 11:23:00 +00001708** This function performs the parts of the "close file" operation
1709** common to all locking schemes. It closes the directory and file
1710** handles, if they are valid, and sets all fields of the unixFile
1711** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001712**
1713** It is *not* necessary to hold the mutex when this routine is called,
1714** even on VxWorks. A mutex will be acquired on VxWorks by the
1715** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001716*/
1717static int closeUnixFile(sqlite3_file *id){
1718 unixFile *pFile = (unixFile*)id;
1719 if( pFile ){
1720 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001721 robust_close(pFile, pFile->dirfd, __LINE__);
1722 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001723 }
1724 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001725 robust_close(pFile, pFile->h, __LINE__);
1726 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001727 }
drh6c7d5c52008-11-21 20:32:33 +00001728#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001729 if( pFile->pId ){
1730 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001731 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001732 }
drh107886a2008-11-21 22:21:50 +00001733 vxworksReleaseFileId(pFile->pId);
1734 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001735 }
1736#endif
drhff59a112010-05-14 20:15:51 +00001737 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001738 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001739 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001740 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001741 }
1742 return SQLITE_OK;
1743}
1744
1745/*
danielk1977e3026632004-06-22 11:29:02 +00001746** Close a file.
1747*/
danielk197762079062007-08-15 17:08:46 +00001748static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001749 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001750 if( id ){
1751 unixFile *pFile = (unixFile *)id;
1752 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001753 unixEnterMutex();
drh3cb93392011-03-12 18:10:44 +00001754 assert( pFile->pInode==0 || pFile->pInode->nLock>0
1755 || pFile->pInode->bProcessLock==0 );
drh8af6c222010-05-14 12:43:01 +00001756 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001757 /* If there are outstanding locks, do not actually close the file just
1758 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001759 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001760 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001761 */
dan08da86a2009-08-21 17:18:03 +00001762 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001763 }
danb0ac3e32010-06-16 10:55:42 +00001764 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001765 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001766 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001767 }
aswiftaebf4132008-11-21 00:10:35 +00001768 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001769}
1770
drh734c9862008-11-28 15:37:20 +00001771/************** End of the posix advisory lock implementation *****************
1772******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001773
drh734c9862008-11-28 15:37:20 +00001774/******************************************************************************
1775****************************** No-op Locking **********************************
1776**
1777** Of the various locking implementations available, this is by far the
1778** simplest: locking is ignored. No attempt is made to lock the database
1779** file for reading or writing.
1780**
1781** This locking mode is appropriate for use on read-only databases
1782** (ex: databases that are burned into CD-ROM, for example.) It can
1783** also be used if the application employs some external mechanism to
1784** prevent simultaneous access of the same database by two or more
1785** database connections. But there is a serious risk of database
1786** corruption if this locking mode is used in situations where multiple
1787** database connections are accessing the same database file at the same
1788** time and one or more of those connections are writing.
1789*/
drhbfe66312006-10-03 17:40:40 +00001790
drh734c9862008-11-28 15:37:20 +00001791static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1792 UNUSED_PARAMETER(NotUsed);
1793 *pResOut = 0;
1794 return SQLITE_OK;
1795}
drh734c9862008-11-28 15:37:20 +00001796static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1797 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1798 return SQLITE_OK;
1799}
drh734c9862008-11-28 15:37:20 +00001800static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1801 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1802 return SQLITE_OK;
1803}
1804
1805/*
drh9b35ea62008-11-29 02:20:26 +00001806** Close the file.
drh734c9862008-11-28 15:37:20 +00001807*/
1808static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001809 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001810}
1811
1812/******************* End of the no-op lock implementation *********************
1813******************************************************************************/
1814
1815/******************************************************************************
1816************************* Begin dot-file Locking ******************************
1817**
drh0c2694b2009-09-03 16:23:44 +00001818** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001819** files in order to control access to the database. This works on just
1820** about every filesystem imaginable. But there are serious downsides:
1821**
1822** (1) There is zero concurrency. A single reader blocks all other
1823** connections from reading or writing the database.
1824**
1825** (2) An application crash or power loss can leave stale lock files
1826** sitting around that need to be cleared manually.
1827**
1828** Nevertheless, a dotlock is an appropriate locking mode for use if no
1829** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001830**
1831** Dotfile locking works by creating a file in the same directory as the
1832** database and with the same name but with a ".lock" extension added.
1833** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1834** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001835*/
1836
1837/*
1838** The file suffix added to the data base filename in order to create the
1839** lock file.
1840*/
1841#define DOTLOCK_SUFFIX ".lock"
1842
drh7708e972008-11-29 00:56:52 +00001843/*
1844** This routine checks if there is a RESERVED lock held on the specified
1845** file by this or any other process. If such a lock is held, set *pResOut
1846** to a non-zero value otherwise *pResOut is set to zero. The return value
1847** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1848**
1849** In dotfile locking, either a lock exists or it does not. So in this
1850** variation of CheckReservedLock(), *pResOut is set to true if any lock
1851** is held on the file and false if the file is unlocked.
1852*/
drh734c9862008-11-28 15:37:20 +00001853static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1854 int rc = SQLITE_OK;
1855 int reserved = 0;
1856 unixFile *pFile = (unixFile*)id;
1857
1858 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1859
1860 assert( pFile );
1861
1862 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001863 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001864 /* Either this connection or some other connection in the same process
1865 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001866 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001867 }else{
1868 /* The lock is held if and only if the lockfile exists */
1869 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001870 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001871 }
drh308c2a52010-05-14 11:30:18 +00001872 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001873 *pResOut = reserved;
1874 return rc;
1875}
1876
drh7708e972008-11-29 00:56:52 +00001877/*
drh308c2a52010-05-14 11:30:18 +00001878** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001879** of the following:
1880**
1881** (1) SHARED_LOCK
1882** (2) RESERVED_LOCK
1883** (3) PENDING_LOCK
1884** (4) EXCLUSIVE_LOCK
1885**
1886** Sometimes when requesting one lock state, additional lock states
1887** are inserted in between. The locking might fail on one of the later
1888** transitions leaving the lock state different from what it started but
1889** still short of its goal. The following chart shows the allowed
1890** transitions and the inserted intermediate states:
1891**
1892** UNLOCKED -> SHARED
1893** SHARED -> RESERVED
1894** SHARED -> (PENDING) -> EXCLUSIVE
1895** RESERVED -> (PENDING) -> EXCLUSIVE
1896** PENDING -> EXCLUSIVE
1897**
1898** This routine will only increase a lock. Use the sqlite3OsUnlock()
1899** routine to lower a locking level.
1900**
1901** With dotfile locking, we really only support state (4): EXCLUSIVE.
1902** But we track the other locking levels internally.
1903*/
drh308c2a52010-05-14 11:30:18 +00001904static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001905 unixFile *pFile = (unixFile*)id;
1906 int fd;
1907 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001908 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001909
drh7708e972008-11-29 00:56:52 +00001910
1911 /* If we have any lock, then the lock file already exists. All we have
1912 ** to do is adjust our internal record of the lock level.
1913 */
drh308c2a52010-05-14 11:30:18 +00001914 if( pFile->eFileLock > NO_LOCK ){
1915 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001916#if !OS_VXWORKS
1917 /* Always update the timestamp on the old file */
1918 utimes(zLockFile, NULL);
1919#endif
drh7708e972008-11-29 00:56:52 +00001920 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001921 }
1922
1923 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001924 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001925 if( fd<0 ){
1926 /* failed to open/create the file, someone else may have stolen the lock */
1927 int tErrno = errno;
1928 if( EEXIST == tErrno ){
1929 rc = SQLITE_BUSY;
1930 } else {
1931 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1932 if( IS_LOCK_ERROR(rc) ){
1933 pFile->lastErrno = tErrno;
1934 }
1935 }
drh7708e972008-11-29 00:56:52 +00001936 return rc;
drh734c9862008-11-28 15:37:20 +00001937 }
drh0e9365c2011-03-02 02:08:13 +00001938 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001939
1940 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001941 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001942 return rc;
1943}
1944
drh7708e972008-11-29 00:56:52 +00001945/*
drh308c2a52010-05-14 11:30:18 +00001946** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001947** must be either NO_LOCK or SHARED_LOCK.
1948**
1949** If the locking level of the file descriptor is already at or below
1950** the requested locking level, this routine is a no-op.
1951**
1952** When the locking level reaches NO_LOCK, delete the lock file.
1953*/
drh308c2a52010-05-14 11:30:18 +00001954static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001955 unixFile *pFile = (unixFile*)id;
1956 char *zLockFile = (char *)pFile->lockingContext;
1957
1958 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001959 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1960 pFile->eFileLock, getpid()));
1961 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001962
1963 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001964 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001965 return SQLITE_OK;
1966 }
drh7708e972008-11-29 00:56:52 +00001967
1968 /* To downgrade to shared, simply update our internal notion of the
1969 ** lock state. No need to mess with the file on disk.
1970 */
drh308c2a52010-05-14 11:30:18 +00001971 if( eFileLock==SHARED_LOCK ){
1972 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001973 return SQLITE_OK;
1974 }
1975
drh7708e972008-11-29 00:56:52 +00001976 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001977 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001978 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001979 int rc = 0;
1980 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001981 if( ENOENT != tErrno ){
1982 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1983 }
1984 if( IS_LOCK_ERROR(rc) ){
1985 pFile->lastErrno = tErrno;
1986 }
1987 return rc;
1988 }
drh308c2a52010-05-14 11:30:18 +00001989 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001990 return SQLITE_OK;
1991}
1992
1993/*
drh9b35ea62008-11-29 02:20:26 +00001994** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001995*/
1996static int dotlockClose(sqlite3_file *id) {
1997 int rc;
1998 if( id ){
1999 unixFile *pFile = (unixFile*)id;
2000 dotlockUnlock(id, NO_LOCK);
2001 sqlite3_free(pFile->lockingContext);
2002 }
drh734c9862008-11-28 15:37:20 +00002003 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002004 return rc;
2005}
2006/****************** End of the dot-file lock implementation *******************
2007******************************************************************************/
2008
2009/******************************************************************************
2010************************** Begin flock Locking ********************************
2011**
2012** Use the flock() system call to do file locking.
2013**
drh6b9d6dd2008-12-03 19:34:47 +00002014** flock() locking is like dot-file locking in that the various
2015** fine-grain locking levels supported by SQLite are collapsed into
2016** a single exclusive lock. In other words, SHARED, RESERVED, and
2017** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2018** still works when you do this, but concurrency is reduced since
2019** only a single process can be reading the database at a time.
2020**
drh734c9862008-11-28 15:37:20 +00002021** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2022** compiling for VXWORKS.
2023*/
2024#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002025
drh6b9d6dd2008-12-03 19:34:47 +00002026/*
drhff812312011-02-23 13:33:46 +00002027** Retry flock() calls that fail with EINTR
2028*/
2029#ifdef EINTR
2030static int robust_flock(int fd, int op){
2031 int rc;
2032 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2033 return rc;
2034}
2035#else
drh5c819272011-02-23 14:00:12 +00002036# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002037#endif
2038
2039
2040/*
drh6b9d6dd2008-12-03 19:34:47 +00002041** This routine checks if there is a RESERVED lock held on the specified
2042** file by this or any other process. If such a lock is held, set *pResOut
2043** to a non-zero value otherwise *pResOut is set to zero. The return value
2044** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2045*/
drh734c9862008-11-28 15:37:20 +00002046static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2047 int rc = SQLITE_OK;
2048 int reserved = 0;
2049 unixFile *pFile = (unixFile*)id;
2050
2051 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2052
2053 assert( pFile );
2054
2055 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002056 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002057 reserved = 1;
2058 }
2059
2060 /* Otherwise see if some other process holds it. */
2061 if( !reserved ){
2062 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002063 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002064 if( !lrc ){
2065 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002066 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002067 if ( lrc ) {
2068 int tErrno = errno;
2069 /* unlock failed with an error */
2070 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2071 if( IS_LOCK_ERROR(lrc) ){
2072 pFile->lastErrno = tErrno;
2073 rc = lrc;
2074 }
2075 }
2076 } else {
2077 int tErrno = errno;
2078 reserved = 1;
2079 /* someone else might have it reserved */
2080 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2081 if( IS_LOCK_ERROR(lrc) ){
2082 pFile->lastErrno = tErrno;
2083 rc = lrc;
2084 }
2085 }
2086 }
drh308c2a52010-05-14 11:30:18 +00002087 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002088
2089#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2090 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2091 rc = SQLITE_OK;
2092 reserved=1;
2093 }
2094#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2095 *pResOut = reserved;
2096 return rc;
2097}
2098
drh6b9d6dd2008-12-03 19:34:47 +00002099/*
drh308c2a52010-05-14 11:30:18 +00002100** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002101** of the following:
2102**
2103** (1) SHARED_LOCK
2104** (2) RESERVED_LOCK
2105** (3) PENDING_LOCK
2106** (4) EXCLUSIVE_LOCK
2107**
2108** Sometimes when requesting one lock state, additional lock states
2109** are inserted in between. The locking might fail on one of the later
2110** transitions leaving the lock state different from what it started but
2111** still short of its goal. The following chart shows the allowed
2112** transitions and the inserted intermediate states:
2113**
2114** UNLOCKED -> SHARED
2115** SHARED -> RESERVED
2116** SHARED -> (PENDING) -> EXCLUSIVE
2117** RESERVED -> (PENDING) -> EXCLUSIVE
2118** PENDING -> EXCLUSIVE
2119**
2120** flock() only really support EXCLUSIVE locks. We track intermediate
2121** lock states in the sqlite3_file structure, but all locks SHARED or
2122** above are really EXCLUSIVE locks and exclude all other processes from
2123** access the file.
2124**
2125** This routine will only increase a lock. Use the sqlite3OsUnlock()
2126** routine to lower a locking level.
2127*/
drh308c2a52010-05-14 11:30:18 +00002128static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002129 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002130 unixFile *pFile = (unixFile*)id;
2131
2132 assert( pFile );
2133
2134 /* if we already have a lock, it is exclusive.
2135 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002136 if (pFile->eFileLock > NO_LOCK) {
2137 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002138 return SQLITE_OK;
2139 }
2140
2141 /* grab an exclusive lock */
2142
drhff812312011-02-23 13:33:46 +00002143 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002144 int tErrno = errno;
2145 /* didn't get, must be busy */
2146 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2147 if( IS_LOCK_ERROR(rc) ){
2148 pFile->lastErrno = tErrno;
2149 }
2150 } else {
2151 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002152 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002153 }
drh308c2a52010-05-14 11:30:18 +00002154 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2155 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002156#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2157 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2158 rc = SQLITE_BUSY;
2159 }
2160#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2161 return rc;
2162}
2163
drh6b9d6dd2008-12-03 19:34:47 +00002164
2165/*
drh308c2a52010-05-14 11:30:18 +00002166** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002167** must be either NO_LOCK or SHARED_LOCK.
2168**
2169** If the locking level of the file descriptor is already at or below
2170** the requested locking level, this routine is a no-op.
2171*/
drh308c2a52010-05-14 11:30:18 +00002172static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002173 unixFile *pFile = (unixFile*)id;
2174
2175 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002176 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2177 pFile->eFileLock, getpid()));
2178 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002179
2180 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002181 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002182 return SQLITE_OK;
2183 }
2184
2185 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002186 if (eFileLock==SHARED_LOCK) {
2187 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002188 return SQLITE_OK;
2189 }
2190
2191 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002192 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002193 if (rc) {
2194 int r, tErrno = errno;
2195 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2196 if( IS_LOCK_ERROR(r) ){
2197 pFile->lastErrno = tErrno;
2198 }
2199#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2200 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2201 r = SQLITE_BUSY;
2202 }
2203#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2204
2205 return r;
2206 } else {
drh308c2a52010-05-14 11:30:18 +00002207 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002208 return SQLITE_OK;
2209 }
2210}
2211
2212/*
2213** Close a file.
2214*/
2215static int flockClose(sqlite3_file *id) {
2216 if( id ){
2217 flockUnlock(id, NO_LOCK);
2218 }
2219 return closeUnixFile(id);
2220}
2221
2222#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2223
2224/******************* End of the flock lock implementation *********************
2225******************************************************************************/
2226
2227/******************************************************************************
2228************************ Begin Named Semaphore Locking ************************
2229**
2230** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002231**
2232** Semaphore locking is like dot-lock and flock in that it really only
2233** supports EXCLUSIVE locking. Only a single process can read or write
2234** the database file at a time. This reduces potential concurrency, but
2235** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002236*/
2237#if OS_VXWORKS
2238
drh6b9d6dd2008-12-03 19:34:47 +00002239/*
2240** This routine checks if there is a RESERVED lock held on the specified
2241** file by this or any other process. If such a lock is held, set *pResOut
2242** to a non-zero value otherwise *pResOut is set to zero. The return value
2243** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2244*/
drh734c9862008-11-28 15:37:20 +00002245static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2246 int rc = SQLITE_OK;
2247 int reserved = 0;
2248 unixFile *pFile = (unixFile*)id;
2249
2250 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2251
2252 assert( pFile );
2253
2254 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002255 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002256 reserved = 1;
2257 }
2258
2259 /* Otherwise see if some other process holds it. */
2260 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002261 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002262 struct stat statBuf;
2263
2264 if( sem_trywait(pSem)==-1 ){
2265 int tErrno = errno;
2266 if( EAGAIN != tErrno ){
2267 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2268 pFile->lastErrno = tErrno;
2269 } else {
2270 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002271 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002272 }
2273 }else{
2274 /* we could have it if we want it */
2275 sem_post(pSem);
2276 }
2277 }
drh308c2a52010-05-14 11:30:18 +00002278 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002279
2280 *pResOut = reserved;
2281 return rc;
2282}
2283
drh6b9d6dd2008-12-03 19:34:47 +00002284/*
drh308c2a52010-05-14 11:30:18 +00002285** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002286** of the following:
2287**
2288** (1) SHARED_LOCK
2289** (2) RESERVED_LOCK
2290** (3) PENDING_LOCK
2291** (4) EXCLUSIVE_LOCK
2292**
2293** Sometimes when requesting one lock state, additional lock states
2294** are inserted in between. The locking might fail on one of the later
2295** transitions leaving the lock state different from what it started but
2296** still short of its goal. The following chart shows the allowed
2297** transitions and the inserted intermediate states:
2298**
2299** UNLOCKED -> SHARED
2300** SHARED -> RESERVED
2301** SHARED -> (PENDING) -> EXCLUSIVE
2302** RESERVED -> (PENDING) -> EXCLUSIVE
2303** PENDING -> EXCLUSIVE
2304**
2305** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2306** lock states in the sqlite3_file structure, but all locks SHARED or
2307** above are really EXCLUSIVE locks and exclude all other processes from
2308** access the file.
2309**
2310** This routine will only increase a lock. Use the sqlite3OsUnlock()
2311** routine to lower a locking level.
2312*/
drh308c2a52010-05-14 11:30:18 +00002313static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002314 unixFile *pFile = (unixFile*)id;
2315 int fd;
drh8af6c222010-05-14 12:43:01 +00002316 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002317 int rc = SQLITE_OK;
2318
2319 /* if we already have a lock, it is exclusive.
2320 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002321 if (pFile->eFileLock > NO_LOCK) {
2322 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002323 rc = SQLITE_OK;
2324 goto sem_end_lock;
2325 }
2326
2327 /* lock semaphore now but bail out when already locked. */
2328 if( sem_trywait(pSem)==-1 ){
2329 rc = SQLITE_BUSY;
2330 goto sem_end_lock;
2331 }
2332
2333 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002334 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002335
2336 sem_end_lock:
2337 return rc;
2338}
2339
drh6b9d6dd2008-12-03 19:34:47 +00002340/*
drh308c2a52010-05-14 11:30:18 +00002341** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002342** must be either NO_LOCK or SHARED_LOCK.
2343**
2344** If the locking level of the file descriptor is already at or below
2345** the requested locking level, this routine is a no-op.
2346*/
drh308c2a52010-05-14 11:30:18 +00002347static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002348 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002349 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002350
2351 assert( pFile );
2352 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002353 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2354 pFile->eFileLock, getpid()));
2355 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002356
2357 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002358 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002359 return SQLITE_OK;
2360 }
2361
2362 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002363 if (eFileLock==SHARED_LOCK) {
2364 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002365 return SQLITE_OK;
2366 }
2367
2368 /* no, really unlock. */
2369 if ( sem_post(pSem)==-1 ) {
2370 int rc, tErrno = errno;
2371 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2372 if( IS_LOCK_ERROR(rc) ){
2373 pFile->lastErrno = tErrno;
2374 }
2375 return rc;
2376 }
drh308c2a52010-05-14 11:30:18 +00002377 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002378 return SQLITE_OK;
2379}
2380
2381/*
2382 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002383 */
drh734c9862008-11-28 15:37:20 +00002384static int semClose(sqlite3_file *id) {
2385 if( id ){
2386 unixFile *pFile = (unixFile*)id;
2387 semUnlock(id, NO_LOCK);
2388 assert( pFile );
2389 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002390 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002391 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002392 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002393 }
2394 return SQLITE_OK;
2395}
2396
2397#endif /* OS_VXWORKS */
2398/*
2399** Named semaphore locking is only available on VxWorks.
2400**
2401*************** End of the named semaphore lock implementation ****************
2402******************************************************************************/
2403
2404
2405/******************************************************************************
2406*************************** Begin AFP Locking *********************************
2407**
2408** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2409** on Apple Macintosh computers - both OS9 and OSX.
2410**
2411** Third-party implementations of AFP are available. But this code here
2412** only works on OSX.
2413*/
2414
drhd2cb50b2009-01-09 21:41:17 +00002415#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002416/*
2417** The afpLockingContext structure contains all afp lock specific state
2418*/
drhbfe66312006-10-03 17:40:40 +00002419typedef struct afpLockingContext afpLockingContext;
2420struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002421 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002422 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002423};
2424
2425struct ByteRangeLockPB2
2426{
2427 unsigned long long offset; /* offset to first byte to lock */
2428 unsigned long long length; /* nbr of bytes to lock */
2429 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2430 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2431 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2432 int fd; /* file desc to assoc this lock with */
2433};
2434
drhfd131da2007-08-07 17:13:03 +00002435#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002436
drh6b9d6dd2008-12-03 19:34:47 +00002437/*
2438** This is a utility for setting or clearing a bit-range lock on an
2439** AFP filesystem.
2440**
2441** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2442*/
2443static int afpSetLock(
2444 const char *path, /* Name of the file to be locked or unlocked */
2445 unixFile *pFile, /* Open file descriptor on path */
2446 unsigned long long offset, /* First byte to be locked */
2447 unsigned long long length, /* Number of bytes to lock */
2448 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002449){
drh6b9d6dd2008-12-03 19:34:47 +00002450 struct ByteRangeLockPB2 pb;
2451 int err;
drhbfe66312006-10-03 17:40:40 +00002452
2453 pb.unLockFlag = setLockFlag ? 0 : 1;
2454 pb.startEndFlag = 0;
2455 pb.offset = offset;
2456 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002457 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002458
drh308c2a52010-05-14 11:30:18 +00002459 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002460 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002461 offset, length));
drhbfe66312006-10-03 17:40:40 +00002462 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2463 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002464 int rc;
2465 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002466 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2467 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002468#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2469 rc = SQLITE_BUSY;
2470#else
drh734c9862008-11-28 15:37:20 +00002471 rc = sqliteErrorFromPosixError(tErrno,
2472 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002473#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002474 if( IS_LOCK_ERROR(rc) ){
2475 pFile->lastErrno = tErrno;
2476 }
2477 return rc;
drhbfe66312006-10-03 17:40:40 +00002478 } else {
aswift5b1a2562008-08-22 00:22:35 +00002479 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002480 }
2481}
2482
drh6b9d6dd2008-12-03 19:34:47 +00002483/*
2484** This routine checks if there is a RESERVED lock held on the specified
2485** file by this or any other process. If such a lock is held, set *pResOut
2486** to a non-zero value otherwise *pResOut is set to zero. The return value
2487** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2488*/
danielk1977e339d652008-06-28 11:23:00 +00002489static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002490 int rc = SQLITE_OK;
2491 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002492 unixFile *pFile = (unixFile*)id;
2493
aswift5b1a2562008-08-22 00:22:35 +00002494 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2495
2496 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002497 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002498 if( context->reserved ){
2499 *pResOut = 1;
2500 return SQLITE_OK;
2501 }
drh8af6c222010-05-14 12:43:01 +00002502 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002503
2504 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002505 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002506 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002507 }
2508
2509 /* Otherwise see if some other process holds it.
2510 */
aswift5b1a2562008-08-22 00:22:35 +00002511 if( !reserved ){
2512 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002513 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002514 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002515 /* if we succeeded in taking the reserved lock, unlock it to restore
2516 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002517 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002518 } else {
2519 /* if we failed to get the lock then someone else must have it */
2520 reserved = 1;
2521 }
2522 if( IS_LOCK_ERROR(lrc) ){
2523 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002524 }
2525 }
drhbfe66312006-10-03 17:40:40 +00002526
drh7ed97b92010-01-20 13:07:21 +00002527 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002528 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002529
2530 *pResOut = reserved;
2531 return rc;
drhbfe66312006-10-03 17:40:40 +00002532}
2533
drh6b9d6dd2008-12-03 19:34:47 +00002534/*
drh308c2a52010-05-14 11:30:18 +00002535** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002536** of the following:
2537**
2538** (1) SHARED_LOCK
2539** (2) RESERVED_LOCK
2540** (3) PENDING_LOCK
2541** (4) EXCLUSIVE_LOCK
2542**
2543** Sometimes when requesting one lock state, additional lock states
2544** are inserted in between. The locking might fail on one of the later
2545** transitions leaving the lock state different from what it started but
2546** still short of its goal. The following chart shows the allowed
2547** transitions and the inserted intermediate states:
2548**
2549** UNLOCKED -> SHARED
2550** SHARED -> RESERVED
2551** SHARED -> (PENDING) -> EXCLUSIVE
2552** RESERVED -> (PENDING) -> EXCLUSIVE
2553** PENDING -> EXCLUSIVE
2554**
2555** This routine will only increase a lock. Use the sqlite3OsUnlock()
2556** routine to lower a locking level.
2557*/
drh308c2a52010-05-14 11:30:18 +00002558static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002559 int rc = SQLITE_OK;
2560 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002561 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002562 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002563
2564 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002565 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2566 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002567 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002568
drhbfe66312006-10-03 17:40:40 +00002569 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002570 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002571 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002572 */
drh308c2a52010-05-14 11:30:18 +00002573 if( pFile->eFileLock>=eFileLock ){
2574 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2575 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002576 return SQLITE_OK;
2577 }
2578
2579 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002580 ** (1) We never move from unlocked to anything higher than shared lock.
2581 ** (2) SQLite never explicitly requests a pendig lock.
2582 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002583 */
drh308c2a52010-05-14 11:30:18 +00002584 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2585 assert( eFileLock!=PENDING_LOCK );
2586 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002587
drh8af6c222010-05-14 12:43:01 +00002588 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002589 */
drh6c7d5c52008-11-21 20:32:33 +00002590 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002591 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002592
2593 /* If some thread using this PID has a lock via a different unixFile*
2594 ** handle that precludes the requested lock, return BUSY.
2595 */
drh8af6c222010-05-14 12:43:01 +00002596 if( (pFile->eFileLock!=pInode->eFileLock &&
2597 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002598 ){
2599 rc = SQLITE_BUSY;
2600 goto afp_end_lock;
2601 }
2602
2603 /* If a SHARED lock is requested, and some thread using this PID already
2604 ** has a SHARED or RESERVED lock, then increment reference counts and
2605 ** return SQLITE_OK.
2606 */
drh308c2a52010-05-14 11:30:18 +00002607 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002608 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002609 assert( eFileLock==SHARED_LOCK );
2610 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002611 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002612 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002613 pInode->nShared++;
2614 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002615 goto afp_end_lock;
2616 }
drhbfe66312006-10-03 17:40:40 +00002617
2618 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002619 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2620 ** be released.
2621 */
drh308c2a52010-05-14 11:30:18 +00002622 if( eFileLock==SHARED_LOCK
2623 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002624 ){
2625 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002626 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002627 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002628 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002629 goto afp_end_lock;
2630 }
2631 }
2632
2633 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002634 ** operating system calls for the specified lock.
2635 */
drh308c2a52010-05-14 11:30:18 +00002636 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002637 int lrc1, lrc2, lrc1Errno;
2638 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002639
drh8af6c222010-05-14 12:43:01 +00002640 assert( pInode->nShared==0 );
2641 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002642
2643 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002644 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002645 /* note that the quality of the randomness doesn't matter that much */
2646 lk = random();
drh8af6c222010-05-14 12:43:01 +00002647 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002648 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002649 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002650 if( IS_LOCK_ERROR(lrc1) ){
2651 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002652 }
aswift5b1a2562008-08-22 00:22:35 +00002653 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002654 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002655
aswift5b1a2562008-08-22 00:22:35 +00002656 if( IS_LOCK_ERROR(lrc1) ) {
2657 pFile->lastErrno = lrc1Errno;
2658 rc = lrc1;
2659 goto afp_end_lock;
2660 } else if( IS_LOCK_ERROR(lrc2) ){
2661 rc = lrc2;
2662 goto afp_end_lock;
2663 } else if( lrc1 != SQLITE_OK ) {
2664 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002665 } else {
drh308c2a52010-05-14 11:30:18 +00002666 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002667 pInode->nLock++;
2668 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002669 }
drh8af6c222010-05-14 12:43:01 +00002670 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002671 /* We are trying for an exclusive lock but another thread in this
2672 ** same process is still holding a shared lock. */
2673 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002674 }else{
2675 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2676 ** assumed that there is a SHARED or greater lock on the file
2677 ** already.
2678 */
2679 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002680 assert( 0!=pFile->eFileLock );
2681 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002682 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002683 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002684 if( !failed ){
2685 context->reserved = 1;
2686 }
drhbfe66312006-10-03 17:40:40 +00002687 }
drh308c2a52010-05-14 11:30:18 +00002688 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002689 /* Acquire an EXCLUSIVE lock */
2690
2691 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002692 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002693 */
drh6b9d6dd2008-12-03 19:34:47 +00002694 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002695 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002696 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002697 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002698 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002699 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002700 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002701 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002702 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2703 ** a critical I/O error
2704 */
2705 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2706 SQLITE_IOERR_LOCK;
2707 goto afp_end_lock;
2708 }
2709 }else{
aswift5b1a2562008-08-22 00:22:35 +00002710 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002711 }
2712 }
aswift5b1a2562008-08-22 00:22:35 +00002713 if( failed ){
2714 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002715 }
2716 }
2717
2718 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002719 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002720 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002721 }else if( eFileLock==EXCLUSIVE_LOCK ){
2722 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002723 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002724 }
2725
2726afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002727 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002728 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2729 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002730 return rc;
2731}
2732
2733/*
drh308c2a52010-05-14 11:30:18 +00002734** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002735** must be either NO_LOCK or SHARED_LOCK.
2736**
2737** If the locking level of the file descriptor is already at or below
2738** the requested locking level, this routine is a no-op.
2739*/
drh308c2a52010-05-14 11:30:18 +00002740static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002741 int rc = SQLITE_OK;
2742 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002743 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002744 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2745 int skipShared = 0;
2746#ifdef SQLITE_TEST
2747 int h = pFile->h;
2748#endif
drhbfe66312006-10-03 17:40:40 +00002749
2750 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002751 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002752 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002753 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002754
drh308c2a52010-05-14 11:30:18 +00002755 assert( eFileLock<=SHARED_LOCK );
2756 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002757 return SQLITE_OK;
2758 }
drh6c7d5c52008-11-21 20:32:33 +00002759 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002760 pInode = pFile->pInode;
2761 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002762 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002763 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002764 SimulateIOErrorBenign(1);
2765 SimulateIOError( h=(-1) )
2766 SimulateIOErrorBenign(0);
2767
2768#ifndef NDEBUG
2769 /* When reducing a lock such that other processes can start
2770 ** reading the database file again, make sure that the
2771 ** transaction counter was updated if any part of the database
2772 ** file changed. If the transaction counter is not updated,
2773 ** other connections to the same file might not realize that
2774 ** the file has changed and hence might not know to flush their
2775 ** cache. The use of a stale cache can lead to database corruption.
2776 */
2777 assert( pFile->inNormalWrite==0
2778 || pFile->dbUpdate==0
2779 || pFile->transCntrChng==1 );
2780 pFile->inNormalWrite = 0;
2781#endif
aswiftaebf4132008-11-21 00:10:35 +00002782
drh308c2a52010-05-14 11:30:18 +00002783 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002784 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002785 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002786 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002787 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002788 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2789 } else {
2790 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002791 }
2792 }
drh308c2a52010-05-14 11:30:18 +00002793 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002794 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002795 }
drh308c2a52010-05-14 11:30:18 +00002796 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002797 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2798 if( !rc ){
2799 context->reserved = 0;
2800 }
aswiftaebf4132008-11-21 00:10:35 +00002801 }
drh8af6c222010-05-14 12:43:01 +00002802 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2803 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002804 }
aswiftaebf4132008-11-21 00:10:35 +00002805 }
drh308c2a52010-05-14 11:30:18 +00002806 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002807
drh7ed97b92010-01-20 13:07:21 +00002808 /* Decrement the shared lock counter. Release the lock using an
2809 ** OS call only when all threads in this same process have released
2810 ** the lock.
2811 */
drh8af6c222010-05-14 12:43:01 +00002812 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2813 pInode->nShared--;
2814 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002815 SimulateIOErrorBenign(1);
2816 SimulateIOError( h=(-1) )
2817 SimulateIOErrorBenign(0);
2818 if( !skipShared ){
2819 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2820 }
2821 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002822 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002823 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002824 }
2825 }
2826 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002827 pInode->nLock--;
2828 assert( pInode->nLock>=0 );
2829 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002830 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002831 }
2832 }
drhbfe66312006-10-03 17:40:40 +00002833 }
drh7ed97b92010-01-20 13:07:21 +00002834
drh6c7d5c52008-11-21 20:32:33 +00002835 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002836 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002837 return rc;
2838}
2839
2840/*
drh339eb0b2008-03-07 15:34:11 +00002841** Close a file & cleanup AFP specific locking context
2842*/
danielk1977e339d652008-06-28 11:23:00 +00002843static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002844 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002845 if( id ){
2846 unixFile *pFile = (unixFile*)id;
2847 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002848 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002849 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002850 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002851 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002852 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002853 ** the last lock is cleared.
2854 */
dan08da86a2009-08-21 17:18:03 +00002855 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002856 }
danb0ac3e32010-06-16 10:55:42 +00002857 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002858 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002859 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002860 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002861 }
drh7ed97b92010-01-20 13:07:21 +00002862 return rc;
drhbfe66312006-10-03 17:40:40 +00002863}
2864
drhd2cb50b2009-01-09 21:41:17 +00002865#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002866/*
2867** The code above is the AFP lock implementation. The code is specific
2868** to MacOSX and does not work on other unix platforms. No alternative
2869** is available. If you don't compile for a mac, then the "unix-afp"
2870** VFS is not available.
2871**
2872********************* End of the AFP lock implementation **********************
2873******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002874
drh7ed97b92010-01-20 13:07:21 +00002875/******************************************************************************
2876*************************** Begin NFS Locking ********************************/
2877
2878#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2879/*
drh308c2a52010-05-14 11:30:18 +00002880 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002881 ** must be either NO_LOCK or SHARED_LOCK.
2882 **
2883 ** If the locking level of the file descriptor is already at or below
2884 ** the requested locking level, this routine is a no-op.
2885 */
drh308c2a52010-05-14 11:30:18 +00002886static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002887 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002888}
2889
2890#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2891/*
2892** The code above is the NFS lock implementation. The code is specific
2893** to MacOSX and does not work on other unix platforms. No alternative
2894** is available.
2895**
2896********************* End of the NFS lock implementation **********************
2897******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002898
2899/******************************************************************************
2900**************** Non-locking sqlite3_file methods *****************************
2901**
2902** The next division contains implementations for all methods of the
2903** sqlite3_file object other than the locking methods. The locking
2904** methods were defined in divisions above (one locking method per
2905** division). Those methods that are common to all locking modes
2906** are gather together into this division.
2907*/
drhbfe66312006-10-03 17:40:40 +00002908
2909/*
drh734c9862008-11-28 15:37:20 +00002910** Seek to the offset passed as the second argument, then read cnt
2911** bytes into pBuf. Return the number of bytes actually read.
2912**
2913** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2914** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2915** one system to another. Since SQLite does not define USE_PREAD
2916** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2917** See tickets #2741 and #2681.
2918**
2919** To avoid stomping the errno value on a failed read the lastErrno value
2920** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002921*/
drh734c9862008-11-28 15:37:20 +00002922static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2923 int got;
drh7ed97b92010-01-20 13:07:21 +00002924#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002925 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002926#endif
drh734c9862008-11-28 15:37:20 +00002927 TIMER_START;
2928#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002929 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002930 SimulateIOError( got = -1 );
2931#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002932 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002933 SimulateIOError( got = -1 );
2934#else
2935 newOffset = lseek(id->h, offset, SEEK_SET);
2936 SimulateIOError( newOffset-- );
2937 if( newOffset!=offset ){
2938 if( newOffset == -1 ){
2939 ((unixFile*)id)->lastErrno = errno;
2940 }else{
2941 ((unixFile*)id)->lastErrno = 0;
2942 }
2943 return -1;
2944 }
drhe562be52011-03-02 18:01:10 +00002945 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002946#endif
2947 TIMER_END;
2948 if( got<0 ){
2949 ((unixFile*)id)->lastErrno = errno;
2950 }
drh308c2a52010-05-14 11:30:18 +00002951 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002952 return got;
drhbfe66312006-10-03 17:40:40 +00002953}
2954
2955/*
drh734c9862008-11-28 15:37:20 +00002956** Read data from a file into a buffer. Return SQLITE_OK if all
2957** bytes were read successfully and SQLITE_IOERR if anything goes
2958** wrong.
drh339eb0b2008-03-07 15:34:11 +00002959*/
drh734c9862008-11-28 15:37:20 +00002960static int unixRead(
2961 sqlite3_file *id,
2962 void *pBuf,
2963 int amt,
2964 sqlite3_int64 offset
2965){
dan08da86a2009-08-21 17:18:03 +00002966 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002967 int got;
2968 assert( id );
drh08c6d442009-02-09 17:34:07 +00002969
dan08da86a2009-08-21 17:18:03 +00002970 /* If this is a database file (not a journal, master-journal or temp
2971 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002972#if 0
dane946c392009-08-22 11:39:46 +00002973 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002974 || offset>=PENDING_BYTE+512
2975 || offset+amt<=PENDING_BYTE
2976 );
dan7c246102010-04-12 19:00:29 +00002977#endif
drh08c6d442009-02-09 17:34:07 +00002978
dan08da86a2009-08-21 17:18:03 +00002979 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002980 if( got==amt ){
2981 return SQLITE_OK;
2982 }else if( got<0 ){
2983 /* lastErrno set by seekAndRead */
2984 return SQLITE_IOERR_READ;
2985 }else{
dan08da86a2009-08-21 17:18:03 +00002986 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002987 /* Unread parts of the buffer must be zero-filled */
2988 memset(&((char*)pBuf)[got], 0, amt-got);
2989 return SQLITE_IOERR_SHORT_READ;
2990 }
2991}
2992
2993/*
2994** Seek to the offset in id->offset then read cnt bytes into pBuf.
2995** Return the number of bytes actually read. Update the offset.
2996**
2997** To avoid stomping the errno value on a failed write the lastErrno value
2998** is set before returning.
2999*/
3000static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3001 int got;
drh7ed97b92010-01-20 13:07:21 +00003002#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003003 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003004#endif
drh734c9862008-11-28 15:37:20 +00003005 TIMER_START;
3006#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003007 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003008#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003009 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003010#else
3011 newOffset = lseek(id->h, offset, SEEK_SET);
3012 if( newOffset!=offset ){
3013 if( newOffset == -1 ){
3014 ((unixFile*)id)->lastErrno = errno;
3015 }else{
3016 ((unixFile*)id)->lastErrno = 0;
3017 }
3018 return -1;
3019 }
drhe562be52011-03-02 18:01:10 +00003020 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003021#endif
3022 TIMER_END;
3023 if( got<0 ){
3024 ((unixFile*)id)->lastErrno = errno;
3025 }
3026
drh308c2a52010-05-14 11:30:18 +00003027 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003028 return got;
3029}
3030
3031
3032/*
3033** Write data from a buffer into a file. Return SQLITE_OK on success
3034** or some other error code on failure.
3035*/
3036static int unixWrite(
3037 sqlite3_file *id,
3038 const void *pBuf,
3039 int amt,
3040 sqlite3_int64 offset
3041){
dan08da86a2009-08-21 17:18:03 +00003042 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003043 int wrote = 0;
3044 assert( id );
3045 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003046
dan08da86a2009-08-21 17:18:03 +00003047 /* If this is a database file (not a journal, master-journal or temp
3048 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003049#if 0
dane946c392009-08-22 11:39:46 +00003050 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003051 || offset>=PENDING_BYTE+512
3052 || offset+amt<=PENDING_BYTE
3053 );
dan7c246102010-04-12 19:00:29 +00003054#endif
drh08c6d442009-02-09 17:34:07 +00003055
drh8f941bc2009-01-14 23:03:40 +00003056#ifndef NDEBUG
3057 /* If we are doing a normal write to a database file (as opposed to
3058 ** doing a hot-journal rollback or a write to some file other than a
3059 ** normal database file) then record the fact that the database
3060 ** has changed. If the transaction counter is modified, record that
3061 ** fact too.
3062 */
dan08da86a2009-08-21 17:18:03 +00003063 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003064 pFile->dbUpdate = 1; /* The database has been modified */
3065 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003066 int rc;
drh8f941bc2009-01-14 23:03:40 +00003067 char oldCntr[4];
3068 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003069 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003070 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003071 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003072 pFile->transCntrChng = 1; /* The transaction counter has changed */
3073 }
3074 }
3075 }
3076#endif
3077
dan08da86a2009-08-21 17:18:03 +00003078 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003079 amt -= wrote;
3080 offset += wrote;
3081 pBuf = &((char*)pBuf)[wrote];
3082 }
3083 SimulateIOError(( wrote=(-1), amt=1 ));
3084 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003085
drh734c9862008-11-28 15:37:20 +00003086 if( amt>0 ){
3087 if( wrote<0 ){
3088 /* lastErrno set by seekAndWrite */
3089 return SQLITE_IOERR_WRITE;
3090 }else{
dan08da86a2009-08-21 17:18:03 +00003091 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003092 return SQLITE_FULL;
3093 }
3094 }
dan6e09d692010-07-27 18:34:15 +00003095
drh734c9862008-11-28 15:37:20 +00003096 return SQLITE_OK;
3097}
3098
3099#ifdef SQLITE_TEST
3100/*
3101** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003102** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003103*/
3104int sqlite3_sync_count = 0;
3105int sqlite3_fullsync_count = 0;
3106#endif
3107
3108/*
drh89240432009-03-25 01:06:01 +00003109** We do not trust systems to provide a working fdatasync(). Some do.
3110** Others do no. To be safe, we will stick with the (slower) fsync().
3111** If you know that your system does support fdatasync() correctly,
3112** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003113*/
drh89240432009-03-25 01:06:01 +00003114#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003115# define fdatasync fsync
3116#endif
3117
3118/*
3119** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3120** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3121** only available on Mac OS X. But that could change.
3122*/
3123#ifdef F_FULLFSYNC
3124# define HAVE_FULLFSYNC 1
3125#else
3126# define HAVE_FULLFSYNC 0
3127#endif
3128
3129
3130/*
3131** The fsync() system call does not work as advertised on many
3132** unix systems. The following procedure is an attempt to make
3133** it work better.
3134**
3135** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3136** for testing when we want to run through the test suite quickly.
3137** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3138** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3139** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003140**
3141** SQLite sets the dataOnly flag if the size of the file is unchanged.
3142** The idea behind dataOnly is that it should only write the file content
3143** to disk, not the inode. We only set dataOnly if the file size is
3144** unchanged since the file size is part of the inode. However,
3145** Ted Ts'o tells us that fdatasync() will also write the inode if the
3146** file size has changed. The only real difference between fdatasync()
3147** and fsync(), Ted tells us, is that fdatasync() will not flush the
3148** inode if the mtime or owner or other inode attributes have changed.
3149** We only care about the file size, not the other file attributes, so
3150** as far as SQLite is concerned, an fdatasync() is always adequate.
3151** So, we always use fdatasync() if it is available, regardless of
3152** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003153*/
3154static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003155 int rc;
drh734c9862008-11-28 15:37:20 +00003156
3157 /* The following "ifdef/elif/else/" block has the same structure as
3158 ** the one below. It is replicated here solely to avoid cluttering
3159 ** up the real code with the UNUSED_PARAMETER() macros.
3160 */
3161#ifdef SQLITE_NO_SYNC
3162 UNUSED_PARAMETER(fd);
3163 UNUSED_PARAMETER(fullSync);
3164 UNUSED_PARAMETER(dataOnly);
3165#elif HAVE_FULLFSYNC
3166 UNUSED_PARAMETER(dataOnly);
3167#else
3168 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003169 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003170#endif
3171
3172 /* Record the number of times that we do a normal fsync() and
3173 ** FULLSYNC. This is used during testing to verify that this procedure
3174 ** gets called with the correct arguments.
3175 */
3176#ifdef SQLITE_TEST
3177 if( fullSync ) sqlite3_fullsync_count++;
3178 sqlite3_sync_count++;
3179#endif
3180
3181 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3182 ** no-op
3183 */
3184#ifdef SQLITE_NO_SYNC
3185 rc = SQLITE_OK;
3186#elif HAVE_FULLFSYNC
3187 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003188 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003189 }else{
3190 rc = 1;
3191 }
3192 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003193 ** It shouldn't be possible for fullfsync to fail on the local
3194 ** file system (on OSX), so failure indicates that FULLFSYNC
3195 ** isn't supported for this file system. So, attempt an fsync
3196 ** and (for now) ignore the overhead of a superfluous fcntl call.
3197 ** It'd be better to detect fullfsync support once and avoid
3198 ** the fcntl call every time sync is called.
3199 */
drh734c9862008-11-28 15:37:20 +00003200 if( rc ) rc = fsync(fd);
3201
drh7ed97b92010-01-20 13:07:21 +00003202#elif defined(__APPLE__)
3203 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3204 ** so currently we default to the macro that redefines fdatasync to fsync
3205 */
3206 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003207#else
drh0b647ff2009-03-21 14:41:04 +00003208 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003209#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003210 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003211 rc = fsync(fd);
3212 }
drh0b647ff2009-03-21 14:41:04 +00003213#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003214#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3215
3216 if( OS_VXWORKS && rc!= -1 ){
3217 rc = 0;
3218 }
chw97185482008-11-17 08:05:31 +00003219 return rc;
drhbfe66312006-10-03 17:40:40 +00003220}
3221
drh734c9862008-11-28 15:37:20 +00003222/*
3223** Make sure all writes to a particular file are committed to disk.
3224**
3225** If dataOnly==0 then both the file itself and its metadata (file
3226** size, access time, etc) are synced. If dataOnly!=0 then only the
3227** file data is synced.
3228**
3229** Under Unix, also make sure that the directory entry for the file
3230** has been created by fsync-ing the directory that contains the file.
3231** If we do not do this and we encounter a power failure, the directory
3232** entry for the journal might not exist after we reboot. The next
3233** SQLite to access the file will not know that the journal exists (because
3234** the directory entry for the journal was never created) and the transaction
3235** will not roll back - possibly leading to database corruption.
3236*/
3237static int unixSync(sqlite3_file *id, int flags){
3238 int rc;
3239 unixFile *pFile = (unixFile*)id;
3240
3241 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3242 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3243
3244 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3245 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3246 || (flags&0x0F)==SQLITE_SYNC_FULL
3247 );
3248
3249 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3250 ** line is to test that doing so does not cause any problems.
3251 */
3252 SimulateDiskfullError( return SQLITE_FULL );
3253
3254 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003255 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003256 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3257 SimulateIOError( rc=1 );
3258 if( rc ){
3259 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003260 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003261 }
3262 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003263 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3264 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003265#ifndef SQLITE_DISABLE_DIRSYNC
3266 /* The directory sync is only attempted if full_fsync is
3267 ** turned off or unavailable. If a full_fsync occurred above,
3268 ** then the directory sync is superfluous.
3269 */
3270 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3271 /*
3272 ** We have received multiple reports of fsync() returning
3273 ** errors when applied to directories on certain file systems.
3274 ** A failed directory sync is not a big deal. So it seems
3275 ** better to ignore the error. Ticket #1657
3276 */
3277 /* pFile->lastErrno = errno; */
3278 /* return SQLITE_IOERR; */
3279 }
3280#endif
drh0e9365c2011-03-02 02:08:13 +00003281 /* Only need to sync once, so close the directory when we are done */
3282 robust_close(pFile, pFile->dirfd, __LINE__);
3283 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003284 }
3285 return rc;
3286}
3287
3288/*
3289** Truncate an open file to a specified size
3290*/
3291static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003292 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003293 int rc;
dan6e09d692010-07-27 18:34:15 +00003294 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003295 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003296
3297 /* If the user has configured a chunk-size for this file, truncate the
3298 ** file so that it consists of an integer number of chunks (i.e. the
3299 ** actual file size after the operation may be larger than the requested
3300 ** size).
3301 */
3302 if( pFile->szChunk ){
3303 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3304 }
3305
drhff812312011-02-23 13:33:46 +00003306 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003307 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003308 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003309 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003310 }else{
drh3313b142009-11-06 04:13:18 +00003311#ifndef NDEBUG
3312 /* If we are doing a normal write to a database file (as opposed to
3313 ** doing a hot-journal rollback or a write to some file other than a
3314 ** normal database file) and we truncate the file to zero length,
3315 ** that effectively updates the change counter. This might happen
3316 ** when restoring a database using the backup API from a zero-length
3317 ** source.
3318 */
dan6e09d692010-07-27 18:34:15 +00003319 if( pFile->inNormalWrite && nByte==0 ){
3320 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003321 }
3322#endif
3323
drh734c9862008-11-28 15:37:20 +00003324 return SQLITE_OK;
3325 }
3326}
3327
3328/*
3329** Determine the current size of a file in bytes
3330*/
3331static int unixFileSize(sqlite3_file *id, i64 *pSize){
3332 int rc;
3333 struct stat buf;
3334 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003335 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003336 SimulateIOError( rc=1 );
3337 if( rc!=0 ){
3338 ((unixFile*)id)->lastErrno = errno;
3339 return SQLITE_IOERR_FSTAT;
3340 }
3341 *pSize = buf.st_size;
3342
drh8af6c222010-05-14 12:43:01 +00003343 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003344 ** writes a single byte into that file in order to work around a bug
3345 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3346 ** layers, we need to report this file size as zero even though it is
3347 ** really 1. Ticket #3260.
3348 */
3349 if( *pSize==1 ) *pSize = 0;
3350
3351
3352 return SQLITE_OK;
3353}
3354
drhd2cb50b2009-01-09 21:41:17 +00003355#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003356/*
3357** Handler for proxy-locking file-control verbs. Defined below in the
3358** proxying locking division.
3359*/
3360static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003361#endif
drh715ff302008-12-03 22:32:44 +00003362
dan502019c2010-07-28 14:26:17 +00003363/*
3364** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3365** file-control operation.
3366**
3367** If the user has configured a chunk-size for this file, it could be
3368** that the file needs to be extended at this point. Otherwise, the
3369** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3370*/
3371static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3372 if( pFile->szChunk ){
3373 i64 nSize; /* Required file size */
3374 struct stat buf; /* Used to hold return values of fstat() */
3375
drh99ab3b12011-03-02 15:09:07 +00003376 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003377
3378 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3379 if( nSize>(i64)buf.st_size ){
3380#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003381 int rc;
3382 do{
drhe562be52011-03-02 18:01:10 +00003383 rc = osFallocate(pFile->.h, buf.st_size, nSize-buf.st_size;
drhff812312011-02-23 13:33:46 +00003384 }while( rc<0 && errno=EINTR );
3385 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003386#else
3387 /* If the OS does not have posix_fallocate(), fake it. First use
3388 ** ftruncate() to set the file size, then write a single byte to
3389 ** the last byte in each block within the extended region. This
3390 ** is the same technique used by glibc to implement posix_fallocate()
3391 ** on systems that do not have a real fallocate() system call.
3392 */
3393 int nBlk = buf.st_blksize; /* File-system block size */
3394 i64 iWrite; /* Next offset to write to */
3395 int nWrite; /* Return value from seekAndWrite() */
3396
drhff812312011-02-23 13:33:46 +00003397 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003398 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003399 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003400 }
3401 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3402 do {
3403 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3404 iWrite += nBlk;
3405 } while( nWrite==1 && iWrite<nSize );
3406 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3407#endif
3408 }
3409 }
3410
3411 return SQLITE_OK;
3412}
danielk1977ad94b582007-08-20 06:44:22 +00003413
danielk1977e3026632004-06-22 11:29:02 +00003414/*
drh9e33c2c2007-08-31 18:34:59 +00003415** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003416*/
drhcc6bb3e2007-08-31 16:11:35 +00003417static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003418 switch( op ){
3419 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003420 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003421 return SQLITE_OK;
3422 }
drh7708e972008-11-29 00:56:52 +00003423 case SQLITE_LAST_ERRNO: {
3424 *(int*)pArg = ((unixFile*)id)->lastErrno;
3425 return SQLITE_OK;
3426 }
dan6e09d692010-07-27 18:34:15 +00003427 case SQLITE_FCNTL_CHUNK_SIZE: {
3428 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003429 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003430 }
drh9ff27ec2010-05-19 19:26:05 +00003431 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003432 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003433 }
drh8f941bc2009-01-14 23:03:40 +00003434#ifndef NDEBUG
3435 /* The pager calls this method to signal that it has done
3436 ** a rollback and that the database is therefore unchanged and
3437 ** it hence it is OK for the transaction change counter to be
3438 ** unchanged.
3439 */
3440 case SQLITE_FCNTL_DB_UNCHANGED: {
3441 ((unixFile*)id)->dbUpdate = 0;
3442 return SQLITE_OK;
3443 }
3444#endif
drhd2cb50b2009-01-09 21:41:17 +00003445#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003446 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003447 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003448 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003449 }
drhd2cb50b2009-01-09 21:41:17 +00003450#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003451 case SQLITE_FCNTL_SYNC_OMITTED: {
3452 return SQLITE_OK; /* A no-op */
3453 }
drh9e33c2c2007-08-31 18:34:59 +00003454 }
drh0b52b7d2011-01-26 19:46:22 +00003455 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003456}
3457
3458/*
danielk1977a3d4c882007-03-23 10:08:38 +00003459** Return the sector size in bytes of the underlying block device for
3460** the specified file. This is almost always 512 bytes, but may be
3461** larger for some devices.
3462**
3463** SQLite code assumes this function cannot fail. It also assumes that
3464** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003465** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003466** same for both.
3467*/
danielk1977397d65f2008-11-19 11:35:39 +00003468static int unixSectorSize(sqlite3_file *NotUsed){
3469 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003470 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003471}
3472
danielk197790949c22007-08-17 16:50:38 +00003473/*
danielk1977397d65f2008-11-19 11:35:39 +00003474** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003475*/
danielk1977397d65f2008-11-19 11:35:39 +00003476static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3477 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003478 return 0;
3479}
3480
drhd9e5c4f2010-05-12 18:01:39 +00003481#ifndef SQLITE_OMIT_WAL
3482
3483
3484/*
drhd91c68f2010-05-14 14:52:25 +00003485** Object used to represent an shared memory buffer.
3486**
3487** When multiple threads all reference the same wal-index, each thread
3488** has its own unixShm object, but they all point to a single instance
3489** of this unixShmNode object. In other words, each wal-index is opened
3490** only once per process.
3491**
3492** Each unixShmNode object is connected to a single unixInodeInfo object.
3493** We could coalesce this object into unixInodeInfo, but that would mean
3494** every open file that does not use shared memory (in other words, most
3495** open files) would have to carry around this extra information. So
3496** the unixInodeInfo object contains a pointer to this unixShmNode object
3497** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003498**
3499** unixMutexHeld() must be true when creating or destroying
3500** this object or while reading or writing the following fields:
3501**
3502** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003503**
3504** The following fields are read-only after the object is created:
3505**
3506** fid
3507** zFilename
3508**
drhd91c68f2010-05-14 14:52:25 +00003509** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003510** unixMutexHeld() is true when reading or writing any other field
3511** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003512*/
drhd91c68f2010-05-14 14:52:25 +00003513struct unixShmNode {
3514 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003515 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003516 char *zFilename; /* Name of the mmapped file */
3517 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003518 int szRegion; /* Size of shared-memory regions */
3519 int nRegion; /* Size of array apRegion */
3520 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003521 int nRef; /* Number of unixShm objects pointing to this */
3522 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003523#ifdef SQLITE_DEBUG
3524 u8 exclMask; /* Mask of exclusive locks held */
3525 u8 sharedMask; /* Mask of shared locks held */
3526 u8 nextShmId; /* Next available unixShm.id value */
3527#endif
3528};
3529
3530/*
drhd9e5c4f2010-05-12 18:01:39 +00003531** Structure used internally by this VFS to record the state of an
3532** open shared memory connection.
3533**
drhd91c68f2010-05-14 14:52:25 +00003534** The following fields are initialized when this object is created and
3535** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003536**
drhd91c68f2010-05-14 14:52:25 +00003537** unixShm.pFile
3538** unixShm.id
3539**
3540** All other fields are read/write. The unixShm.pFile->mutex must be held
3541** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003542*/
3543struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003544 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3545 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003546 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003547 u16 sharedMask; /* Mask of shared locks held */
3548 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003549#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003550 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003551#endif
3552};
3553
3554/*
drhd9e5c4f2010-05-12 18:01:39 +00003555** Constants used for locking
3556*/
drhbd9676c2010-06-23 17:58:38 +00003557#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003558#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003559
drhd9e5c4f2010-05-12 18:01:39 +00003560/*
drh73b64e42010-05-30 19:55:15 +00003561** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003562**
3563** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3564** otherwise.
3565*/
3566static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003567 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3568 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003569 int ofst, /* First byte of the locking range */
3570 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003571){
3572 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003573 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003574
drhd91c68f2010-05-14 14:52:25 +00003575 /* Access to the unixShmNode object is serialized by the caller */
3576 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003577
drh73b64e42010-05-30 19:55:15 +00003578 /* Shared locks never span more than one byte */
3579 assert( n==1 || lockType!=F_RDLCK );
3580
3581 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003582 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003583
drh3cb93392011-03-12 18:10:44 +00003584 if( pShmNode->h>=0 ){
3585 /* Initialize the locking parameters */
3586 memset(&f, 0, sizeof(f));
3587 f.l_type = lockType;
3588 f.l_whence = SEEK_SET;
3589 f.l_start = ofst;
3590 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003591
drh3cb93392011-03-12 18:10:44 +00003592 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3593 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3594 }
drhd9e5c4f2010-05-12 18:01:39 +00003595
3596 /* Update the global lock state and do debug tracing */
3597#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003598 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003599 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003600 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003601 if( rc==SQLITE_OK ){
3602 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003603 OSTRACE(("unlock %d ok", ofst));
3604 pShmNode->exclMask &= ~mask;
3605 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003606 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003607 OSTRACE(("read-lock %d ok", ofst));
3608 pShmNode->exclMask &= ~mask;
3609 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003610 }else{
3611 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003612 OSTRACE(("write-lock %d ok", ofst));
3613 pShmNode->exclMask |= mask;
3614 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003615 }
3616 }else{
3617 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003618 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003619 }else if( lockType==F_RDLCK ){
3620 OSTRACE(("read-lock failed"));
3621 }else{
3622 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003623 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003624 }
3625 }
drh20e1f082010-05-31 16:10:12 +00003626 OSTRACE((" - afterwards %03x,%03x\n",
3627 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003628 }
drhd9e5c4f2010-05-12 18:01:39 +00003629#endif
3630
3631 return rc;
3632}
3633
drhd9e5c4f2010-05-12 18:01:39 +00003634
3635/*
drhd91c68f2010-05-14 14:52:25 +00003636** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003637**
3638** This is not a VFS shared-memory method; it is a utility function called
3639** by VFS shared-memory methods.
3640*/
drhd91c68f2010-05-14 14:52:25 +00003641static void unixShmPurge(unixFile *pFd){
3642 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003643 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003644 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003645 int i;
drhd91c68f2010-05-14 14:52:25 +00003646 assert( p->pInode==pFd->pInode );
3647 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003648 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003649 if( p->h>=0 ){
3650 munmap(p->apRegion[i], p->szRegion);
3651 }else{
3652 sqlite3_free(p->apRegion[i]);
3653 }
dan13a3cb82010-06-11 19:04:21 +00003654 }
dan18801912010-06-14 14:07:50 +00003655 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003656 if( p->h>=0 ){
3657 robust_close(pFd, p->h, __LINE__);
3658 p->h = -1;
3659 }
drhd91c68f2010-05-14 14:52:25 +00003660 p->pInode->pShmNode = 0;
3661 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003662 }
3663}
3664
3665/*
danda9fe0c2010-07-13 18:44:03 +00003666** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003667** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003668**
drh7234c6d2010-06-19 15:10:09 +00003669** The file used to implement shared-memory is in the same directory
3670** as the open database file and has the same name as the open database
3671** file with the "-shm" suffix added. For example, if the database file
3672** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003673** for shared memory will be called "/home/user1/config.db-shm".
3674**
3675** Another approach to is to use files in /dev/shm or /dev/tmp or an
3676** some other tmpfs mount. But if a file in a different directory
3677** from the database file is used, then differing access permissions
3678** or a chroot() might cause two different processes on the same
3679** database to end up using different files for shared memory -
3680** meaning that their memory would not really be shared - resulting
3681** in database corruption. Nevertheless, this tmpfs file usage
3682** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3683** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3684** option results in an incompatible build of SQLite; builds of SQLite
3685** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3686** same database file at the same time, database corruption will likely
3687** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3688** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003689**
3690** When opening a new shared-memory file, if no other instances of that
3691** file are currently open, in this process or in other processes, then
3692** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003693**
3694** If the original database file (pDbFd) is using the "unix-excl" VFS
3695** that means that an exclusive lock is held on the database file and
3696** that no other processes are able to read or write the database. In
3697** that case, we do not really need shared memory. No shared memory
3698** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003699*/
danda9fe0c2010-07-13 18:44:03 +00003700static int unixOpenSharedMemory(unixFile *pDbFd){
3701 struct unixShm *p = 0; /* The connection to be opened */
3702 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3703 int rc; /* Result code */
3704 unixInodeInfo *pInode; /* The inode of fd */
3705 char *zShmFilename; /* Name of the file used for SHM */
3706 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003707
danda9fe0c2010-07-13 18:44:03 +00003708 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003709 p = sqlite3_malloc( sizeof(*p) );
3710 if( p==0 ) return SQLITE_NOMEM;
3711 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003712 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003713
danda9fe0c2010-07-13 18:44:03 +00003714 /* Check to see if a unixShmNode object already exists. Reuse an existing
3715 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003716 */
3717 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003718 pInode = pDbFd->pInode;
3719 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003720 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003721 struct stat sStat; /* fstat() info for database file */
3722
3723 /* Call fstat() to figure out the permissions on the database file. If
3724 ** a new *-shm file is created, an attempt will be made to create it
3725 ** with the same permissions. The actual permissions the file is created
3726 ** with are subject to the current umask setting.
3727 */
drh3cb93392011-03-12 18:10:44 +00003728 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003729 rc = SQLITE_IOERR_FSTAT;
3730 goto shm_open_err;
3731 }
3732
drha4ced192010-07-15 18:32:40 +00003733#ifdef SQLITE_SHM_DIRECTORY
3734 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3735#else
drh7234c6d2010-06-19 15:10:09 +00003736 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003737#endif
drh7234c6d2010-06-19 15:10:09 +00003738 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003739 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003740 rc = SQLITE_NOMEM;
3741 goto shm_open_err;
3742 }
drhd91c68f2010-05-14 14:52:25 +00003743 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003744 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003745#ifdef SQLITE_SHM_DIRECTORY
3746 sqlite3_snprintf(nShmFilename, zShmFilename,
3747 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3748 (u32)sStat.st_ino, (u32)sStat.st_dev);
3749#else
drh7234c6d2010-06-19 15:10:09 +00003750 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003751#endif
drhd91c68f2010-05-14 14:52:25 +00003752 pShmNode->h = -1;
3753 pDbFd->pInode->pShmNode = pShmNode;
3754 pShmNode->pInode = pDbFd->pInode;
3755 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3756 if( pShmNode->mutex==0 ){
3757 rc = SQLITE_NOMEM;
3758 goto shm_open_err;
3759 }
drhd9e5c4f2010-05-12 18:01:39 +00003760
drh3cb93392011-03-12 18:10:44 +00003761 if( pInode->bProcessLock==0 ){
3762 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3763 (sStat.st_mode & 0777));
3764 if( pShmNode->h<0 ){
3765 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3766 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003767 }
drh3cb93392011-03-12 18:10:44 +00003768
3769 /* Check to see if another process is holding the dead-man switch.
3770 ** If not, truncate the file to zero length.
3771 */
3772 rc = SQLITE_OK;
3773 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3774 if( robust_ftruncate(pShmNode->h, 0) ){
3775 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3776 }
3777 }
3778 if( rc==SQLITE_OK ){
3779 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3780 }
3781 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003782 }
drhd9e5c4f2010-05-12 18:01:39 +00003783 }
3784
drhd91c68f2010-05-14 14:52:25 +00003785 /* Make the new connection a child of the unixShmNode */
3786 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003787#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003788 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003789#endif
drhd91c68f2010-05-14 14:52:25 +00003790 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003791 pDbFd->pShm = p;
3792 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003793
3794 /* The reference count on pShmNode has already been incremented under
3795 ** the cover of the unixEnterMutex() mutex and the pointer from the
3796 ** new (struct unixShm) object to the pShmNode has been set. All that is
3797 ** left to do is to link the new object into the linked list starting
3798 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3799 ** mutex.
3800 */
3801 sqlite3_mutex_enter(pShmNode->mutex);
3802 p->pNext = pShmNode->pFirst;
3803 pShmNode->pFirst = p;
3804 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003805 return SQLITE_OK;
3806
3807 /* Jump here on any error */
3808shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003809 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003810 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003811 unixLeaveMutex();
3812 return rc;
3813}
3814
3815/*
danda9fe0c2010-07-13 18:44:03 +00003816** This function is called to obtain a pointer to region iRegion of the
3817** shared-memory associated with the database file fd. Shared-memory regions
3818** are numbered starting from zero. Each shared-memory region is szRegion
3819** bytes in size.
3820**
3821** If an error occurs, an error code is returned and *pp is set to NULL.
3822**
3823** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3824** region has not been allocated (by any client, including one running in a
3825** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3826** bExtend is non-zero and the requested shared-memory region has not yet
3827** been allocated, it is allocated by this function.
3828**
3829** If the shared-memory region has already been allocated or is allocated by
3830** this call as described above, then it is mapped into this processes
3831** address space (if it is not already), *pp is set to point to the mapped
3832** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003833*/
danda9fe0c2010-07-13 18:44:03 +00003834static int unixShmMap(
3835 sqlite3_file *fd, /* Handle open on database file */
3836 int iRegion, /* Region to retrieve */
3837 int szRegion, /* Size of regions */
3838 int bExtend, /* True to extend file if necessary */
3839 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003840){
danda9fe0c2010-07-13 18:44:03 +00003841 unixFile *pDbFd = (unixFile*)fd;
3842 unixShm *p;
3843 unixShmNode *pShmNode;
3844 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003845
danda9fe0c2010-07-13 18:44:03 +00003846 /* If the shared-memory file has not yet been opened, open it now. */
3847 if( pDbFd->pShm==0 ){
3848 rc = unixOpenSharedMemory(pDbFd);
3849 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003850 }
drhd9e5c4f2010-05-12 18:01:39 +00003851
danda9fe0c2010-07-13 18:44:03 +00003852 p = pDbFd->pShm;
3853 pShmNode = p->pShmNode;
3854 sqlite3_mutex_enter(pShmNode->mutex);
3855 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003856 assert( pShmNode->pInode==pDbFd->pInode );
3857 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3858 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003859
3860 if( pShmNode->nRegion<=iRegion ){
3861 char **apNew; /* New apRegion[] array */
3862 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3863 struct stat sStat; /* Used by fstat() */
3864
3865 pShmNode->szRegion = szRegion;
3866
drh3cb93392011-03-12 18:10:44 +00003867 if( pShmNode->h>=0 ){
3868 /* The requested region is not mapped into this processes address space.
3869 ** Check to see if it has been allocated (i.e. if the wal-index file is
3870 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003871 */
drh3cb93392011-03-12 18:10:44 +00003872 if( osFstat(pShmNode->h, &sStat) ){
3873 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003874 goto shmpage_out;
3875 }
drh3cb93392011-03-12 18:10:44 +00003876
3877 if( sStat.st_size<nByte ){
3878 /* The requested memory region does not exist. If bExtend is set to
3879 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3880 **
3881 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3882 ** the requested memory region.
3883 */
3884 if( !bExtend ) goto shmpage_out;
3885 if( robust_ftruncate(pShmNode->h, nByte) ){
3886 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3887 pShmNode->zFilename);
3888 goto shmpage_out;
3889 }
3890 }
danda9fe0c2010-07-13 18:44:03 +00003891 }
3892
3893 /* Map the requested memory region into this processes address space. */
3894 apNew = (char **)sqlite3_realloc(
3895 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3896 );
3897 if( !apNew ){
3898 rc = SQLITE_IOERR_NOMEM;
3899 goto shmpage_out;
3900 }
3901 pShmNode->apRegion = apNew;
3902 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003903 void *pMem;
3904 if( pShmNode->h>=0 ){
3905 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3906 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3907 );
3908 if( pMem==MAP_FAILED ){
3909 rc = SQLITE_IOERR;
3910 goto shmpage_out;
3911 }
3912 }else{
3913 pMem = sqlite3_malloc(szRegion);
3914 if( pMem==0 ){
3915 rc = SQLITE_NOMEM;
3916 goto shmpage_out;
3917 }
3918 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003919 }
3920 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3921 pShmNode->nRegion++;
3922 }
3923 }
3924
3925shmpage_out:
3926 if( pShmNode->nRegion>iRegion ){
3927 *pp = pShmNode->apRegion[iRegion];
3928 }else{
3929 *pp = 0;
3930 }
3931 sqlite3_mutex_leave(pShmNode->mutex);
3932 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003933}
3934
3935/*
drhd9e5c4f2010-05-12 18:01:39 +00003936** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003937**
3938** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3939** different here than in posix. In xShmLock(), one can go from unlocked
3940** to shared and back or from unlocked to exclusive and back. But one may
3941** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003942*/
3943static int unixShmLock(
3944 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003945 int ofst, /* First lock to acquire or release */
3946 int n, /* Number of locks to acquire or release */
3947 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003948){
drh73b64e42010-05-30 19:55:15 +00003949 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3950 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3951 unixShm *pX; /* For looping over all siblings */
3952 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3953 int rc = SQLITE_OK; /* Result code */
3954 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003955
drhd91c68f2010-05-14 14:52:25 +00003956 assert( pShmNode==pDbFd->pInode->pShmNode );
3957 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003958 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003959 assert( n>=1 );
3960 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3961 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3962 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3963 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3964 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003965 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3966 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003967
drhc99597c2010-05-31 01:41:15 +00003968 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003969 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003970 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003971 if( flags & SQLITE_SHM_UNLOCK ){
3972 u16 allMask = 0; /* Mask of locks held by siblings */
3973
3974 /* See if any siblings hold this same lock */
3975 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3976 if( pX==p ) continue;
3977 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3978 allMask |= pX->sharedMask;
3979 }
3980
3981 /* Unlock the system-level locks */
3982 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003983 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003984 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003985 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003986 }
drh73b64e42010-05-30 19:55:15 +00003987
3988 /* Undo the local locks */
3989 if( rc==SQLITE_OK ){
3990 p->exclMask &= ~mask;
3991 p->sharedMask &= ~mask;
3992 }
3993 }else if( flags & SQLITE_SHM_SHARED ){
3994 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3995
3996 /* Find out which shared locks are already held by sibling connections.
3997 ** If any sibling already holds an exclusive lock, go ahead and return
3998 ** SQLITE_BUSY.
3999 */
4000 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004001 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004002 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004003 break;
4004 }
4005 allShared |= pX->sharedMask;
4006 }
4007
4008 /* Get shared locks at the system level, if necessary */
4009 if( rc==SQLITE_OK ){
4010 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004011 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004012 }else{
drh73b64e42010-05-30 19:55:15 +00004013 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004014 }
drhd9e5c4f2010-05-12 18:01:39 +00004015 }
drh73b64e42010-05-30 19:55:15 +00004016
4017 /* Get the local shared locks */
4018 if( rc==SQLITE_OK ){
4019 p->sharedMask |= mask;
4020 }
4021 }else{
4022 /* Make sure no sibling connections hold locks that will block this
4023 ** lock. If any do, return SQLITE_BUSY right away.
4024 */
4025 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004026 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4027 rc = SQLITE_BUSY;
4028 break;
4029 }
4030 }
4031
4032 /* Get the exclusive locks at the system level. Then if successful
4033 ** also mark the local connection as being locked.
4034 */
4035 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004036 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004037 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004038 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004039 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004040 }
drhd9e5c4f2010-05-12 18:01:39 +00004041 }
4042 }
drhd91c68f2010-05-14 14:52:25 +00004043 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004044 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4045 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004046 return rc;
4047}
4048
drh286a2882010-05-20 23:51:06 +00004049/*
4050** Implement a memory barrier or memory fence on shared memory.
4051**
4052** All loads and stores begun before the barrier must complete before
4053** any load or store begun after the barrier.
4054*/
4055static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004056 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004057){
drhff828942010-06-26 21:34:06 +00004058 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004059 unixEnterMutex();
4060 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004061}
4062
dan18801912010-06-14 14:07:50 +00004063/*
danda9fe0c2010-07-13 18:44:03 +00004064** Close a connection to shared-memory. Delete the underlying
4065** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004066**
4067** If there is no shared memory associated with the connection then this
4068** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004069*/
danda9fe0c2010-07-13 18:44:03 +00004070static int unixShmUnmap(
4071 sqlite3_file *fd, /* The underlying database file */
4072 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004073){
danda9fe0c2010-07-13 18:44:03 +00004074 unixShm *p; /* The connection to be closed */
4075 unixShmNode *pShmNode; /* The underlying shared-memory file */
4076 unixShm **pp; /* For looping over sibling connections */
4077 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004078
danda9fe0c2010-07-13 18:44:03 +00004079 pDbFd = (unixFile*)fd;
4080 p = pDbFd->pShm;
4081 if( p==0 ) return SQLITE_OK;
4082 pShmNode = p->pShmNode;
4083
4084 assert( pShmNode==pDbFd->pInode->pShmNode );
4085 assert( pShmNode->pInode==pDbFd->pInode );
4086
4087 /* Remove connection p from the set of connections associated
4088 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004089 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004090 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4091 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004092
danda9fe0c2010-07-13 18:44:03 +00004093 /* Free the connection p */
4094 sqlite3_free(p);
4095 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004096 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004097
4098 /* If pShmNode->nRef has reached 0, then close the underlying
4099 ** shared-memory file, too */
4100 unixEnterMutex();
4101 assert( pShmNode->nRef>0 );
4102 pShmNode->nRef--;
4103 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004104 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004105 unixShmPurge(pDbFd);
4106 }
4107 unixLeaveMutex();
4108
4109 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004110}
drh286a2882010-05-20 23:51:06 +00004111
danda9fe0c2010-07-13 18:44:03 +00004112
drhd9e5c4f2010-05-12 18:01:39 +00004113#else
drh6b017cc2010-06-14 18:01:46 +00004114# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004115# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004116# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004117# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004118#endif /* #ifndef SQLITE_OMIT_WAL */
4119
drh734c9862008-11-28 15:37:20 +00004120/*
4121** Here ends the implementation of all sqlite3_file methods.
4122**
4123********************** End sqlite3_file Methods *******************************
4124******************************************************************************/
4125
4126/*
drh6b9d6dd2008-12-03 19:34:47 +00004127** This division contains definitions of sqlite3_io_methods objects that
4128** implement various file locking strategies. It also contains definitions
4129** of "finder" functions. A finder-function is used to locate the appropriate
4130** sqlite3_io_methods object for a particular database file. The pAppData
4131** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4132** the correct finder-function for that VFS.
4133**
4134** Most finder functions return a pointer to a fixed sqlite3_io_methods
4135** object. The only interesting finder-function is autolockIoFinder, which
4136** looks at the filesystem type and tries to guess the best locking
4137** strategy from that.
4138**
drh1875f7a2008-12-08 18:19:17 +00004139** For finder-funtion F, two objects are created:
4140**
4141** (1) The real finder-function named "FImpt()".
4142**
dane946c392009-08-22 11:39:46 +00004143** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004144**
4145**
4146** A pointer to the F pointer is used as the pAppData value for VFS
4147** objects. We have to do this instead of letting pAppData point
4148** directly at the finder-function since C90 rules prevent a void*
4149** from be cast into a function pointer.
4150**
drh6b9d6dd2008-12-03 19:34:47 +00004151**
drh7708e972008-11-29 00:56:52 +00004152** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004153**
drh7708e972008-11-29 00:56:52 +00004154** * A constant sqlite3_io_methods object call METHOD that has locking
4155** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4156**
4157** * An I/O method finder function called FINDER that returns a pointer
4158** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004159*/
drhd9e5c4f2010-05-12 18:01:39 +00004160#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004161static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004162 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004163 CLOSE, /* xClose */ \
4164 unixRead, /* xRead */ \
4165 unixWrite, /* xWrite */ \
4166 unixTruncate, /* xTruncate */ \
4167 unixSync, /* xSync */ \
4168 unixFileSize, /* xFileSize */ \
4169 LOCK, /* xLock */ \
4170 UNLOCK, /* xUnlock */ \
4171 CKLOCK, /* xCheckReservedLock */ \
4172 unixFileControl, /* xFileControl */ \
4173 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004174 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004175 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004176 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004177 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004178 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004179}; \
drh0c2694b2009-09-03 16:23:44 +00004180static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4181 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004182 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004183} \
drh0c2694b2009-09-03 16:23:44 +00004184static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004185 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004186
4187/*
4188** Here are all of the sqlite3_io_methods objects for each of the
4189** locking strategies. Functions that return pointers to these methods
4190** are also created.
4191*/
4192IOMETHODS(
4193 posixIoFinder, /* Finder function name */
4194 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004195 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004196 unixClose, /* xClose method */
4197 unixLock, /* xLock method */
4198 unixUnlock, /* xUnlock method */
4199 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004200)
drh7708e972008-11-29 00:56:52 +00004201IOMETHODS(
4202 nolockIoFinder, /* Finder function name */
4203 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004204 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004205 nolockClose, /* xClose method */
4206 nolockLock, /* xLock method */
4207 nolockUnlock, /* xUnlock method */
4208 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004209)
drh7708e972008-11-29 00:56:52 +00004210IOMETHODS(
4211 dotlockIoFinder, /* Finder function name */
4212 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004213 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004214 dotlockClose, /* xClose method */
4215 dotlockLock, /* xLock method */
4216 dotlockUnlock, /* xUnlock method */
4217 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004218)
drh7708e972008-11-29 00:56:52 +00004219
chw78a13182009-04-07 05:35:03 +00004220#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004221IOMETHODS(
4222 flockIoFinder, /* Finder function name */
4223 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004224 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004225 flockClose, /* xClose method */
4226 flockLock, /* xLock method */
4227 flockUnlock, /* xUnlock method */
4228 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004229)
drh7708e972008-11-29 00:56:52 +00004230#endif
4231
drh6c7d5c52008-11-21 20:32:33 +00004232#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004233IOMETHODS(
4234 semIoFinder, /* Finder function name */
4235 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004236 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004237 semClose, /* xClose method */
4238 semLock, /* xLock method */
4239 semUnlock, /* xUnlock method */
4240 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004241)
aswiftaebf4132008-11-21 00:10:35 +00004242#endif
drh7708e972008-11-29 00:56:52 +00004243
drhd2cb50b2009-01-09 21:41:17 +00004244#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004245IOMETHODS(
4246 afpIoFinder, /* Finder function name */
4247 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004248 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004249 afpClose, /* xClose method */
4250 afpLock, /* xLock method */
4251 afpUnlock, /* xUnlock method */
4252 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004253)
drh715ff302008-12-03 22:32:44 +00004254#endif
4255
4256/*
4257** The proxy locking method is a "super-method" in the sense that it
4258** opens secondary file descriptors for the conch and lock files and
4259** it uses proxy, dot-file, AFP, and flock() locking methods on those
4260** secondary files. For this reason, the division that implements
4261** proxy locking is located much further down in the file. But we need
4262** to go ahead and define the sqlite3_io_methods and finder function
4263** for proxy locking here. So we forward declare the I/O methods.
4264*/
drhd2cb50b2009-01-09 21:41:17 +00004265#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004266static int proxyClose(sqlite3_file*);
4267static int proxyLock(sqlite3_file*, int);
4268static int proxyUnlock(sqlite3_file*, int);
4269static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004270IOMETHODS(
4271 proxyIoFinder, /* Finder function name */
4272 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004273 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004274 proxyClose, /* xClose method */
4275 proxyLock, /* xLock method */
4276 proxyUnlock, /* xUnlock method */
4277 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004278)
aswiftaebf4132008-11-21 00:10:35 +00004279#endif
drh7708e972008-11-29 00:56:52 +00004280
drh7ed97b92010-01-20 13:07:21 +00004281/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4282#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4283IOMETHODS(
4284 nfsIoFinder, /* Finder function name */
4285 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004286 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004287 unixClose, /* xClose method */
4288 unixLock, /* xLock method */
4289 nfsUnlock, /* xUnlock method */
4290 unixCheckReservedLock /* xCheckReservedLock method */
4291)
4292#endif
drh7708e972008-11-29 00:56:52 +00004293
drhd2cb50b2009-01-09 21:41:17 +00004294#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004295/*
drh6b9d6dd2008-12-03 19:34:47 +00004296** This "finder" function attempts to determine the best locking strategy
4297** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004298** object that implements that strategy.
4299**
4300** This is for MacOSX only.
4301*/
drh1875f7a2008-12-08 18:19:17 +00004302static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004303 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004304 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004305){
4306 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004307 const char *zFilesystem; /* Filesystem type name */
4308 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004309 } aMap[] = {
4310 { "hfs", &posixIoMethods },
4311 { "ufs", &posixIoMethods },
4312 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004313 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004314 { "webdav", &nolockIoMethods },
4315 { 0, 0 }
4316 };
4317 int i;
4318 struct statfs fsInfo;
4319 struct flock lockInfo;
4320
4321 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004322 /* If filePath==NULL that means we are dealing with a transient file
4323 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004324 return &nolockIoMethods;
4325 }
4326 if( statfs(filePath, &fsInfo) != -1 ){
4327 if( fsInfo.f_flags & MNT_RDONLY ){
4328 return &nolockIoMethods;
4329 }
4330 for(i=0; aMap[i].zFilesystem; i++){
4331 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4332 return aMap[i].pMethods;
4333 }
4334 }
4335 }
4336
4337 /* Default case. Handles, amongst others, "nfs".
4338 ** Test byte-range lock using fcntl(). If the call succeeds,
4339 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004340 */
drh7708e972008-11-29 00:56:52 +00004341 lockInfo.l_len = 1;
4342 lockInfo.l_start = 0;
4343 lockInfo.l_whence = SEEK_SET;
4344 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004345 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004346 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4347 return &nfsIoMethods;
4348 } else {
4349 return &posixIoMethods;
4350 }
drh7708e972008-11-29 00:56:52 +00004351 }else{
4352 return &dotlockIoMethods;
4353 }
4354}
drh0c2694b2009-09-03 16:23:44 +00004355static const sqlite3_io_methods
4356 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004357
drhd2cb50b2009-01-09 21:41:17 +00004358#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004359
chw78a13182009-04-07 05:35:03 +00004360#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4361/*
4362** This "finder" function attempts to determine the best locking strategy
4363** for the database file "filePath". It then returns the sqlite3_io_methods
4364** object that implements that strategy.
4365**
4366** This is for VXWorks only.
4367*/
4368static const sqlite3_io_methods *autolockIoFinderImpl(
4369 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004370 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004371){
4372 struct flock lockInfo;
4373
4374 if( !filePath ){
4375 /* If filePath==NULL that means we are dealing with a transient file
4376 ** that does not need to be locked. */
4377 return &nolockIoMethods;
4378 }
4379
4380 /* Test if fcntl() is supported and use POSIX style locks.
4381 ** Otherwise fall back to the named semaphore method.
4382 */
4383 lockInfo.l_len = 1;
4384 lockInfo.l_start = 0;
4385 lockInfo.l_whence = SEEK_SET;
4386 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004387 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004388 return &posixIoMethods;
4389 }else{
4390 return &semIoMethods;
4391 }
4392}
drh0c2694b2009-09-03 16:23:44 +00004393static const sqlite3_io_methods
4394 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004395
4396#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4397
drh7708e972008-11-29 00:56:52 +00004398/*
4399** An abstract type for a pointer to a IO method finder function:
4400*/
drh0c2694b2009-09-03 16:23:44 +00004401typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004402
aswiftaebf4132008-11-21 00:10:35 +00004403
drh734c9862008-11-28 15:37:20 +00004404/****************************************************************************
4405**************************** sqlite3_vfs methods ****************************
4406**
4407** This division contains the implementation of methods on the
4408** sqlite3_vfs object.
4409*/
4410
danielk1977a3d4c882007-03-23 10:08:38 +00004411/*
danielk1977e339d652008-06-28 11:23:00 +00004412** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004413*/
4414static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004415 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004416 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004417 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004418 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004419 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004420 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004421 int isDelete, /* Delete on close if true */
4422 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004423){
drh7708e972008-11-29 00:56:52 +00004424 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004425 unixFile *pNew = (unixFile *)pId;
4426 int rc = SQLITE_OK;
4427
drh8af6c222010-05-14 12:43:01 +00004428 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004429
dane946c392009-08-22 11:39:46 +00004430 /* Parameter isDelete is only used on vxworks. Express this explicitly
4431 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004432 */
drh7708e972008-11-29 00:56:52 +00004433 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004434
dan00157392010-10-05 11:33:15 +00004435 /* Usually the path zFilename should not be a relative pathname. The
4436 ** exception is when opening the proxy "conch" file in builds that
4437 ** include the special Apple locking styles.
4438 */
dan00157392010-10-05 11:33:15 +00004439#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004440 assert( zFilename==0 || zFilename[0]=='/'
4441 || pVfs->pAppData==(void*)&autolockIoFinder );
4442#else
4443 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004444#endif
dan00157392010-10-05 11:33:15 +00004445
drh308c2a52010-05-14 11:30:18 +00004446 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004447 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004448 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004449 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004450 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4451 pNew->ctrlFlags = UNIXFILE_EXCL;
4452 }else{
4453 pNew->ctrlFlags = 0;
4454 }
drh77197112011-03-15 19:08:48 +00004455 if( isReadOnly ){
4456 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4457 }
drh339eb0b2008-03-07 15:34:11 +00004458
drh6c7d5c52008-11-21 20:32:33 +00004459#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004460 pNew->pId = vxworksFindFileId(zFilename);
4461 if( pNew->pId==0 ){
4462 noLock = 1;
4463 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004464 }
4465#endif
4466
drhda0e7682008-07-30 15:27:54 +00004467 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004468 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004469 }else{
drh0c2694b2009-09-03 16:23:44 +00004470 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004471#if SQLITE_ENABLE_LOCKING_STYLE
4472 /* Cache zFilename in the locking context (AFP and dotlock override) for
4473 ** proxyLock activation is possible (remote proxy is based on db name)
4474 ** zFilename remains valid until file is closed, to support */
4475 pNew->lockingContext = (void*)zFilename;
4476#endif
drhda0e7682008-07-30 15:27:54 +00004477 }
danielk1977e339d652008-06-28 11:23:00 +00004478
drh7ed97b92010-01-20 13:07:21 +00004479 if( pLockingStyle == &posixIoMethods
4480#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4481 || pLockingStyle == &nfsIoMethods
4482#endif
4483 ){
drh7708e972008-11-29 00:56:52 +00004484 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004485 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004486 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004487 /* If an error occured in findInodeInfo(), close the file descriptor
4488 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004489 ** in two scenarios:
4490 **
4491 ** (a) A call to fstat() failed.
4492 ** (b) A malloc failed.
4493 **
4494 ** Scenario (b) may only occur if the process is holding no other
4495 ** file descriptors open on the same file. If there were other file
4496 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004497 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004498 ** handle h - as it is guaranteed that no posix locks will be released
4499 ** by doing so.
4500 **
4501 ** If scenario (a) caused the error then things are not so safe. The
4502 ** implicit assumption here is that if fstat() fails, things are in
4503 ** such bad shape that dropping a lock or two doesn't matter much.
4504 */
drh0e9365c2011-03-02 02:08:13 +00004505 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004506 h = -1;
4507 }
drh7708e972008-11-29 00:56:52 +00004508 unixLeaveMutex();
4509 }
danielk1977e339d652008-06-28 11:23:00 +00004510
drhd2cb50b2009-01-09 21:41:17 +00004511#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004512 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004513 /* AFP locking uses the file path so it needs to be included in
4514 ** the afpLockingContext.
4515 */
4516 afpLockingContext *pCtx;
4517 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4518 if( pCtx==0 ){
4519 rc = SQLITE_NOMEM;
4520 }else{
4521 /* NB: zFilename exists and remains valid until the file is closed
4522 ** according to requirement F11141. So we do not need to make a
4523 ** copy of the filename. */
4524 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004525 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004526 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004527 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004528 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004529 if( rc!=SQLITE_OK ){
4530 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004531 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004532 h = -1;
4533 }
drh7708e972008-11-29 00:56:52 +00004534 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004535 }
drh7708e972008-11-29 00:56:52 +00004536 }
4537#endif
danielk1977e339d652008-06-28 11:23:00 +00004538
drh7708e972008-11-29 00:56:52 +00004539 else if( pLockingStyle == &dotlockIoMethods ){
4540 /* Dotfile locking uses the file path so it needs to be included in
4541 ** the dotlockLockingContext
4542 */
4543 char *zLockFile;
4544 int nFilename;
drhea678832008-12-10 19:26:22 +00004545 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004546 zLockFile = (char *)sqlite3_malloc(nFilename);
4547 if( zLockFile==0 ){
4548 rc = SQLITE_NOMEM;
4549 }else{
4550 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004551 }
drh7708e972008-11-29 00:56:52 +00004552 pNew->lockingContext = zLockFile;
4553 }
danielk1977e339d652008-06-28 11:23:00 +00004554
drh6c7d5c52008-11-21 20:32:33 +00004555#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004556 else if( pLockingStyle == &semIoMethods ){
4557 /* Named semaphore locking uses the file path so it needs to be
4558 ** included in the semLockingContext
4559 */
4560 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004561 rc = findInodeInfo(pNew, &pNew->pInode);
4562 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4563 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004564 int n;
drh2238dcc2009-08-27 17:56:20 +00004565 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004566 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004567 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004568 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004569 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4570 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004571 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004572 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004573 }
chw97185482008-11-17 08:05:31 +00004574 }
drh7708e972008-11-29 00:56:52 +00004575 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004576 }
drh7708e972008-11-29 00:56:52 +00004577#endif
aswift5b1a2562008-08-22 00:22:35 +00004578
4579 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004580#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004581 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004582 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004583 h = -1;
chw97185482008-11-17 08:05:31 +00004584 unlink(zFilename);
4585 isDelete = 0;
4586 }
4587 pNew->isDelete = isDelete;
4588#endif
danielk1977e339d652008-06-28 11:23:00 +00004589 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004590 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4591 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004592 }else{
drh7708e972008-11-29 00:56:52 +00004593 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004594 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004595 }
danielk1977e339d652008-06-28 11:23:00 +00004596 return rc;
drh054889e2005-11-30 03:20:31 +00004597}
drh9c06c952005-11-26 00:25:00 +00004598
danielk1977ad94b582007-08-20 06:44:22 +00004599/*
4600** Open a file descriptor to the directory containing file zFilename.
4601** If successful, *pFd is set to the opened file descriptor and
4602** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4603** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4604** value.
4605**
4606** If SQLITE_OK is returned, the caller is responsible for closing
4607** the file descriptor *pFd using close().
4608*/
danielk1977fee2d252007-08-18 10:59:19 +00004609static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004610 int ii;
drh777b17a2007-09-20 10:02:54 +00004611 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004612 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004613
drh153c62c2007-08-24 03:51:33 +00004614 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004615 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004616 if( ii>0 ){
4617 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004618 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004619 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004620#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004621 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004622#endif
drh308c2a52010-05-14 11:30:18 +00004623 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004624 }
4625 }
danielk1977fee2d252007-08-18 10:59:19 +00004626 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004627 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004628}
4629
danielk1977b4b47412007-08-17 15:53:36 +00004630/*
drh8b3cf822010-06-01 21:02:51 +00004631** Return the name of a directory in which to put temporary files.
4632** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004633*/
drh7234c6d2010-06-19 15:10:09 +00004634static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004635 static const char *azDirs[] = {
4636 0,
aswiftaebf4132008-11-21 00:10:35 +00004637 0,
danielk197717b90b52008-06-06 11:11:25 +00004638 "/var/tmp",
4639 "/usr/tmp",
4640 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004641 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004642 };
drh8b3cf822010-06-01 21:02:51 +00004643 unsigned int i;
4644 struct stat buf;
4645 const char *zDir = 0;
4646
4647 azDirs[0] = sqlite3_temp_directory;
4648 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004649 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004650 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004651 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004652 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004653 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004654 break;
4655 }
4656 return zDir;
4657}
4658
4659/*
4660** Create a temporary file name in zBuf. zBuf must be allocated
4661** by the calling process and must be big enough to hold at least
4662** pVfs->mxPathname bytes.
4663*/
4664static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004665 static const unsigned char zChars[] =
4666 "abcdefghijklmnopqrstuvwxyz"
4667 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4668 "0123456789";
drh41022642008-11-21 00:24:42 +00004669 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004670 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004671
4672 /* It's odd to simulate an io-error here, but really this is just
4673 ** using the io-error infrastructure to test that SQLite handles this
4674 ** function failing.
4675 */
4676 SimulateIOError( return SQLITE_IOERR );
4677
drh7234c6d2010-06-19 15:10:09 +00004678 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004679 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004680
4681 /* Check that the output buffer is large enough for the temporary file
4682 ** name. If it is not, return SQLITE_ERROR.
4683 */
danielk197700e13612008-11-17 19:18:54 +00004684 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004685 return SQLITE_ERROR;
4686 }
4687
4688 do{
4689 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004690 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004691 sqlite3_randomness(15, &zBuf[j]);
4692 for(i=0; i<15; i++, j++){
4693 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4694 }
4695 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004696 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004697 return SQLITE_OK;
4698}
4699
drhd2cb50b2009-01-09 21:41:17 +00004700#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004701/*
4702** Routine to transform a unixFile into a proxy-locking unixFile.
4703** Implementation in the proxy-lock division, but used by unixOpen()
4704** if SQLITE_PREFER_PROXY_LOCKING is defined.
4705*/
4706static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004707#endif
drhc66d5b62008-12-03 22:48:32 +00004708
dan08da86a2009-08-21 17:18:03 +00004709/*
4710** Search for an unused file descriptor that was opened on the database
4711** file (not a journal or master-journal file) identified by pathname
4712** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4713** argument to this function.
4714**
4715** Such a file descriptor may exist if a database connection was closed
4716** but the associated file descriptor could not be closed because some
4717** other file descriptor open on the same file is holding a file-lock.
4718** Refer to comments in the unixClose() function and the lengthy comment
4719** describing "Posix Advisory Locking" at the start of this file for
4720** further details. Also, ticket #4018.
4721**
4722** If a suitable file descriptor is found, then it is returned. If no
4723** such file descriptor is located, -1 is returned.
4724*/
dane946c392009-08-22 11:39:46 +00004725static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4726 UnixUnusedFd *pUnused = 0;
4727
4728 /* Do not search for an unused file descriptor on vxworks. Not because
4729 ** vxworks would not benefit from the change (it might, we're not sure),
4730 ** but because no way to test it is currently available. It is better
4731 ** not to risk breaking vxworks support for the sake of such an obscure
4732 ** feature. */
4733#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004734 struct stat sStat; /* Results of stat() call */
4735
4736 /* A stat() call may fail for various reasons. If this happens, it is
4737 ** almost certain that an open() call on the same path will also fail.
4738 ** For this reason, if an error occurs in the stat() call here, it is
4739 ** ignored and -1 is returned. The caller will try to open a new file
4740 ** descriptor on the same path, fail, and return an error to SQLite.
4741 **
4742 ** Even if a subsequent open() call does succeed, the consequences of
4743 ** not searching for a resusable file descriptor are not dire. */
4744 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004745 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004746
4747 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004748 pInode = inodeList;
4749 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4750 || pInode->fileId.ino!=sStat.st_ino) ){
4751 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004752 }
drh8af6c222010-05-14 12:43:01 +00004753 if( pInode ){
dane946c392009-08-22 11:39:46 +00004754 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004755 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004756 pUnused = *pp;
4757 if( pUnused ){
4758 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004759 }
4760 }
4761 unixLeaveMutex();
4762 }
dane946c392009-08-22 11:39:46 +00004763#endif /* if !OS_VXWORKS */
4764 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004765}
danielk197717b90b52008-06-06 11:11:25 +00004766
4767/*
danddb0ac42010-07-14 14:48:58 +00004768** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004769** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004770** and a value suitable for passing as the third argument to open(2) is
4771** written to *pMode. If an IO error occurs, an SQLite error code is
4772** returned and the value of *pMode is not modified.
4773**
4774** If the file being opened is a temporary file, it is always created with
4775** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004776** is a database or master journal file, it is created with the permissions
4777** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004778**
drh8ab58662010-07-15 18:38:39 +00004779** Finally, if the file being opened is a WAL or regular journal file, then
4780** this function queries the file-system for the permissions on the
4781** corresponding database file and sets *pMode to this value. Whenever
4782** possible, WAL and journal files are created using the same permissions
4783** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004784*/
4785static int findCreateFileMode(
4786 const char *zPath, /* Path of file (possibly) being created */
4787 int flags, /* Flags passed as 4th argument to xOpen() */
4788 mode_t *pMode /* OUT: Permissions to open file with */
4789){
4790 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004791 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004792 char zDb[MAX_PATHNAME+1]; /* Database file path */
4793 int nDb; /* Number of valid bytes in zDb */
4794 struct stat sStat; /* Output of stat() on database file */
4795
dana0c989d2010-11-05 18:07:37 +00004796 /* zPath is a path to a WAL or journal file. The following block derives
4797 ** the path to the associated database file from zPath. This block handles
4798 ** the following naming conventions:
4799 **
4800 ** "<path to db>-journal"
4801 ** "<path to db>-wal"
4802 ** "<path to db>-journal-NNNN"
4803 ** "<path to db>-wal-NNNN"
4804 **
4805 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4806 ** used by the test_multiplex.c module.
4807 */
4808 nDb = sqlite3Strlen30(zPath) - 1;
4809 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4810 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004811 memcpy(zDb, zPath, nDb);
4812 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004813
danddb0ac42010-07-14 14:48:58 +00004814 if( 0==stat(zDb, &sStat) ){
4815 *pMode = sStat.st_mode & 0777;
4816 }else{
4817 rc = SQLITE_IOERR_FSTAT;
4818 }
4819 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4820 *pMode = 0600;
4821 }else{
4822 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4823 }
4824 return rc;
4825}
4826
4827/*
danielk1977ad94b582007-08-20 06:44:22 +00004828** Open the file zPath.
4829**
danielk1977b4b47412007-08-17 15:53:36 +00004830** Previously, the SQLite OS layer used three functions in place of this
4831** one:
4832**
4833** sqlite3OsOpenReadWrite();
4834** sqlite3OsOpenReadOnly();
4835** sqlite3OsOpenExclusive();
4836**
4837** These calls correspond to the following combinations of flags:
4838**
4839** ReadWrite() -> (READWRITE | CREATE)
4840** ReadOnly() -> (READONLY)
4841** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4842**
4843** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4844** true, the file was configured to be automatically deleted when the
4845** file handle closed. To achieve the same effect using this new
4846** interface, add the DELETEONCLOSE flag to those specified above for
4847** OpenExclusive().
4848*/
4849static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004850 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4851 const char *zPath, /* Pathname of file to be opened */
4852 sqlite3_file *pFile, /* The file descriptor to be filled in */
4853 int flags, /* Input flags to control the opening */
4854 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004855){
dan08da86a2009-08-21 17:18:03 +00004856 unixFile *p = (unixFile *)pFile;
4857 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004858 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004859 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004860 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004861 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004862 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004863
4864 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4865 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4866 int isCreate = (flags & SQLITE_OPEN_CREATE);
4867 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4868 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004869#if SQLITE_ENABLE_LOCKING_STYLE
4870 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4871#endif
danielk1977b4b47412007-08-17 15:53:36 +00004872
danielk1977fee2d252007-08-18 10:59:19 +00004873 /* If creating a master or main-file journal, this function will open
4874 ** a file-descriptor on the directory too. The first time unixSync()
4875 ** is called the directory file descriptor will be fsync()ed and close()d.
4876 */
danddb0ac42010-07-14 14:48:58 +00004877 int isOpenDirectory = (isCreate && (
4878 eType==SQLITE_OPEN_MASTER_JOURNAL
4879 || eType==SQLITE_OPEN_MAIN_JOURNAL
4880 || eType==SQLITE_OPEN_WAL
4881 ));
danielk1977fee2d252007-08-18 10:59:19 +00004882
danielk197717b90b52008-06-06 11:11:25 +00004883 /* If argument zPath is a NULL pointer, this function is required to open
4884 ** a temporary file. Use this buffer to store the file name in.
4885 */
4886 char zTmpname[MAX_PATHNAME+1];
4887 const char *zName = zPath;
4888
danielk1977fee2d252007-08-18 10:59:19 +00004889 /* Check the following statements are true:
4890 **
4891 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4892 ** (b) if CREATE is set, then READWRITE must also be set, and
4893 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004894 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004895 */
danielk1977b4b47412007-08-17 15:53:36 +00004896 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004897 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004898 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004899 assert(isDelete==0 || isCreate);
4900
danddb0ac42010-07-14 14:48:58 +00004901 /* The main DB, main journal, WAL file and master journal are never
4902 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004903 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4904 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4905 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004906 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004907
danielk1977fee2d252007-08-18 10:59:19 +00004908 /* Assert that the upper layer has set one of the "file-type" flags. */
4909 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4910 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4911 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004912 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004913 );
4914
dan08da86a2009-08-21 17:18:03 +00004915 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004916
dan08da86a2009-08-21 17:18:03 +00004917 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004918 UnixUnusedFd *pUnused;
4919 pUnused = findReusableFd(zName, flags);
4920 if( pUnused ){
4921 fd = pUnused->fd;
4922 }else{
dan6aa657f2009-08-24 18:57:58 +00004923 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004924 if( !pUnused ){
4925 return SQLITE_NOMEM;
4926 }
4927 }
4928 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004929 }else if( !zName ){
4930 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004931 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004932 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004933 if( rc!=SQLITE_OK ){
4934 return rc;
4935 }
4936 zName = zTmpname;
4937 }
4938
dan08da86a2009-08-21 17:18:03 +00004939 /* Determine the value of the flags parameter passed to POSIX function
4940 ** open(). These must be calculated even if open() is not called, as
4941 ** they may be stored as part of the file handle and used by the
4942 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004943 if( isReadonly ) openFlags |= O_RDONLY;
4944 if( isReadWrite ) openFlags |= O_RDWR;
4945 if( isCreate ) openFlags |= O_CREAT;
4946 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4947 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004948
danielk1977b4b47412007-08-17 15:53:36 +00004949 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004950 mode_t openMode; /* Permissions to create file with */
4951 rc = findCreateFileMode(zName, flags, &openMode);
4952 if( rc!=SQLITE_OK ){
4953 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004954 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004955 return rc;
4956 }
drhad4f1e52011-03-04 15:43:57 +00004957 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004958 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004959 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4960 /* Failed to open the file for read/write access. Try read-only. */
4961 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004962 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004963 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004964 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00004965 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00004966 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004967 }
4968 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004969 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004970 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004971 }
danielk1977b4b47412007-08-17 15:53:36 +00004972 }
dan08da86a2009-08-21 17:18:03 +00004973 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004974 if( pOutFlags ){
4975 *pOutFlags = flags;
4976 }
4977
dane946c392009-08-22 11:39:46 +00004978 if( p->pUnused ){
4979 p->pUnused->fd = fd;
4980 p->pUnused->flags = flags;
4981 }
4982
danielk1977b4b47412007-08-17 15:53:36 +00004983 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004984#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004985 zPath = zName;
4986#else
danielk197717b90b52008-06-06 11:11:25 +00004987 unlink(zName);
chw97185482008-11-17 08:05:31 +00004988#endif
danielk1977b4b47412007-08-17 15:53:36 +00004989 }
drh41022642008-11-21 00:24:42 +00004990#if SQLITE_ENABLE_LOCKING_STYLE
4991 else{
dan08da86a2009-08-21 17:18:03 +00004992 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004993 }
4994#endif
4995
danielk1977fee2d252007-08-18 10:59:19 +00004996 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004997 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004998 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004999 /* It is safe to close fd at this point, because it is guaranteed not
5000 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005001 ** it would not be safe to close as this would release any locks held
5002 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005003 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005004 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005005 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005006 }
5007 }
danielk1977e339d652008-06-28 11:23:00 +00005008
5009#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005010 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005011#endif
5012
drhda0e7682008-07-30 15:27:54 +00005013 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005014
drh7ed97b92010-01-20 13:07:21 +00005015
5016#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5017 struct statfs fsInfo;
5018 if( fstatfs(fd, &fsInfo) == -1 ){
5019 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005020 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5021 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005022 return SQLITE_IOERR_ACCESS;
5023 }
5024 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5025 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5026 }
5027#endif
5028
5029#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005030#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005031 isAutoProxy = 1;
5032#endif
5033 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005034 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5035 int useProxy = 0;
5036
dan08da86a2009-08-21 17:18:03 +00005037 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5038 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005039 if( envforce!=NULL ){
5040 useProxy = atoi(envforce)>0;
5041 }else{
5042 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005043 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005044 /* In theory, the close(fd) call is sub-optimal. If the file opened
5045 ** with fd is a database file, and there are other connections open
5046 ** on that file that are currently holding advisory locks on it,
5047 ** then the call to close() will cancel those locks. In practice,
5048 ** we're assuming that statfs() doesn't fail very often. At least
5049 ** not while other file descriptors opened by the same process on
5050 ** the same file are working. */
5051 p->lastErrno = errno;
5052 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005053 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005054 }
drh0e9365c2011-03-02 02:08:13 +00005055 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005056 rc = SQLITE_IOERR_ACCESS;
5057 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005058 }
5059 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5060 }
5061 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005062 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5063 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005064 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005065 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005066 if( rc!=SQLITE_OK ){
5067 /* Use unixClose to clean up the resources added in fillInUnixFile
5068 ** and clear all the structure's references. Specifically,
5069 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5070 */
5071 unixClose(pFile);
5072 return rc;
5073 }
aswiftaebf4132008-11-21 00:10:35 +00005074 }
dane946c392009-08-22 11:39:46 +00005075 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005076 }
5077 }
5078#endif
5079
drh77197112011-03-15 19:08:48 +00005080 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5081 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005082open_finished:
5083 if( rc!=SQLITE_OK ){
5084 sqlite3_free(p->pUnused);
5085 }
5086 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005087}
5088
dane946c392009-08-22 11:39:46 +00005089
danielk1977b4b47412007-08-17 15:53:36 +00005090/*
danielk1977fee2d252007-08-18 10:59:19 +00005091** Delete the file at zPath. If the dirSync argument is true, fsync()
5092** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005093*/
drh6b9d6dd2008-12-03 19:34:47 +00005094static int unixDelete(
5095 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5096 const char *zPath, /* Name of file to be deleted */
5097 int dirSync /* If true, fsync() directory after deleting file */
5098){
danielk1977fee2d252007-08-18 10:59:19 +00005099 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005100 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005101 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005102 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005103 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005104 }
danielk1977d39fa702008-10-16 13:27:40 +00005105#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005106 if( dirSync ){
5107 int fd;
5108 rc = openDirectory(zPath, &fd);
5109 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005110#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005111 if( fsync(fd)==-1 )
5112#else
5113 if( fsync(fd) )
5114#endif
5115 {
dane18d4952011-02-21 11:46:24 +00005116 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005117 }
drh0e9365c2011-03-02 02:08:13 +00005118 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005119 }
5120 }
danielk1977d138dd82008-10-15 16:02:48 +00005121#endif
danielk1977fee2d252007-08-18 10:59:19 +00005122 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005123}
5124
danielk197790949c22007-08-17 16:50:38 +00005125/*
5126** Test the existance of or access permissions of file zPath. The
5127** test performed depends on the value of flags:
5128**
5129** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5130** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5131** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5132**
5133** Otherwise return 0.
5134*/
danielk1977861f7452008-06-05 11:39:11 +00005135static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005136 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5137 const char *zPath, /* Path of the file to examine */
5138 int flags, /* What do we want to learn about the zPath file? */
5139 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005140){
rse25c0d1a2007-09-20 08:38:14 +00005141 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005142 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005143 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005144 switch( flags ){
5145 case SQLITE_ACCESS_EXISTS:
5146 amode = F_OK;
5147 break;
5148 case SQLITE_ACCESS_READWRITE:
5149 amode = W_OK|R_OK;
5150 break;
drh50d3f902007-08-27 21:10:36 +00005151 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005152 amode = R_OK;
5153 break;
5154
5155 default:
5156 assert(!"Invalid flags argument");
5157 }
drh99ab3b12011-03-02 15:09:07 +00005158 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005159 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5160 struct stat buf;
5161 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5162 *pResOut = 0;
5163 }
5164 }
danielk1977861f7452008-06-05 11:39:11 +00005165 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005166}
5167
danielk1977b4b47412007-08-17 15:53:36 +00005168
5169/*
5170** Turn a relative pathname into a full pathname. The relative path
5171** is stored as a nul-terminated string in the buffer pointed to by
5172** zPath.
5173**
5174** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5175** (in this case, MAX_PATHNAME bytes). The full-path is written to
5176** this buffer before returning.
5177*/
danielk1977adfb9b02007-09-17 07:02:56 +00005178static int unixFullPathname(
5179 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5180 const char *zPath, /* Possibly relative input path */
5181 int nOut, /* Size of output buffer in bytes */
5182 char *zOut /* Output buffer */
5183){
danielk1977843e65f2007-09-01 16:16:15 +00005184
5185 /* It's odd to simulate an io-error here, but really this is just
5186 ** using the io-error infrastructure to test that SQLite handles this
5187 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005188 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005189 */
5190 SimulateIOError( return SQLITE_ERROR );
5191
drh153c62c2007-08-24 03:51:33 +00005192 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005193 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005194
drh3c7f2dc2007-12-06 13:26:20 +00005195 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005196 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005197 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005198 }else{
5199 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005200 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005201 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005202 }
drhea678832008-12-10 19:26:22 +00005203 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005204 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005205 }
5206 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005207}
5208
drh0ccebe72005-06-07 22:22:50 +00005209
drh761df872006-12-21 01:29:22 +00005210#ifndef SQLITE_OMIT_LOAD_EXTENSION
5211/*
5212** Interfaces for opening a shared library, finding entry points
5213** within the shared library, and closing the shared library.
5214*/
5215#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005216static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5217 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005218 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5219}
danielk197795c8a542007-09-01 06:51:27 +00005220
5221/*
5222** SQLite calls this function immediately after a call to unixDlSym() or
5223** unixDlOpen() fails (returns a null pointer). If a more detailed error
5224** message is available, it is written to zBufOut. If no error message
5225** is available, zBufOut is left unmodified and SQLite uses a default
5226** error message.
5227*/
danielk1977397d65f2008-11-19 11:35:39 +00005228static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005229 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005230 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005231 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005232 zErr = dlerror();
5233 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005234 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005235 }
drh6c7d5c52008-11-21 20:32:33 +00005236 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005237}
drh1875f7a2008-12-08 18:19:17 +00005238static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5239 /*
5240 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5241 ** cast into a pointer to a function. And yet the library dlsym() routine
5242 ** returns a void* which is really a pointer to a function. So how do we
5243 ** use dlsym() with -pedantic-errors?
5244 **
5245 ** Variable x below is defined to be a pointer to a function taking
5246 ** parameters void* and const char* and returning a pointer to a function.
5247 ** We initialize x by assigning it a pointer to the dlsym() function.
5248 ** (That assignment requires a cast.) Then we call the function that
5249 ** x points to.
5250 **
5251 ** This work-around is unlikely to work correctly on any system where
5252 ** you really cannot cast a function pointer into void*. But then, on the
5253 ** other hand, dlsym() will not work on such a system either, so we have
5254 ** not really lost anything.
5255 */
5256 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005257 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005258 x = (void(*(*)(void*,const char*))(void))dlsym;
5259 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005260}
danielk1977397d65f2008-11-19 11:35:39 +00005261static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5262 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005263 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005264}
danielk1977b4b47412007-08-17 15:53:36 +00005265#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5266 #define unixDlOpen 0
5267 #define unixDlError 0
5268 #define unixDlSym 0
5269 #define unixDlClose 0
5270#endif
5271
5272/*
danielk197790949c22007-08-17 16:50:38 +00005273** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005274*/
danielk1977397d65f2008-11-19 11:35:39 +00005275static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5276 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005277 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005278
drhbbd42a62004-05-22 17:41:58 +00005279 /* We have to initialize zBuf to prevent valgrind from reporting
5280 ** errors. The reports issued by valgrind are incorrect - we would
5281 ** prefer that the randomness be increased by making use of the
5282 ** uninitialized space in zBuf - but valgrind errors tend to worry
5283 ** some users. Rather than argue, it seems easier just to initialize
5284 ** the whole array and silence valgrind, even if that means less randomness
5285 ** in the random seed.
5286 **
5287 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005288 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005289 ** tests repeatable.
5290 */
danielk1977b4b47412007-08-17 15:53:36 +00005291 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005292#if !defined(SQLITE_TEST)
5293 {
drh842b8642005-01-21 17:53:17 +00005294 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005295 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005296 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005297 time_t t;
5298 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005299 memcpy(zBuf, &t, sizeof(t));
5300 pid = getpid();
5301 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005302 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005303 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005304 }else{
drhe562be52011-03-02 18:01:10 +00005305 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005306 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005307 }
drhbbd42a62004-05-22 17:41:58 +00005308 }
5309#endif
drh72cbd072008-10-14 17:58:38 +00005310 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005311}
5312
danielk1977b4b47412007-08-17 15:53:36 +00005313
drhbbd42a62004-05-22 17:41:58 +00005314/*
5315** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005316** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005317** The return value is the number of microseconds of sleep actually
5318** requested from the underlying operating system, a number which
5319** might be greater than or equal to the argument, but not less
5320** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005321*/
danielk1977397d65f2008-11-19 11:35:39 +00005322static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005323#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005324 struct timespec sp;
5325
5326 sp.tv_sec = microseconds / 1000000;
5327 sp.tv_nsec = (microseconds % 1000000) * 1000;
5328 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005329 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005330 return microseconds;
5331#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005332 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005333 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005334 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005335#else
danielk1977b4b47412007-08-17 15:53:36 +00005336 int seconds = (microseconds+999999)/1000000;
5337 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005338 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005339 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005340#endif
drh88f474a2006-01-02 20:00:12 +00005341}
5342
5343/*
drh6b9d6dd2008-12-03 19:34:47 +00005344** The following variable, if set to a non-zero value, is interpreted as
5345** the number of seconds since 1970 and is used to set the result of
5346** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005347*/
5348#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005349int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005350#endif
5351
5352/*
drhb7e8ea22010-05-03 14:32:30 +00005353** Find the current time (in Universal Coordinated Time). Write into *piNow
5354** the current time and date as a Julian Day number times 86_400_000. In
5355** other words, write into *piNow the number of milliseconds since the Julian
5356** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5357** proleptic Gregorian calendar.
5358**
5359** On success, return 0. Return 1 if the time and date cannot be found.
5360*/
5361static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5362 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5363#if defined(NO_GETTOD)
5364 time_t t;
5365 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005366 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005367#elif OS_VXWORKS
5368 struct timespec sNow;
5369 clock_gettime(CLOCK_REALTIME, &sNow);
5370 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5371#else
5372 struct timeval sNow;
5373 gettimeofday(&sNow, 0);
5374 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5375#endif
5376
5377#ifdef SQLITE_TEST
5378 if( sqlite3_current_time ){
5379 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5380 }
5381#endif
5382 UNUSED_PARAMETER(NotUsed);
5383 return 0;
5384}
5385
5386/*
drhbbd42a62004-05-22 17:41:58 +00005387** Find the current time (in Universal Coordinated Time). Write the
5388** current time and date as a Julian Day number into *prNow and
5389** return 0. Return 1 if the time and date cannot be found.
5390*/
danielk1977397d65f2008-11-19 11:35:39 +00005391static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005392 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005393 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005394 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005395 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005396 return 0;
5397}
danielk1977b4b47412007-08-17 15:53:36 +00005398
drh6b9d6dd2008-12-03 19:34:47 +00005399/*
5400** We added the xGetLastError() method with the intention of providing
5401** better low-level error messages when operating-system problems come up
5402** during SQLite operation. But so far, none of that has been implemented
5403** in the core. So this routine is never called. For now, it is merely
5404** a place-holder.
5405*/
danielk1977397d65f2008-11-19 11:35:39 +00005406static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5407 UNUSED_PARAMETER(NotUsed);
5408 UNUSED_PARAMETER(NotUsed2);
5409 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005410 return 0;
5411}
5412
drhf2424c52010-04-26 00:04:55 +00005413
5414/*
drh734c9862008-11-28 15:37:20 +00005415************************ End of sqlite3_vfs methods ***************************
5416******************************************************************************/
5417
drh715ff302008-12-03 22:32:44 +00005418/******************************************************************************
5419************************** Begin Proxy Locking ********************************
5420**
5421** Proxy locking is a "uber-locking-method" in this sense: It uses the
5422** other locking methods on secondary lock files. Proxy locking is a
5423** meta-layer over top of the primitive locking implemented above. For
5424** this reason, the division that implements of proxy locking is deferred
5425** until late in the file (here) after all of the other I/O methods have
5426** been defined - so that the primitive locking methods are available
5427** as services to help with the implementation of proxy locking.
5428**
5429****
5430**
5431** The default locking schemes in SQLite use byte-range locks on the
5432** database file to coordinate safe, concurrent access by multiple readers
5433** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5434** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5435** as POSIX read & write locks over fixed set of locations (via fsctl),
5436** on AFP and SMB only exclusive byte-range locks are available via fsctl
5437** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5438** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5439** address in the shared range is taken for a SHARED lock, the entire
5440** shared range is taken for an EXCLUSIVE lock):
5441**
5442** PENDING_BYTE 0x40000000
5443** RESERVED_BYTE 0x40000001
5444** SHARED_RANGE 0x40000002 -> 0x40000200
5445**
5446** This works well on the local file system, but shows a nearly 100x
5447** slowdown in read performance on AFP because the AFP client disables
5448** the read cache when byte-range locks are present. Enabling the read
5449** cache exposes a cache coherency problem that is present on all OS X
5450** supported network file systems. NFS and AFP both observe the
5451** close-to-open semantics for ensuring cache coherency
5452** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5453** address the requirements for concurrent database access by multiple
5454** readers and writers
5455** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5456**
5457** To address the performance and cache coherency issues, proxy file locking
5458** changes the way database access is controlled by limiting access to a
5459** single host at a time and moving file locks off of the database file
5460** and onto a proxy file on the local file system.
5461**
5462**
5463** Using proxy locks
5464** -----------------
5465**
5466** C APIs
5467**
5468** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5469** <proxy_path> | ":auto:");
5470** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5471**
5472**
5473** SQL pragmas
5474**
5475** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5476** PRAGMA [database.]lock_proxy_file
5477**
5478** Specifying ":auto:" means that if there is a conch file with a matching
5479** host ID in it, the proxy path in the conch file will be used, otherwise
5480** a proxy path based on the user's temp dir
5481** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5482** actual proxy file name is generated from the name and path of the
5483** database file. For example:
5484**
5485** For database path "/Users/me/foo.db"
5486** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5487**
5488** Once a lock proxy is configured for a database connection, it can not
5489** be removed, however it may be switched to a different proxy path via
5490** the above APIs (assuming the conch file is not being held by another
5491** connection or process).
5492**
5493**
5494** How proxy locking works
5495** -----------------------
5496**
5497** Proxy file locking relies primarily on two new supporting files:
5498**
5499** * conch file to limit access to the database file to a single host
5500** at a time
5501**
5502** * proxy file to act as a proxy for the advisory locks normally
5503** taken on the database
5504**
5505** The conch file - to use a proxy file, sqlite must first "hold the conch"
5506** by taking an sqlite-style shared lock on the conch file, reading the
5507** contents and comparing the host's unique host ID (see below) and lock
5508** proxy path against the values stored in the conch. The conch file is
5509** stored in the same directory as the database file and the file name
5510** is patterned after the database file name as ".<databasename>-conch".
5511** If the conch file does not exist, or it's contents do not match the
5512** host ID and/or proxy path, then the lock is escalated to an exclusive
5513** lock and the conch file contents is updated with the host ID and proxy
5514** path and the lock is downgraded to a shared lock again. If the conch
5515** is held by another process (with a shared lock), the exclusive lock
5516** will fail and SQLITE_BUSY is returned.
5517**
5518** The proxy file - a single-byte file used for all advisory file locks
5519** normally taken on the database file. This allows for safe sharing
5520** of the database file for multiple readers and writers on the same
5521** host (the conch ensures that they all use the same local lock file).
5522**
drh715ff302008-12-03 22:32:44 +00005523** Requesting the lock proxy does not immediately take the conch, it is
5524** only taken when the first request to lock database file is made.
5525** This matches the semantics of the traditional locking behavior, where
5526** opening a connection to a database file does not take a lock on it.
5527** The shared lock and an open file descriptor are maintained until
5528** the connection to the database is closed.
5529**
5530** The proxy file and the lock file are never deleted so they only need
5531** to be created the first time they are used.
5532**
5533** Configuration options
5534** ---------------------
5535**
5536** SQLITE_PREFER_PROXY_LOCKING
5537**
5538** Database files accessed on non-local file systems are
5539** automatically configured for proxy locking, lock files are
5540** named automatically using the same logic as
5541** PRAGMA lock_proxy_file=":auto:"
5542**
5543** SQLITE_PROXY_DEBUG
5544**
5545** Enables the logging of error messages during host id file
5546** retrieval and creation
5547**
drh715ff302008-12-03 22:32:44 +00005548** LOCKPROXYDIR
5549**
5550** Overrides the default directory used for lock proxy files that
5551** are named automatically via the ":auto:" setting
5552**
5553** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5554**
5555** Permissions to use when creating a directory for storing the
5556** lock proxy files, only used when LOCKPROXYDIR is not set.
5557**
5558**
5559** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5560** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5561** force proxy locking to be used for every database file opened, and 0
5562** will force automatic proxy locking to be disabled for all database
5563** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5564** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5565*/
5566
5567/*
5568** Proxy locking is only available on MacOSX
5569*/
drhd2cb50b2009-01-09 21:41:17 +00005570#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005571
drh715ff302008-12-03 22:32:44 +00005572/*
5573** The proxyLockingContext has the path and file structures for the remote
5574** and local proxy files in it
5575*/
5576typedef struct proxyLockingContext proxyLockingContext;
5577struct proxyLockingContext {
5578 unixFile *conchFile; /* Open conch file */
5579 char *conchFilePath; /* Name of the conch file */
5580 unixFile *lockProxy; /* Open proxy lock file */
5581 char *lockProxyPath; /* Name of the proxy lock file */
5582 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005583 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005584 void *oldLockingContext; /* Original lockingcontext to restore on close */
5585 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5586};
5587
drh7ed97b92010-01-20 13:07:21 +00005588/*
5589** The proxy lock file path for the database at dbPath is written into lPath,
5590** which must point to valid, writable memory large enough for a maxLen length
5591** file path.
drh715ff302008-12-03 22:32:44 +00005592*/
drh715ff302008-12-03 22:32:44 +00005593static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5594 int len;
5595 int dbLen;
5596 int i;
5597
5598#ifdef LOCKPROXYDIR
5599 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5600#else
5601# ifdef _CS_DARWIN_USER_TEMP_DIR
5602 {
drh7ed97b92010-01-20 13:07:21 +00005603 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005604 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5605 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005606 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005607 }
drh7ed97b92010-01-20 13:07:21 +00005608 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005609 }
5610# else
5611 len = strlcpy(lPath, "/tmp/", maxLen);
5612# endif
5613#endif
5614
5615 if( lPath[len-1]!='/' ){
5616 len = strlcat(lPath, "/", maxLen);
5617 }
5618
5619 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005620 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005621 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005622 char c = dbPath[i];
5623 lPath[i+len] = (c=='/')?'_':c;
5624 }
5625 lPath[i+len]='\0';
5626 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005627 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005628 return SQLITE_OK;
5629}
5630
drh7ed97b92010-01-20 13:07:21 +00005631/*
5632 ** Creates the lock file and any missing directories in lockPath
5633 */
5634static int proxyCreateLockPath(const char *lockPath){
5635 int i, len;
5636 char buf[MAXPATHLEN];
5637 int start = 0;
5638
5639 assert(lockPath!=NULL);
5640 /* try to create all the intermediate directories */
5641 len = (int)strlen(lockPath);
5642 buf[0] = lockPath[0];
5643 for( i=1; i<len; i++ ){
5644 if( lockPath[i] == '/' && (i - start > 0) ){
5645 /* only mkdir if leaf dir != "." or "/" or ".." */
5646 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5647 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5648 buf[i]='\0';
5649 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5650 int err=errno;
5651 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005652 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005653 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005654 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005655 return err;
5656 }
5657 }
5658 }
5659 start=i+1;
5660 }
5661 buf[i] = lockPath[i];
5662 }
drh308c2a52010-05-14 11:30:18 +00005663 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005664 return 0;
5665}
5666
drh715ff302008-12-03 22:32:44 +00005667/*
5668** Create a new VFS file descriptor (stored in memory obtained from
5669** sqlite3_malloc) and open the file named "path" in the file descriptor.
5670**
5671** The caller is responsible not only for closing the file descriptor
5672** but also for freeing the memory associated with the file descriptor.
5673*/
drh7ed97b92010-01-20 13:07:21 +00005674static int proxyCreateUnixFile(
5675 const char *path, /* path for the new unixFile */
5676 unixFile **ppFile, /* unixFile created and returned by ref */
5677 int islockfile /* if non zero missing dirs will be created */
5678) {
5679 int fd = -1;
5680 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005681 unixFile *pNew;
5682 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005683 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005684 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005685 int terrno = 0;
5686 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005687
drh7ed97b92010-01-20 13:07:21 +00005688 /* 1. first try to open/create the file
5689 ** 2. if that fails, and this is a lock file (not-conch), try creating
5690 ** the parent directories and then try again.
5691 ** 3. if that fails, try to open the file read-only
5692 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5693 */
5694 pUnused = findReusableFd(path, openFlags);
5695 if( pUnused ){
5696 fd = pUnused->fd;
5697 }else{
5698 pUnused = sqlite3_malloc(sizeof(*pUnused));
5699 if( !pUnused ){
5700 return SQLITE_NOMEM;
5701 }
5702 }
5703 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005704 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005705 terrno = errno;
5706 if( fd<0 && errno==ENOENT && islockfile ){
5707 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005708 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005709 }
5710 }
5711 }
5712 if( fd<0 ){
5713 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005714 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005715 terrno = errno;
5716 }
5717 if( fd<0 ){
5718 if( islockfile ){
5719 return SQLITE_BUSY;
5720 }
5721 switch (terrno) {
5722 case EACCES:
5723 return SQLITE_PERM;
5724 case EIO:
5725 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5726 default:
drh9978c972010-02-23 17:36:32 +00005727 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005728 }
5729 }
5730
5731 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5732 if( pNew==NULL ){
5733 rc = SQLITE_NOMEM;
5734 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005735 }
5736 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005737 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005738 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005739 pUnused->fd = fd;
5740 pUnused->flags = openFlags;
5741 pNew->pUnused = pUnused;
5742
drh77197112011-03-15 19:08:48 +00005743 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005744 if( rc==SQLITE_OK ){
5745 *ppFile = pNew;
5746 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005747 }
drh7ed97b92010-01-20 13:07:21 +00005748end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005749 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005750 sqlite3_free(pNew);
5751 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005752 return rc;
5753}
5754
drh7ed97b92010-01-20 13:07:21 +00005755#ifdef SQLITE_TEST
5756/* simulate multiple hosts by creating unique hostid file paths */
5757int sqlite3_hostid_num = 0;
5758#endif
5759
5760#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5761
drh0ab216a2010-07-02 17:10:40 +00005762/* Not always defined in the headers as it ought to be */
5763extern int gethostuuid(uuid_t id, const struct timespec *wait);
5764
drh7ed97b92010-01-20 13:07:21 +00005765/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5766** bytes of writable memory.
5767*/
5768static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005769 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5770 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005771#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5772 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005773 {
5774 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5775 if( gethostuuid(pHostID, &timeout) ){
5776 int err = errno;
5777 if( pError ){
5778 *pError = err;
5779 }
5780 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005781 }
drh7ed97b92010-01-20 13:07:21 +00005782 }
drhe8b0c9b2010-09-25 14:13:17 +00005783#endif
drh7ed97b92010-01-20 13:07:21 +00005784#ifdef SQLITE_TEST
5785 /* simulate multiple hosts by creating unique hostid file paths */
5786 if( sqlite3_hostid_num != 0){
5787 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5788 }
5789#endif
5790
5791 return SQLITE_OK;
5792}
5793
5794/* The conch file contains the header, host id and lock file path
5795 */
5796#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5797#define PROXY_HEADERLEN 1 /* conch file header length */
5798#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5799#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5800
5801/*
5802** Takes an open conch file, copies the contents to a new path and then moves
5803** it back. The newly created file's file descriptor is assigned to the
5804** conch file structure and finally the original conch file descriptor is
5805** closed. Returns zero if successful.
5806*/
5807static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5808 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5809 unixFile *conchFile = pCtx->conchFile;
5810 char tPath[MAXPATHLEN];
5811 char buf[PROXY_MAXCONCHLEN];
5812 char *cPath = pCtx->conchFilePath;
5813 size_t readLen = 0;
5814 size_t pathLen = 0;
5815 char errmsg[64] = "";
5816 int fd = -1;
5817 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005818 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005819
5820 /* create a new path by replace the trailing '-conch' with '-break' */
5821 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5822 if( pathLen>MAXPATHLEN || pathLen<6 ||
5823 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005824 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005825 goto end_breaklock;
5826 }
5827 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005828 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005829 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005830 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005831 goto end_breaklock;
5832 }
5833 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005834 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5835 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005836 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005837 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005838 goto end_breaklock;
5839 }
drhe562be52011-03-02 18:01:10 +00005840 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005841 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005842 goto end_breaklock;
5843 }
5844 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005845 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005846 goto end_breaklock;
5847 }
5848 rc = 0;
5849 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005850 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005851 conchFile->h = fd;
5852 conchFile->openFlags = O_RDWR | O_CREAT;
5853
5854end_breaklock:
5855 if( rc ){
5856 if( fd>=0 ){
5857 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005858 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005859 }
5860 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5861 }
5862 return rc;
5863}
5864
5865/* Take the requested lock on the conch file and break a stale lock if the
5866** host id matches.
5867*/
5868static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5869 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5870 unixFile *conchFile = pCtx->conchFile;
5871 int rc = SQLITE_OK;
5872 int nTries = 0;
5873 struct timespec conchModTime;
5874
5875 do {
5876 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5877 nTries ++;
5878 if( rc==SQLITE_BUSY ){
5879 /* If the lock failed (busy):
5880 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5881 * 2nd try: fail if the mod time changed or host id is different, wait
5882 * 10 sec and try again
5883 * 3rd try: break the lock unless the mod time has changed.
5884 */
5885 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005886 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005887 pFile->lastErrno = errno;
5888 return SQLITE_IOERR_LOCK;
5889 }
5890
5891 if( nTries==1 ){
5892 conchModTime = buf.st_mtimespec;
5893 usleep(500000); /* wait 0.5 sec and try the lock again*/
5894 continue;
5895 }
5896
5897 assert( nTries>1 );
5898 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5899 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5900 return SQLITE_BUSY;
5901 }
5902
5903 if( nTries==2 ){
5904 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005905 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005906 if( len<0 ){
5907 pFile->lastErrno = errno;
5908 return SQLITE_IOERR_LOCK;
5909 }
5910 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5911 /* don't break the lock if the host id doesn't match */
5912 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5913 return SQLITE_BUSY;
5914 }
5915 }else{
5916 /* don't break the lock on short read or a version mismatch */
5917 return SQLITE_BUSY;
5918 }
5919 usleep(10000000); /* wait 10 sec and try the lock again */
5920 continue;
5921 }
5922
5923 assert( nTries==3 );
5924 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5925 rc = SQLITE_OK;
5926 if( lockType==EXCLUSIVE_LOCK ){
5927 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5928 }
5929 if( !rc ){
5930 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5931 }
5932 }
5933 }
5934 } while( rc==SQLITE_BUSY && nTries<3 );
5935
5936 return rc;
5937}
5938
5939/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005940** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5941** lockPath means that the lockPath in the conch file will be used if the
5942** host IDs match, or a new lock path will be generated automatically
5943** and written to the conch file.
5944*/
5945static int proxyTakeConch(unixFile *pFile){
5946 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5947
drh7ed97b92010-01-20 13:07:21 +00005948 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005949 return SQLITE_OK;
5950 }else{
5951 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005952 uuid_t myHostID;
5953 int pError = 0;
5954 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005955 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005956 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005957 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005958 int createConch = 0;
5959 int hostIdMatch = 0;
5960 int readLen = 0;
5961 int tryOldLockPath = 0;
5962 int forceNewLockPath = 0;
5963
drh308c2a52010-05-14 11:30:18 +00005964 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5965 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005966
drh7ed97b92010-01-20 13:07:21 +00005967 rc = proxyGetHostID(myHostID, &pError);
5968 if( (rc&0xff)==SQLITE_IOERR ){
5969 pFile->lastErrno = pError;
5970 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005971 }
drh7ed97b92010-01-20 13:07:21 +00005972 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005973 if( rc!=SQLITE_OK ){
5974 goto end_takeconch;
5975 }
drh7ed97b92010-01-20 13:07:21 +00005976 /* read the existing conch file */
5977 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5978 if( readLen<0 ){
5979 /* I/O error: lastErrno set by seekAndRead */
5980 pFile->lastErrno = conchFile->lastErrno;
5981 rc = SQLITE_IOERR_READ;
5982 goto end_takeconch;
5983 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5984 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5985 /* a short read or version format mismatch means we need to create a new
5986 ** conch file.
5987 */
5988 createConch = 1;
5989 }
5990 /* if the host id matches and the lock path already exists in the conch
5991 ** we'll try to use the path there, if we can't open that path, we'll
5992 ** retry with a new auto-generated path
5993 */
5994 do { /* in case we need to try again for an :auto: named lock file */
5995
5996 if( !createConch && !forceNewLockPath ){
5997 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5998 PROXY_HOSTIDLEN);
5999 /* if the conch has data compare the contents */
6000 if( !pCtx->lockProxyPath ){
6001 /* for auto-named local lock file, just check the host ID and we'll
6002 ** use the local lock file path that's already in there
6003 */
6004 if( hostIdMatch ){
6005 size_t pathLen = (readLen - PROXY_PATHINDEX);
6006
6007 if( pathLen>=MAXPATHLEN ){
6008 pathLen=MAXPATHLEN-1;
6009 }
6010 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6011 lockPath[pathLen] = 0;
6012 tempLockPath = lockPath;
6013 tryOldLockPath = 1;
6014 /* create a copy of the lock path if the conch is taken */
6015 goto end_takeconch;
6016 }
6017 }else if( hostIdMatch
6018 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6019 readLen-PROXY_PATHINDEX)
6020 ){
6021 /* conch host and lock path match */
6022 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006023 }
drh7ed97b92010-01-20 13:07:21 +00006024 }
6025
6026 /* if the conch isn't writable and doesn't match, we can't take it */
6027 if( (conchFile->openFlags&O_RDWR) == 0 ){
6028 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006029 goto end_takeconch;
6030 }
drh7ed97b92010-01-20 13:07:21 +00006031
6032 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006033 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006034 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6035 tempLockPath = lockPath;
6036 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006037 }
drh7ed97b92010-01-20 13:07:21 +00006038
6039 /* update conch with host and path (this will fail if other process
6040 ** has a shared lock already), if the host id matches, use the big
6041 ** stick.
drh715ff302008-12-03 22:32:44 +00006042 */
drh7ed97b92010-01-20 13:07:21 +00006043 futimes(conchFile->h, NULL);
6044 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006045 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006046 /* We are trying for an exclusive lock but another thread in this
6047 ** same process is still holding a shared lock. */
6048 rc = SQLITE_BUSY;
6049 } else {
6050 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006051 }
drh715ff302008-12-03 22:32:44 +00006052 }else{
drh7ed97b92010-01-20 13:07:21 +00006053 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006054 }
drh7ed97b92010-01-20 13:07:21 +00006055 if( rc==SQLITE_OK ){
6056 char writeBuffer[PROXY_MAXCONCHLEN];
6057 int writeSize = 0;
6058
6059 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6060 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6061 if( pCtx->lockProxyPath!=NULL ){
6062 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6063 }else{
6064 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6065 }
6066 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006067 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006068 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6069 fsync(conchFile->h);
6070 /* If we created a new conch file (not just updated the contents of a
6071 ** valid conch file), try to match the permissions of the database
6072 */
6073 if( rc==SQLITE_OK && createConch ){
6074 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006075 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006076 if( err==0 ){
6077 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6078 S_IROTH|S_IWOTH);
6079 /* try to match the database file R/W permissions, ignore failure */
6080#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006081 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006082#else
drhff812312011-02-23 13:33:46 +00006083 do{
drhe562be52011-03-02 18:01:10 +00006084 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006085 }while( rc==(-1) && errno==EINTR );
6086 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006087 int code = errno;
6088 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6089 cmode, code, strerror(code));
6090 } else {
6091 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6092 }
6093 }else{
6094 int code = errno;
6095 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6096 err, code, strerror(code));
6097#endif
6098 }
drh715ff302008-12-03 22:32:44 +00006099 }
6100 }
drh7ed97b92010-01-20 13:07:21 +00006101 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6102
6103 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006104 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006105 if( rc==SQLITE_OK && pFile->openFlags ){
6106 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006107 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006108 }
6109 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006110 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006111 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006112 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006113 if( fd>=0 ){
6114 pFile->h = fd;
6115 }else{
drh9978c972010-02-23 17:36:32 +00006116 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006117 during locking */
6118 }
6119 }
6120 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6121 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6122 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6123 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6124 /* we couldn't create the proxy lock file with the old lock file path
6125 ** so try again via auto-naming
6126 */
6127 forceNewLockPath = 1;
6128 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006129 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006130 }
6131 }
6132 if( rc==SQLITE_OK ){
6133 /* Need to make a copy of path if we extracted the value
6134 ** from the conch file or the path was allocated on the stack
6135 */
6136 if( tempLockPath ){
6137 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6138 if( !pCtx->lockProxyPath ){
6139 rc = SQLITE_NOMEM;
6140 }
6141 }
6142 }
6143 if( rc==SQLITE_OK ){
6144 pCtx->conchHeld = 1;
6145
6146 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6147 afpLockingContext *afpCtx;
6148 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6149 afpCtx->dbPath = pCtx->lockProxyPath;
6150 }
6151 } else {
6152 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6153 }
drh308c2a52010-05-14 11:30:18 +00006154 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6155 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006156 return rc;
drh308c2a52010-05-14 11:30:18 +00006157 } while (1); /* in case we need to retry the :auto: lock file -
6158 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006159 }
6160}
6161
6162/*
6163** If pFile holds a lock on a conch file, then release that lock.
6164*/
6165static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006166 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006167 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6168 unixFile *conchFile; /* Name of the conch file */
6169
6170 pCtx = (proxyLockingContext *)pFile->lockingContext;
6171 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006172 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006173 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006174 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006175 if( pCtx->conchHeld>0 ){
6176 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6177 }
drh715ff302008-12-03 22:32:44 +00006178 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006179 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6180 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006181 return rc;
6182}
6183
6184/*
6185** Given the name of a database file, compute the name of its conch file.
6186** Store the conch filename in memory obtained from sqlite3_malloc().
6187** Make *pConchPath point to the new name. Return SQLITE_OK on success
6188** or SQLITE_NOMEM if unable to obtain memory.
6189**
6190** The caller is responsible for ensuring that the allocated memory
6191** space is eventually freed.
6192**
6193** *pConchPath is set to NULL if a memory allocation error occurs.
6194*/
6195static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6196 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006197 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006198 char *conchPath; /* buffer in which to construct conch name */
6199
6200 /* Allocate space for the conch filename and initialize the name to
6201 ** the name of the original database file. */
6202 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6203 if( conchPath==0 ){
6204 return SQLITE_NOMEM;
6205 }
6206 memcpy(conchPath, dbPath, len+1);
6207
6208 /* now insert a "." before the last / character */
6209 for( i=(len-1); i>=0; i-- ){
6210 if( conchPath[i]=='/' ){
6211 i++;
6212 break;
6213 }
6214 }
6215 conchPath[i]='.';
6216 while ( i<len ){
6217 conchPath[i+1]=dbPath[i];
6218 i++;
6219 }
6220
6221 /* append the "-conch" suffix to the file */
6222 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006223 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006224
6225 return SQLITE_OK;
6226}
6227
6228
6229/* Takes a fully configured proxy locking-style unix file and switches
6230** the local lock file path
6231*/
6232static int switchLockProxyPath(unixFile *pFile, const char *path) {
6233 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6234 char *oldPath = pCtx->lockProxyPath;
6235 int rc = SQLITE_OK;
6236
drh308c2a52010-05-14 11:30:18 +00006237 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006238 return SQLITE_BUSY;
6239 }
6240
6241 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6242 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6243 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6244 return SQLITE_OK;
6245 }else{
6246 unixFile *lockProxy = pCtx->lockProxy;
6247 pCtx->lockProxy=NULL;
6248 pCtx->conchHeld = 0;
6249 if( lockProxy!=NULL ){
6250 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6251 if( rc ) return rc;
6252 sqlite3_free(lockProxy);
6253 }
6254 sqlite3_free(oldPath);
6255 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6256 }
6257
6258 return rc;
6259}
6260
6261/*
6262** pFile is a file that has been opened by a prior xOpen call. dbPath
6263** is a string buffer at least MAXPATHLEN+1 characters in size.
6264**
6265** This routine find the filename associated with pFile and writes it
6266** int dbPath.
6267*/
6268static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006269#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006270 if( pFile->pMethod == &afpIoMethods ){
6271 /* afp style keeps a reference to the db path in the filePath field
6272 ** of the struct */
drhea678832008-12-10 19:26:22 +00006273 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006274 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6275 } else
drh715ff302008-12-03 22:32:44 +00006276#endif
6277 if( pFile->pMethod == &dotlockIoMethods ){
6278 /* dot lock style uses the locking context to store the dot lock
6279 ** file path */
6280 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6281 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6282 }else{
6283 /* all other styles use the locking context to store the db file path */
6284 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006285 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006286 }
6287 return SQLITE_OK;
6288}
6289
6290/*
6291** Takes an already filled in unix file and alters it so all file locking
6292** will be performed on the local proxy lock file. The following fields
6293** are preserved in the locking context so that they can be restored and
6294** the unix structure properly cleaned up at close time:
6295** ->lockingContext
6296** ->pMethod
6297*/
6298static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6299 proxyLockingContext *pCtx;
6300 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6301 char *lockPath=NULL;
6302 int rc = SQLITE_OK;
6303
drh308c2a52010-05-14 11:30:18 +00006304 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006305 return SQLITE_BUSY;
6306 }
6307 proxyGetDbPathForUnixFile(pFile, dbPath);
6308 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6309 lockPath=NULL;
6310 }else{
6311 lockPath=(char *)path;
6312 }
6313
drh308c2a52010-05-14 11:30:18 +00006314 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6315 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006316
6317 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6318 if( pCtx==0 ){
6319 return SQLITE_NOMEM;
6320 }
6321 memset(pCtx, 0, sizeof(*pCtx));
6322
6323 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6324 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006325 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6326 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6327 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6328 ** (c) the file system is read-only, then enable no-locking access.
6329 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6330 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6331 */
6332 struct statfs fsInfo;
6333 struct stat conchInfo;
6334 int goLockless = 0;
6335
drh99ab3b12011-03-02 15:09:07 +00006336 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006337 int err = errno;
6338 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6339 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6340 }
6341 }
6342 if( goLockless ){
6343 pCtx->conchHeld = -1; /* read only FS/ lockless */
6344 rc = SQLITE_OK;
6345 }
6346 }
drh715ff302008-12-03 22:32:44 +00006347 }
6348 if( rc==SQLITE_OK && lockPath ){
6349 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6350 }
6351
6352 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006353 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6354 if( pCtx->dbPath==NULL ){
6355 rc = SQLITE_NOMEM;
6356 }
6357 }
6358 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006359 /* all memory is allocated, proxys are created and assigned,
6360 ** switch the locking context and pMethod then return.
6361 */
drh715ff302008-12-03 22:32:44 +00006362 pCtx->oldLockingContext = pFile->lockingContext;
6363 pFile->lockingContext = pCtx;
6364 pCtx->pOldMethod = pFile->pMethod;
6365 pFile->pMethod = &proxyIoMethods;
6366 }else{
6367 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006368 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006369 sqlite3_free(pCtx->conchFile);
6370 }
drhd56b1212010-08-11 06:14:15 +00006371 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006372 sqlite3_free(pCtx->conchFilePath);
6373 sqlite3_free(pCtx);
6374 }
drh308c2a52010-05-14 11:30:18 +00006375 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6376 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006377 return rc;
6378}
6379
6380
6381/*
6382** This routine handles sqlite3_file_control() calls that are specific
6383** to proxy locking.
6384*/
6385static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6386 switch( op ){
6387 case SQLITE_GET_LOCKPROXYFILE: {
6388 unixFile *pFile = (unixFile*)id;
6389 if( pFile->pMethod == &proxyIoMethods ){
6390 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6391 proxyTakeConch(pFile);
6392 if( pCtx->lockProxyPath ){
6393 *(const char **)pArg = pCtx->lockProxyPath;
6394 }else{
6395 *(const char **)pArg = ":auto: (not held)";
6396 }
6397 } else {
6398 *(const char **)pArg = NULL;
6399 }
6400 return SQLITE_OK;
6401 }
6402 case SQLITE_SET_LOCKPROXYFILE: {
6403 unixFile *pFile = (unixFile*)id;
6404 int rc = SQLITE_OK;
6405 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6406 if( pArg==NULL || (const char *)pArg==0 ){
6407 if( isProxyStyle ){
6408 /* turn off proxy locking - not supported */
6409 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6410 }else{
6411 /* turn off proxy locking - already off - NOOP */
6412 rc = SQLITE_OK;
6413 }
6414 }else{
6415 const char *proxyPath = (const char *)pArg;
6416 if( isProxyStyle ){
6417 proxyLockingContext *pCtx =
6418 (proxyLockingContext*)pFile->lockingContext;
6419 if( !strcmp(pArg, ":auto:")
6420 || (pCtx->lockProxyPath &&
6421 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6422 ){
6423 rc = SQLITE_OK;
6424 }else{
6425 rc = switchLockProxyPath(pFile, proxyPath);
6426 }
6427 }else{
6428 /* turn on proxy file locking */
6429 rc = proxyTransformUnixFile(pFile, proxyPath);
6430 }
6431 }
6432 return rc;
6433 }
6434 default: {
6435 assert( 0 ); /* The call assures that only valid opcodes are sent */
6436 }
6437 }
6438 /*NOTREACHED*/
6439 return SQLITE_ERROR;
6440}
6441
6442/*
6443** Within this division (the proxying locking implementation) the procedures
6444** above this point are all utilities. The lock-related methods of the
6445** proxy-locking sqlite3_io_method object follow.
6446*/
6447
6448
6449/*
6450** This routine checks if there is a RESERVED lock held on the specified
6451** file by this or any other process. If such a lock is held, set *pResOut
6452** to a non-zero value otherwise *pResOut is set to zero. The return value
6453** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6454*/
6455static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6456 unixFile *pFile = (unixFile*)id;
6457 int rc = proxyTakeConch(pFile);
6458 if( rc==SQLITE_OK ){
6459 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006460 if( pCtx->conchHeld>0 ){
6461 unixFile *proxy = pCtx->lockProxy;
6462 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6463 }else{ /* conchHeld < 0 is lockless */
6464 pResOut=0;
6465 }
drh715ff302008-12-03 22:32:44 +00006466 }
6467 return rc;
6468}
6469
6470/*
drh308c2a52010-05-14 11:30:18 +00006471** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006472** of the following:
6473**
6474** (1) SHARED_LOCK
6475** (2) RESERVED_LOCK
6476** (3) PENDING_LOCK
6477** (4) EXCLUSIVE_LOCK
6478**
6479** Sometimes when requesting one lock state, additional lock states
6480** are inserted in between. The locking might fail on one of the later
6481** transitions leaving the lock state different from what it started but
6482** still short of its goal. The following chart shows the allowed
6483** transitions and the inserted intermediate states:
6484**
6485** UNLOCKED -> SHARED
6486** SHARED -> RESERVED
6487** SHARED -> (PENDING) -> EXCLUSIVE
6488** RESERVED -> (PENDING) -> EXCLUSIVE
6489** PENDING -> EXCLUSIVE
6490**
6491** This routine will only increase a lock. Use the sqlite3OsUnlock()
6492** routine to lower a locking level.
6493*/
drh308c2a52010-05-14 11:30:18 +00006494static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006495 unixFile *pFile = (unixFile*)id;
6496 int rc = proxyTakeConch(pFile);
6497 if( rc==SQLITE_OK ){
6498 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006499 if( pCtx->conchHeld>0 ){
6500 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006501 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6502 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006503 }else{
6504 /* conchHeld < 0 is lockless */
6505 }
drh715ff302008-12-03 22:32:44 +00006506 }
6507 return rc;
6508}
6509
6510
6511/*
drh308c2a52010-05-14 11:30:18 +00006512** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006513** must be either NO_LOCK or SHARED_LOCK.
6514**
6515** If the locking level of the file descriptor is already at or below
6516** the requested locking level, this routine is a no-op.
6517*/
drh308c2a52010-05-14 11:30:18 +00006518static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006519 unixFile *pFile = (unixFile*)id;
6520 int rc = proxyTakeConch(pFile);
6521 if( rc==SQLITE_OK ){
6522 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006523 if( pCtx->conchHeld>0 ){
6524 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006525 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6526 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006527 }else{
6528 /* conchHeld < 0 is lockless */
6529 }
drh715ff302008-12-03 22:32:44 +00006530 }
6531 return rc;
6532}
6533
6534/*
6535** Close a file that uses proxy locks.
6536*/
6537static int proxyClose(sqlite3_file *id) {
6538 if( id ){
6539 unixFile *pFile = (unixFile*)id;
6540 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6541 unixFile *lockProxy = pCtx->lockProxy;
6542 unixFile *conchFile = pCtx->conchFile;
6543 int rc = SQLITE_OK;
6544
6545 if( lockProxy ){
6546 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6547 if( rc ) return rc;
6548 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6549 if( rc ) return rc;
6550 sqlite3_free(lockProxy);
6551 pCtx->lockProxy = 0;
6552 }
6553 if( conchFile ){
6554 if( pCtx->conchHeld ){
6555 rc = proxyReleaseConch(pFile);
6556 if( rc ) return rc;
6557 }
6558 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6559 if( rc ) return rc;
6560 sqlite3_free(conchFile);
6561 }
drhd56b1212010-08-11 06:14:15 +00006562 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006563 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006564 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006565 /* restore the original locking context and pMethod then close it */
6566 pFile->lockingContext = pCtx->oldLockingContext;
6567 pFile->pMethod = pCtx->pOldMethod;
6568 sqlite3_free(pCtx);
6569 return pFile->pMethod->xClose(id);
6570 }
6571 return SQLITE_OK;
6572}
6573
6574
6575
drhd2cb50b2009-01-09 21:41:17 +00006576#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006577/*
6578** The proxy locking style is intended for use with AFP filesystems.
6579** And since AFP is only supported on MacOSX, the proxy locking is also
6580** restricted to MacOSX.
6581**
6582**
6583******************* End of the proxy lock implementation **********************
6584******************************************************************************/
6585
drh734c9862008-11-28 15:37:20 +00006586/*
danielk1977e339d652008-06-28 11:23:00 +00006587** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006588**
6589** This routine registers all VFS implementations for unix-like operating
6590** systems. This routine, and the sqlite3_os_end() routine that follows,
6591** should be the only routines in this file that are visible from other
6592** files.
drh6b9d6dd2008-12-03 19:34:47 +00006593**
6594** This routine is called once during SQLite initialization and by a
6595** single thread. The memory allocation and mutex subsystems have not
6596** necessarily been initialized when this routine is called, and so they
6597** should not be used.
drh153c62c2007-08-24 03:51:33 +00006598*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006599int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006600 /*
6601 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006602 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6603 ** to the "finder" function. (pAppData is a pointer to a pointer because
6604 ** silly C90 rules prohibit a void* from being cast to a function pointer
6605 ** and so we have to go through the intermediate pointer to avoid problems
6606 ** when compiling with -pedantic-errors on GCC.)
6607 **
6608 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006609 ** finder-function. The finder-function returns a pointer to the
6610 ** sqlite_io_methods object that implements the desired locking
6611 ** behaviors. See the division above that contains the IOMETHODS
6612 ** macro for addition information on finder-functions.
6613 **
6614 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6615 ** object. But the "autolockIoFinder" available on MacOSX does a little
6616 ** more than that; it looks at the filesystem type that hosts the
6617 ** database file and tries to choose an locking method appropriate for
6618 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006619 */
drh7708e972008-11-29 00:56:52 +00006620 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006621 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006622 sizeof(unixFile), /* szOsFile */ \
6623 MAX_PATHNAME, /* mxPathname */ \
6624 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006625 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006626 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006627 unixOpen, /* xOpen */ \
6628 unixDelete, /* xDelete */ \
6629 unixAccess, /* xAccess */ \
6630 unixFullPathname, /* xFullPathname */ \
6631 unixDlOpen, /* xDlOpen */ \
6632 unixDlError, /* xDlError */ \
6633 unixDlSym, /* xDlSym */ \
6634 unixDlClose, /* xDlClose */ \
6635 unixRandomness, /* xRandomness */ \
6636 unixSleep, /* xSleep */ \
6637 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006638 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006639 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006640 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006641 unixGetSystemCall, /* xGetSystemCall */ \
6642 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006643 }
6644
drh6b9d6dd2008-12-03 19:34:47 +00006645 /*
6646 ** All default VFSes for unix are contained in the following array.
6647 **
6648 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6649 ** by the SQLite core when the VFS is registered. So the following
6650 ** array cannot be const.
6651 */
danielk1977e339d652008-06-28 11:23:00 +00006652 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006653#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006654 UNIXVFS("unix", autolockIoFinder ),
6655#else
6656 UNIXVFS("unix", posixIoFinder ),
6657#endif
6658 UNIXVFS("unix-none", nolockIoFinder ),
6659 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006660 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006661#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006662 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006663#endif
6664#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006665 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006666#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006667 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006668#endif
chw78a13182009-04-07 05:35:03 +00006669#endif
drhd2cb50b2009-01-09 21:41:17 +00006670#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006671 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006672 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006673 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006674#endif
drh153c62c2007-08-24 03:51:33 +00006675 };
drh6b9d6dd2008-12-03 19:34:47 +00006676 unsigned int i; /* Loop counter */
6677
6678 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006679 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006680 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006681 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006682 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006683}
danielk1977e339d652008-06-28 11:23:00 +00006684
6685/*
drh6b9d6dd2008-12-03 19:34:47 +00006686** Shutdown the operating system interface.
6687**
6688** Some operating systems might need to do some cleanup in this routine,
6689** to release dynamically allocated objects. But not on unix.
6690** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006691*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006692int sqlite3_os_end(void){
6693 return SQLITE_OK;
6694}
drhdce8bdb2007-08-16 13:01:44 +00006695
danielk197729bafea2008-06-26 10:41:19 +00006696#endif /* SQLITE_OS_UNIX */