blob: 567dcf90c5c045c9d4add65c1e2b7df1add9b1ac [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
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000211 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000212 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000213 int lastErrno; /* The unix errno from last I/O error */
214 void *lockingContext; /* Locking style specific state */
215 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000216 const char *zPath; /* Name of the file */
217 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000218 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000219#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000220 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000221#endif
drh7ed97b92010-01-20 13:07:21 +0000222#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000223 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000224#endif
225#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000226 int isDelete; /* Delete on close if true */
227 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000228#endif
drh8f941bc2009-01-14 23:03:40 +0000229#ifndef NDEBUG
230 /* The next group of variables are used to track whether or not the
231 ** transaction counter in bytes 24-27 of database files are updated
232 ** whenever any part of the database changes. An assertion fault will
233 ** occur if a file is updated without also updating the transaction
234 ** counter. This test is made to avoid new problems similar to the
235 ** one described by ticket #3584.
236 */
237 unsigned char transCntrChng; /* True if the transaction counter changed */
238 unsigned char dbUpdate; /* True if any part of database file changed */
239 unsigned char inNormalWrite; /* True if in a normal write operation */
240#endif
danielk1977967a4a12007-08-20 14:23:44 +0000241#ifdef SQLITE_TEST
242 /* In test mode, increase the size of this structure a bit so that
243 ** it is larger than the struct CrashFile defined in test6.c.
244 */
245 char aPadding[32];
246#endif
drh9cbe6352005-11-29 03:13:21 +0000247};
248
drh0ccebe72005-06-07 22:22:50 +0000249/*
drha7e61d82011-03-12 17:02:57 +0000250** Allowed values for the unixFile.ctrlFlags bitmask:
251*/
drhf0b190d2011-07-26 16:03:07 +0000252#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
253#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
254#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
drh0059eae2011-08-08 23:48:40 +0000255#define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
drha7e61d82011-03-12 17:02:57 +0000256
257/*
drh198bf392006-01-06 21:52:49 +0000258** Include code that is common to all os_*.c files
259*/
260#include "os_common.h"
261
262/*
drh0ccebe72005-06-07 22:22:50 +0000263** Define various macros that are missing from some systems.
264*/
drhbbd42a62004-05-22 17:41:58 +0000265#ifndef O_LARGEFILE
266# define O_LARGEFILE 0
267#endif
268#ifdef SQLITE_DISABLE_LFS
269# undef O_LARGEFILE
270# define O_LARGEFILE 0
271#endif
272#ifndef O_NOFOLLOW
273# define O_NOFOLLOW 0
274#endif
275#ifndef O_BINARY
276# define O_BINARY 0
277#endif
278
279/*
drh2b4b5962005-06-15 17:47:55 +0000280** The threadid macro resolves to the thread-id or to 0. Used for
281** testing and debugging only.
282*/
drhd677b3d2007-08-20 22:48:41 +0000283#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000284#define threadid pthread_self()
285#else
286#define threadid 0
287#endif
288
drh99ab3b12011-03-02 15:09:07 +0000289/*
drh9a3baf12011-04-25 18:01:27 +0000290** Different Unix systems declare open() in different ways. Same use
291** open(const char*,int,mode_t). Others use open(const char*,int,...).
292** The difference is important when using a pointer to the function.
293**
294** The safest way to deal with the problem is to always use this wrapper
295** which always has the same well-defined interface.
296*/
297static int posixOpen(const char *zFile, int flags, int mode){
298 return open(zFile, flags, mode);
299}
300
301/*
drh99ab3b12011-03-02 15:09:07 +0000302** Many system calls are accessed through pointer-to-functions so that
303** they may be overridden at runtime to facilitate fault injection during
304** testing and sandboxing. The following array holds the names and pointers
305** to all overrideable system calls.
306*/
307static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000308 const char *zName; /* Name of the sytem call */
309 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
310 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000311} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000312 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
313#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000314
drh58ad5802011-03-23 22:02:23 +0000315 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000316#define osClose ((int(*)(int))aSyscall[1].pCurrent)
317
drh58ad5802011-03-23 22:02:23 +0000318 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000319#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
320
drh58ad5802011-03-23 22:02:23 +0000321 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000322#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
323
drh58ad5802011-03-23 22:02:23 +0000324 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
326
327/*
328** The DJGPP compiler environment looks mostly like Unix, but it
329** lacks the fcntl() system call. So redefine fcntl() to be something
330** that always succeeds. This means that locking does not occur under
331** DJGPP. But it is DOS - what did you expect?
332*/
333#ifdef __DJGPP__
334 { "fstat", 0, 0 },
335#define osFstat(a,b,c) 0
336#else
drh58ad5802011-03-23 22:02:23 +0000337 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000338#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
339#endif
340
drh58ad5802011-03-23 22:02:23 +0000341 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000342#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
343
drh58ad5802011-03-23 22:02:23 +0000344 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000346
drh58ad5802011-03-23 22:02:23 +0000347 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000348#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
349
drhd4a80312011-04-15 14:33:20 +0000350#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000351 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000352#else
drh58ad5802011-03-23 22:02:23 +0000353 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000354#endif
355#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
356
357#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000358 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000359#else
drh58ad5802011-03-23 22:02:23 +0000360 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000361#endif
362#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000365#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
366
drhd4a80312011-04-15 14:33:20 +0000367#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000368 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000369#else
drh58ad5802011-03-23 22:02:23 +0000370 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000371#endif
372#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
373 aSyscall[12].pCurrent)
374
375#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000376 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000377#else
drh58ad5802011-03-23 22:02:23 +0000378 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000379#endif
380#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
381 aSyscall[13].pCurrent)
382
drha6c47492011-04-11 18:35:09 +0000383#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000384 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000385#else
386 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000387#endif
drh2aa5a002011-04-13 13:42:25 +0000388#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000389
390#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000391 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000392#else
drh58ad5802011-03-23 22:02:23 +0000393 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000394#endif
dan0fd7d862011-03-29 10:04:23 +0000395#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000396
drh036ac7f2011-08-08 23:18:05 +0000397 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
398#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
399
drhe562be52011-03-02 18:01:10 +0000400}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000401
402/*
403** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000404** "unix" VFSes. Return SQLITE_OK opon successfully updating the
405** system call pointer, or SQLITE_NOTFOUND if there is no configurable
406** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000407*/
408static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000409 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
410 const char *zName, /* Name of system call to override */
411 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000412){
drh58ad5802011-03-23 22:02:23 +0000413 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000414 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000415
416 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000417 if( zName==0 ){
418 /* If no zName is given, restore all system calls to their default
419 ** settings and return NULL
420 */
dan51438a72011-04-02 17:00:47 +0000421 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000422 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
423 if( aSyscall[i].pDefault ){
424 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000425 }
426 }
427 }else{
428 /* If zName is specified, operate on only the one system call
429 ** specified.
430 */
431 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
432 if( strcmp(zName, aSyscall[i].zName)==0 ){
433 if( aSyscall[i].pDefault==0 ){
434 aSyscall[i].pDefault = aSyscall[i].pCurrent;
435 }
drh1df30962011-03-02 19:06:42 +0000436 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000437 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
438 aSyscall[i].pCurrent = pNewFunc;
439 break;
440 }
441 }
442 }
443 return rc;
444}
445
drh1df30962011-03-02 19:06:42 +0000446/*
447** Return the value of a system call. Return NULL if zName is not a
448** recognized system call name. NULL is also returned if the system call
449** is currently undefined.
450*/
drh58ad5802011-03-23 22:02:23 +0000451static sqlite3_syscall_ptr unixGetSystemCall(
452 sqlite3_vfs *pNotUsed,
453 const char *zName
454){
455 unsigned int i;
456
457 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000458 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
459 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
460 }
461 return 0;
462}
463
464/*
465** Return the name of the first system call after zName. If zName==NULL
466** then return the name of the first system call. Return NULL if zName
467** is the last system call or if zName is not the name of a valid
468** system call.
469*/
470static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000471 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000472
473 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000474 if( zName ){
475 for(i=0; i<ArraySize(aSyscall)-1; i++){
476 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000477 }
478 }
dan0fd7d862011-03-29 10:04:23 +0000479 for(i++; i<ArraySize(aSyscall); i++){
480 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000481 }
482 return 0;
483}
484
drhad4f1e52011-03-04 15:43:57 +0000485/*
486** Retry open() calls that fail due to EINTR
487*/
488static int robust_open(const char *z, int f, int m){
489 int rc;
490 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
491 return rc;
492}
danielk197713adf8a2004-06-03 16:08:41 +0000493
drh107886a2008-11-21 22:21:50 +0000494/*
dan9359c7b2009-08-21 08:29:10 +0000495** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000496** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000497** vxworksFileId objects used by this file, all of which may be
498** shared by multiple threads.
499**
500** Function unixMutexHeld() is used to assert() that the global mutex
501** is held when required. This function is only used as part of assert()
502** statements. e.g.
503**
504** unixEnterMutex()
505** assert( unixMutexHeld() );
506** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000507*/
508static void unixEnterMutex(void){
509 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
510}
511static void unixLeaveMutex(void){
512 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
513}
dan9359c7b2009-08-21 08:29:10 +0000514#ifdef SQLITE_DEBUG
515static int unixMutexHeld(void) {
516 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
517}
518#endif
drh107886a2008-11-21 22:21:50 +0000519
drh734c9862008-11-28 15:37:20 +0000520
521#ifdef SQLITE_DEBUG
522/*
523** Helper function for printing out trace information from debugging
524** binaries. This returns the string represetation of the supplied
525** integer lock-type.
526*/
drh308c2a52010-05-14 11:30:18 +0000527static const char *azFileLock(int eFileLock){
528 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000529 case NO_LOCK: return "NONE";
530 case SHARED_LOCK: return "SHARED";
531 case RESERVED_LOCK: return "RESERVED";
532 case PENDING_LOCK: return "PENDING";
533 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000534 }
535 return "ERROR";
536}
537#endif
538
539#ifdef SQLITE_LOCK_TRACE
540/*
541** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000542**
drh734c9862008-11-28 15:37:20 +0000543** This routine is used for troubleshooting locks on multithreaded
544** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
545** command-line option on the compiler. This code is normally
546** turned off.
547*/
548static int lockTrace(int fd, int op, struct flock *p){
549 char *zOpName, *zType;
550 int s;
551 int savedErrno;
552 if( op==F_GETLK ){
553 zOpName = "GETLK";
554 }else if( op==F_SETLK ){
555 zOpName = "SETLK";
556 }else{
drh99ab3b12011-03-02 15:09:07 +0000557 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000558 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
559 return s;
560 }
561 if( p->l_type==F_RDLCK ){
562 zType = "RDLCK";
563 }else if( p->l_type==F_WRLCK ){
564 zType = "WRLCK";
565 }else if( p->l_type==F_UNLCK ){
566 zType = "UNLCK";
567 }else{
568 assert( 0 );
569 }
570 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000571 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000572 savedErrno = errno;
573 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
574 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
575 (int)p->l_pid, s);
576 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
577 struct flock l2;
578 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000579 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000580 if( l2.l_type==F_RDLCK ){
581 zType = "RDLCK";
582 }else if( l2.l_type==F_WRLCK ){
583 zType = "WRLCK";
584 }else if( l2.l_type==F_UNLCK ){
585 zType = "UNLCK";
586 }else{
587 assert( 0 );
588 }
589 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
590 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
591 }
592 errno = savedErrno;
593 return s;
594}
drh99ab3b12011-03-02 15:09:07 +0000595#undef osFcntl
596#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000597#endif /* SQLITE_LOCK_TRACE */
598
drhff812312011-02-23 13:33:46 +0000599/*
600** Retry ftruncate() calls that fail due to EINTR
601*/
drhff812312011-02-23 13:33:46 +0000602static int robust_ftruncate(int h, sqlite3_int64 sz){
603 int rc;
drh99ab3b12011-03-02 15:09:07 +0000604 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000605 return rc;
606}
drh734c9862008-11-28 15:37:20 +0000607
608/*
609** This routine translates a standard POSIX errno code into something
610** useful to the clients of the sqlite3 functions. Specifically, it is
611** intended to translate a variety of "try again" errors into SQLITE_BUSY
612** and a variety of "please close the file descriptor NOW" errors into
613** SQLITE_IOERR
614**
615** Errors during initialization of locks, or file system support for locks,
616** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
617*/
618static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
619 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000620#if 0
621 /* At one point this code was not commented out. In theory, this branch
622 ** should never be hit, as this function should only be called after
623 ** a locking-related function (i.e. fcntl()) has returned non-zero with
624 ** the value of errno as the first argument. Since a system call has failed,
625 ** errno should be non-zero.
626 **
627 ** Despite this, if errno really is zero, we still don't want to return
628 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
629 ** propagated back to the caller. Commenting this branch out means errno==0
630 ** will be handled by the "default:" case below.
631 */
drh734c9862008-11-28 15:37:20 +0000632 case 0:
633 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000634#endif
635
drh734c9862008-11-28 15:37:20 +0000636 case EAGAIN:
637 case ETIMEDOUT:
638 case EBUSY:
639 case EINTR:
640 case ENOLCK:
641 /* random NFS retry error, unless during file system support
642 * introspection, in which it actually means what it says */
643 return SQLITE_BUSY;
644
645 case EACCES:
646 /* EACCES is like EAGAIN during locking operations, but not any other time*/
647 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
648 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
649 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
650 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
651 return SQLITE_BUSY;
652 }
653 /* else fall through */
654 case EPERM:
655 return SQLITE_PERM;
656
danea83bc62011-04-01 11:56:32 +0000657 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
658 ** this module never makes such a call. And the code in SQLite itself
659 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
660 ** this case is also commented out. If the system does set errno to EDEADLK,
661 ** the default SQLITE_IOERR_XXX code will be returned. */
662#if 0
drh734c9862008-11-28 15:37:20 +0000663 case EDEADLK:
664 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000665#endif
drh734c9862008-11-28 15:37:20 +0000666
667#if EOPNOTSUPP!=ENOTSUP
668 case EOPNOTSUPP:
669 /* something went terribly awry, unless during file system support
670 * introspection, in which it actually means what it says */
671#endif
672#ifdef ENOTSUP
673 case ENOTSUP:
674 /* invalid fd, unless during file system support introspection, in which
675 * it actually means what it says */
676#endif
677 case EIO:
678 case EBADF:
679 case EINVAL:
680 case ENOTCONN:
681 case ENODEV:
682 case ENXIO:
683 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000684#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000685 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000686#endif
drh734c9862008-11-28 15:37:20 +0000687 case ENOSYS:
688 /* these should force the client to close the file and reconnect */
689
690 default:
691 return sqliteIOErr;
692 }
693}
694
695
696
697/******************************************************************************
698****************** Begin Unique File ID Utility Used By VxWorks ***************
699**
700** On most versions of unix, we can get a unique ID for a file by concatenating
701** the device number and the inode number. But this does not work on VxWorks.
702** On VxWorks, a unique file id must be based on the canonical filename.
703**
704** A pointer to an instance of the following structure can be used as a
705** unique file ID in VxWorks. Each instance of this structure contains
706** a copy of the canonical filename. There is also a reference count.
707** The structure is reclaimed when the number of pointers to it drops to
708** zero.
709**
710** There are never very many files open at one time and lookups are not
711** a performance-critical path, so it is sufficient to put these
712** structures on a linked list.
713*/
714struct vxworksFileId {
715 struct vxworksFileId *pNext; /* Next in a list of them all */
716 int nRef; /* Number of references to this one */
717 int nName; /* Length of the zCanonicalName[] string */
718 char *zCanonicalName; /* Canonical filename */
719};
720
721#if OS_VXWORKS
722/*
drh9b35ea62008-11-29 02:20:26 +0000723** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000724** variable:
725*/
726static struct vxworksFileId *vxworksFileList = 0;
727
728/*
729** Simplify a filename into its canonical form
730** by making the following changes:
731**
732** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000733** * convert /./ into just /
734** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000735**
736** Changes are made in-place. Return the new name length.
737**
738** The original filename is in z[0..n-1]. Return the number of
739** characters in the simplified name.
740*/
741static int vxworksSimplifyName(char *z, int n){
742 int i, j;
743 while( n>1 && z[n-1]=='/' ){ n--; }
744 for(i=j=0; i<n; i++){
745 if( z[i]=='/' ){
746 if( z[i+1]=='/' ) continue;
747 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
748 i += 1;
749 continue;
750 }
751 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
752 while( j>0 && z[j-1]!='/' ){ j--; }
753 if( j>0 ){ j--; }
754 i += 2;
755 continue;
756 }
757 }
758 z[j++] = z[i];
759 }
760 z[j] = 0;
761 return j;
762}
763
764/*
765** Find a unique file ID for the given absolute pathname. Return
766** a pointer to the vxworksFileId object. This pointer is the unique
767** file ID.
768**
769** The nRef field of the vxworksFileId object is incremented before
770** the object is returned. A new vxworksFileId object is created
771** and added to the global list if necessary.
772**
773** If a memory allocation error occurs, return NULL.
774*/
775static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
776 struct vxworksFileId *pNew; /* search key and new file ID */
777 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
778 int n; /* Length of zAbsoluteName string */
779
780 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000781 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000782 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
783 if( pNew==0 ) return 0;
784 pNew->zCanonicalName = (char*)&pNew[1];
785 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
786 n = vxworksSimplifyName(pNew->zCanonicalName, n);
787
788 /* Search for an existing entry that matching the canonical name.
789 ** If found, increment the reference count and return a pointer to
790 ** the existing file ID.
791 */
792 unixEnterMutex();
793 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
794 if( pCandidate->nName==n
795 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
796 ){
797 sqlite3_free(pNew);
798 pCandidate->nRef++;
799 unixLeaveMutex();
800 return pCandidate;
801 }
802 }
803
804 /* No match was found. We will make a new file ID */
805 pNew->nRef = 1;
806 pNew->nName = n;
807 pNew->pNext = vxworksFileList;
808 vxworksFileList = pNew;
809 unixLeaveMutex();
810 return pNew;
811}
812
813/*
814** Decrement the reference count on a vxworksFileId object. Free
815** the object when the reference count reaches zero.
816*/
817static void vxworksReleaseFileId(struct vxworksFileId *pId){
818 unixEnterMutex();
819 assert( pId->nRef>0 );
820 pId->nRef--;
821 if( pId->nRef==0 ){
822 struct vxworksFileId **pp;
823 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
824 assert( *pp==pId );
825 *pp = pId->pNext;
826 sqlite3_free(pId);
827 }
828 unixLeaveMutex();
829}
830#endif /* OS_VXWORKS */
831/*************** End of Unique File ID Utility Used By VxWorks ****************
832******************************************************************************/
833
834
835/******************************************************************************
836*************************** Posix Advisory Locking ****************************
837**
drh9b35ea62008-11-29 02:20:26 +0000838** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000839** section 6.5.2.2 lines 483 through 490 specify that when a process
840** sets or clears a lock, that operation overrides any prior locks set
841** by the same process. It does not explicitly say so, but this implies
842** that it overrides locks set by the same process using a different
843** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000844**
845** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000846** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
847**
848** Suppose ./file1 and ./file2 are really the same file (because
849** one is a hard or symbolic link to the other) then if you set
850** an exclusive lock on fd1, then try to get an exclusive lock
851** on fd2, it works. I would have expected the second lock to
852** fail since there was already a lock on the file due to fd1.
853** But not so. Since both locks came from the same process, the
854** second overrides the first, even though they were on different
855** file descriptors opened on different file names.
856**
drh734c9862008-11-28 15:37:20 +0000857** This means that we cannot use POSIX locks to synchronize file access
858** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000859** to synchronize access for threads in separate processes, but not
860** threads within the same process.
861**
862** To work around the problem, SQLite has to manage file locks internally
863** on its own. Whenever a new database is opened, we have to find the
864** specific inode of the database file (the inode is determined by the
865** st_dev and st_ino fields of the stat structure that fstat() fills in)
866** and check for locks already existing on that inode. When locks are
867** created or removed, we have to look at our own internal record of the
868** locks to see if another thread has previously set a lock on that same
869** inode.
870**
drh9b35ea62008-11-29 02:20:26 +0000871** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
872** For VxWorks, we have to use the alternative unique ID system based on
873** canonical filename and implemented in the previous division.)
874**
danielk1977ad94b582007-08-20 06:44:22 +0000875** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000876** descriptor. It is now a structure that holds the integer file
877** descriptor and a pointer to a structure that describes the internal
878** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000879** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000880** point to the same locking structure. The locking structure keeps
881** a reference count (so we will know when to delete it) and a "cnt"
882** field that tells us its internal lock status. cnt==0 means the
883** file is unlocked. cnt==-1 means the file has an exclusive lock.
884** cnt>0 means there are cnt shared locks on the file.
885**
886** Any attempt to lock or unlock a file first checks the locking
887** structure. The fcntl() system call is only invoked to set a
888** POSIX lock if the internal lock structure transitions between
889** a locked and an unlocked state.
890**
drh734c9862008-11-28 15:37:20 +0000891** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000892**
893** If you close a file descriptor that points to a file that has locks,
894** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000895** released. To work around this problem, each unixInodeInfo object
896** maintains a count of the number of pending locks on tha inode.
897** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000898** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000899** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000900** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000901** be closed and that list is walked (and cleared) when the last lock
902** clears.
903**
drh9b35ea62008-11-29 02:20:26 +0000904** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000905**
drh9b35ea62008-11-29 02:20:26 +0000906** Many older versions of linux use the LinuxThreads library which is
907** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000908** A cannot be modified or overridden by a different thread B.
909** Only thread A can modify the lock. Locking behavior is correct
910** if the appliation uses the newer Native Posix Thread Library (NPTL)
911** on linux - with NPTL a lock created by thread A can override locks
912** in thread B. But there is no way to know at compile-time which
913** threading library is being used. So there is no way to know at
914** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000915** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000916** current process.
drh5fdae772004-06-29 03:29:00 +0000917**
drh8af6c222010-05-14 12:43:01 +0000918** SQLite used to support LinuxThreads. But support for LinuxThreads
919** was dropped beginning with version 3.7.0. SQLite will still work with
920** LinuxThreads provided that (1) there is no more than one connection
921** per database file in the same process and (2) database connections
922** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000923*/
924
925/*
926** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000927** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000928*/
929struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000930 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000931#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000932 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000933#else
drh107886a2008-11-21 22:21:50 +0000934 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000935#endif
936};
937
938/*
drhbbd42a62004-05-22 17:41:58 +0000939** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000940** inode. Or, on LinuxThreads, there is one of these structures for
941** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000942**
danielk1977ad94b582007-08-20 06:44:22 +0000943** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000944** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000945** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000946*/
drh8af6c222010-05-14 12:43:01 +0000947struct unixInodeInfo {
948 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000949 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000950 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
951 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000952 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000953 unixShmNode *pShmNode; /* Shared memory associated with this inode */
954 int nLock; /* Number of outstanding file locks */
955 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
956 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
957 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000958#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000959 unsigned long long sharedByte; /* for AFP simulated shared lock */
960#endif
drh6c7d5c52008-11-21 20:32:33 +0000961#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000962 sem_t *pSem; /* Named POSIX semaphore */
963 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000964#endif
drhbbd42a62004-05-22 17:41:58 +0000965};
966
drhda0e7682008-07-30 15:27:54 +0000967/*
drh8af6c222010-05-14 12:43:01 +0000968** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000969*/
drhd91c68f2010-05-14 14:52:25 +0000970static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000971
drh5fdae772004-06-29 03:29:00 +0000972/*
dane18d4952011-02-21 11:46:24 +0000973**
974** This function - unixLogError_x(), is only ever called via the macro
975** unixLogError().
976**
977** It is invoked after an error occurs in an OS function and errno has been
978** set. It logs a message using sqlite3_log() containing the current value of
979** errno and, if possible, the human-readable equivalent from strerror() or
980** strerror_r().
981**
982** The first argument passed to the macro should be the error code that
983** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
984** The two subsequent arguments should be the name of the OS function that
985** failed (e.g. "unlink", "open") and the the associated file-system path,
986** if any.
987*/
drh0e9365c2011-03-02 02:08:13 +0000988#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
989static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000990 int errcode, /* SQLite error code */
991 const char *zFunc, /* Name of OS function that failed */
992 const char *zPath, /* File path associated with error */
993 int iLine /* Source line number where error occurred */
994){
995 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000996 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000997
998 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
999 ** the strerror() function to obtain the human-readable error message
1000 ** equivalent to errno. Otherwise, use strerror_r().
1001 */
1002#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1003 char aErr[80];
1004 memset(aErr, 0, sizeof(aErr));
1005 zErr = aErr;
1006
1007 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1008 ** assume that the system provides the the GNU version of strerror_r() that
1009 ** returns a pointer to a buffer containing the error message. That pointer
1010 ** may point to aErr[], or it may point to some static storage somewhere.
1011 ** Otherwise, assume that the system provides the POSIX version of
1012 ** strerror_r(), which always writes an error message into aErr[].
1013 **
1014 ** If the code incorrectly assumes that it is the POSIX version that is
1015 ** available, the error message will often be an empty string. Not a
1016 ** huge problem. Incorrectly concluding that the GNU version is available
1017 ** could lead to a segfault though.
1018 */
1019#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1020 zErr =
1021# endif
drh0e9365c2011-03-02 02:08:13 +00001022 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001023
1024#elif SQLITE_THREADSAFE
1025 /* This is a threadsafe build, but strerror_r() is not available. */
1026 zErr = "";
1027#else
1028 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001029 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001030#endif
1031
1032 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001033 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001034 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001035 "os_unix.c:%d: (%d) %s(%s) - %s",
1036 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001037 );
1038
1039 return errcode;
1040}
1041
drh0e9365c2011-03-02 02:08:13 +00001042/*
1043** Close a file descriptor.
1044**
1045** We assume that close() almost always works, since it is only in a
1046** very sick application or on a very sick platform that it might fail.
1047** If it does fail, simply leak the file descriptor, but do log the
1048** error.
1049**
1050** Note that it is not safe to retry close() after EINTR since the
1051** file descriptor might have already been reused by another thread.
1052** So we don't even try to recover from an EINTR. Just log the error
1053** and move on.
1054*/
1055static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001056 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001057 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1058 pFile ? pFile->zPath : 0, lineno);
1059 }
1060}
dane18d4952011-02-21 11:46:24 +00001061
1062/*
danb0ac3e32010-06-16 10:55:42 +00001063** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001064*/
drh0e9365c2011-03-02 02:08:13 +00001065static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001066 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001067 UnixUnusedFd *p;
1068 UnixUnusedFd *pNext;
1069 for(p=pInode->pUnused; p; p=pNext){
1070 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001071 robust_close(pFile, p->fd, __LINE__);
1072 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001073 }
drh0e9365c2011-03-02 02:08:13 +00001074 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001075}
1076
1077/*
drh8af6c222010-05-14 12:43:01 +00001078** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001079**
1080** The mutex entered using the unixEnterMutex() function must be held
1081** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001082*/
danb0ac3e32010-06-16 10:55:42 +00001083static void releaseInodeInfo(unixFile *pFile){
1084 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001085 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001086 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001087 pInode->nRef--;
1088 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001089 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001090 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001091 if( pInode->pPrev ){
1092 assert( pInode->pPrev->pNext==pInode );
1093 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001094 }else{
drh8af6c222010-05-14 12:43:01 +00001095 assert( inodeList==pInode );
1096 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001097 }
drh8af6c222010-05-14 12:43:01 +00001098 if( pInode->pNext ){
1099 assert( pInode->pNext->pPrev==pInode );
1100 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001101 }
drh8af6c222010-05-14 12:43:01 +00001102 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001103 }
drhbbd42a62004-05-22 17:41:58 +00001104 }
1105}
1106
1107/*
drh8af6c222010-05-14 12:43:01 +00001108** Given a file descriptor, locate the unixInodeInfo object that
1109** describes that file descriptor. Create a new one if necessary. The
1110** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001111**
dan9359c7b2009-08-21 08:29:10 +00001112** The mutex entered using the unixEnterMutex() function must be held
1113** when this function is called.
1114**
drh6c7d5c52008-11-21 20:32:33 +00001115** Return an appropriate error code.
1116*/
drh8af6c222010-05-14 12:43:01 +00001117static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001118 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001119 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001120){
1121 int rc; /* System call return code */
1122 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001123 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1124 struct stat statbuf; /* Low-level file information */
1125 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001126
dan9359c7b2009-08-21 08:29:10 +00001127 assert( unixMutexHeld() );
1128
drh6c7d5c52008-11-21 20:32:33 +00001129 /* Get low-level information about the file that we can used to
1130 ** create a unique name for the file.
1131 */
1132 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001133 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001134 if( rc!=0 ){
1135 pFile->lastErrno = errno;
1136#ifdef EOVERFLOW
1137 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1138#endif
1139 return SQLITE_IOERR;
1140 }
1141
drheb0d74f2009-02-03 15:27:02 +00001142#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001143 /* On OS X on an msdos filesystem, the inode number is reported
1144 ** incorrectly for zero-size files. See ticket #3260. To work
1145 ** around this problem (we consider it a bug in OS X, not SQLite)
1146 ** we always increase the file size to 1 by writing a single byte
1147 ** prior to accessing the inode number. The one byte written is
1148 ** an ASCII 'S' character which also happens to be the first byte
1149 ** in the header of every SQLite database. In this way, if there
1150 ** is a race condition such that another thread has already populated
1151 ** the first page of the database, no damage is done.
1152 */
drh7ed97b92010-01-20 13:07:21 +00001153 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001154 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001155 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001156 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001157 return SQLITE_IOERR;
1158 }
drh99ab3b12011-03-02 15:09:07 +00001159 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001160 if( rc!=0 ){
1161 pFile->lastErrno = errno;
1162 return SQLITE_IOERR;
1163 }
1164 }
drheb0d74f2009-02-03 15:27:02 +00001165#endif
drh6c7d5c52008-11-21 20:32:33 +00001166
drh8af6c222010-05-14 12:43:01 +00001167 memset(&fileId, 0, sizeof(fileId));
1168 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001169#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001170 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001171#else
drh8af6c222010-05-14 12:43:01 +00001172 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001173#endif
drh8af6c222010-05-14 12:43:01 +00001174 pInode = inodeList;
1175 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1176 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001177 }
drh8af6c222010-05-14 12:43:01 +00001178 if( pInode==0 ){
1179 pInode = sqlite3_malloc( sizeof(*pInode) );
1180 if( pInode==0 ){
1181 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001182 }
drh8af6c222010-05-14 12:43:01 +00001183 memset(pInode, 0, sizeof(*pInode));
1184 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1185 pInode->nRef = 1;
1186 pInode->pNext = inodeList;
1187 pInode->pPrev = 0;
1188 if( inodeList ) inodeList->pPrev = pInode;
1189 inodeList = pInode;
1190 }else{
1191 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 *ppInode = pInode;
1194 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001195}
drh6c7d5c52008-11-21 20:32:33 +00001196
aswift5b1a2562008-08-22 00:22:35 +00001197
1198/*
danielk197713adf8a2004-06-03 16:08:41 +00001199** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001200** file by this or any other process. If such a lock is held, set *pResOut
1201** to a non-zero value otherwise *pResOut is set to zero. The return value
1202** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001203*/
danielk1977861f7452008-06-05 11:39:11 +00001204static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001205 int rc = SQLITE_OK;
1206 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001207 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001208
danielk1977861f7452008-06-05 11:39:11 +00001209 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1210
drh054889e2005-11-30 03:20:31 +00001211 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001212 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001213
1214 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001215 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001216 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001217 }
1218
drh2ac3ee92004-06-07 16:27:46 +00001219 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001220 */
danielk197709480a92009-02-09 05:32:32 +00001221#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001222 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001223 struct flock lock;
1224 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001225 lock.l_start = RESERVED_BYTE;
1226 lock.l_len = 1;
1227 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001228 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1229 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1230 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001231 } else if( lock.l_type!=F_UNLCK ){
1232 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001233 }
1234 }
danielk197709480a92009-02-09 05:32:32 +00001235#endif
danielk197713adf8a2004-06-03 16:08:41 +00001236
drh6c7d5c52008-11-21 20:32:33 +00001237 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001238 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001239
aswift5b1a2562008-08-22 00:22:35 +00001240 *pResOut = reserved;
1241 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001242}
1243
1244/*
drha7e61d82011-03-12 17:02:57 +00001245** Attempt to set a system-lock on the file pFile. The lock is
1246** described by pLock.
1247**
drh77197112011-03-15 19:08:48 +00001248** If the pFile was opened read/write from unix-excl, then the only lock
1249** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001250** the first time any lock is attempted. All subsequent system locking
1251** operations become no-ops. Locking operations still happen internally,
1252** in order to coordinate access between separate database connections
1253** within this process, but all of that is handled in memory and the
1254** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001255**
1256** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1257** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1258** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001259**
1260** Zero is returned if the call completes successfully, or -1 if a call
1261** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001262*/
1263static int unixFileLock(unixFile *pFile, struct flock *pLock){
1264 int rc;
drh3cb93392011-03-12 18:10:44 +00001265 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001266 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001267 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001268 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1269 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1270 ){
drh3cb93392011-03-12 18:10:44 +00001271 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001272 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001273 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001274 lock.l_whence = SEEK_SET;
1275 lock.l_start = SHARED_FIRST;
1276 lock.l_len = SHARED_SIZE;
1277 lock.l_type = F_WRLCK;
1278 rc = osFcntl(pFile->h, F_SETLK, &lock);
1279 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001280 pInode->bProcessLock = 1;
1281 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001282 }else{
1283 rc = 0;
1284 }
1285 }else{
1286 rc = osFcntl(pFile->h, F_SETLK, pLock);
1287 }
1288 return rc;
1289}
1290
1291/*
drh308c2a52010-05-14 11:30:18 +00001292** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001293** of the following:
1294**
drh2ac3ee92004-06-07 16:27:46 +00001295** (1) SHARED_LOCK
1296** (2) RESERVED_LOCK
1297** (3) PENDING_LOCK
1298** (4) EXCLUSIVE_LOCK
1299**
drhb3e04342004-06-08 00:47:47 +00001300** Sometimes when requesting one lock state, additional lock states
1301** are inserted in between. The locking might fail on one of the later
1302** transitions leaving the lock state different from what it started but
1303** still short of its goal. The following chart shows the allowed
1304** transitions and the inserted intermediate states:
1305**
1306** UNLOCKED -> SHARED
1307** SHARED -> RESERVED
1308** SHARED -> (PENDING) -> EXCLUSIVE
1309** RESERVED -> (PENDING) -> EXCLUSIVE
1310** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001311**
drha6abd042004-06-09 17:37:22 +00001312** This routine will only increase a lock. Use the sqlite3OsUnlock()
1313** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001314*/
drh308c2a52010-05-14 11:30:18 +00001315static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001316 /* The following describes the implementation of the various locks and
1317 ** lock transitions in terms of the POSIX advisory shared and exclusive
1318 ** lock primitives (called read-locks and write-locks below, to avoid
1319 ** confusion with SQLite lock names). The algorithms are complicated
1320 ** slightly in order to be compatible with windows systems simultaneously
1321 ** accessing the same database file, in case that is ever required.
1322 **
1323 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1324 ** byte', each single bytes at well known offsets, and the 'shared byte
1325 ** range', a range of 510 bytes at a well known offset.
1326 **
1327 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1328 ** byte'. If this is successful, a random byte from the 'shared byte
1329 ** range' is read-locked and the lock on the 'pending byte' released.
1330 **
danielk197790ba3bd2004-06-25 08:32:25 +00001331 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1332 ** A RESERVED lock is implemented by grabbing a write-lock on the
1333 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001334 **
1335 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001336 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1337 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1338 ** obtained, but existing SHARED locks are allowed to persist. A process
1339 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1340 ** This property is used by the algorithm for rolling back a journal file
1341 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001342 **
danielk197790ba3bd2004-06-25 08:32:25 +00001343 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1344 ** implemented by obtaining a write-lock on the entire 'shared byte
1345 ** range'. Since all other locks require a read-lock on one of the bytes
1346 ** within this range, this ensures that no other locks are held on the
1347 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001348 **
1349 ** The reason a single byte cannot be used instead of the 'shared byte
1350 ** range' is that some versions of windows do not support read-locks. By
1351 ** locking a random byte from a range, concurrent SHARED locks may exist
1352 ** even if the locking primitive used is always a write-lock.
1353 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001355 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001356 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001357 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001358 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001359
drh054889e2005-11-30 03:20:31 +00001360 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001361 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1362 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001363 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001364
1365 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001366 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001367 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001368 */
drh308c2a52010-05-14 11:30:18 +00001369 if( pFile->eFileLock>=eFileLock ){
1370 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1371 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 return SQLITE_OK;
1373 }
1374
drh0c2694b2009-09-03 16:23:44 +00001375 /* Make sure the locking sequence is correct.
1376 ** (1) We never move from unlocked to anything higher than shared lock.
1377 ** (2) SQLite never explicitly requests a pendig lock.
1378 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001379 */
drh308c2a52010-05-14 11:30:18 +00001380 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1381 assert( eFileLock!=PENDING_LOCK );
1382 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001383
drh8af6c222010-05-14 12:43:01 +00001384 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001385 */
drh6c7d5c52008-11-21 20:32:33 +00001386 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001387 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001388
danielk1977ad94b582007-08-20 06:44:22 +00001389 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001390 ** handle that precludes the requested lock, return BUSY.
1391 */
drh8af6c222010-05-14 12:43:01 +00001392 if( (pFile->eFileLock!=pInode->eFileLock &&
1393 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001394 ){
1395 rc = SQLITE_BUSY;
1396 goto end_lock;
1397 }
1398
1399 /* If a SHARED lock is requested, and some thread using this PID already
1400 ** has a SHARED or RESERVED lock, then increment reference counts and
1401 ** return SQLITE_OK.
1402 */
drh308c2a52010-05-14 11:30:18 +00001403 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001404 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001405 assert( eFileLock==SHARED_LOCK );
1406 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001407 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001408 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001409 pInode->nShared++;
1410 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001411 goto end_lock;
1412 }
1413
danielk19779a1d0ab2004-06-01 14:09:28 +00001414
drh3cde3bb2004-06-12 02:17:14 +00001415 /* A PENDING lock is needed before acquiring a SHARED lock and before
1416 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1417 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001418 */
drh0c2694b2009-09-03 16:23:44 +00001419 lock.l_len = 1L;
1420 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001421 if( eFileLock==SHARED_LOCK
1422 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001423 ){
drh308c2a52010-05-14 11:30:18 +00001424 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001425 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001426 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001427 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001428 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001429 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001430 pFile->lastErrno = tErrno;
1431 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 goto end_lock;
1433 }
drh3cde3bb2004-06-12 02:17:14 +00001434 }
1435
1436
1437 /* If control gets to this point, then actually go ahead and make
1438 ** operating system calls for the specified lock.
1439 */
drh308c2a52010-05-14 11:30:18 +00001440 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001441 assert( pInode->nShared==0 );
1442 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001443 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001444
drh2ac3ee92004-06-07 16:27:46 +00001445 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001446 lock.l_start = SHARED_FIRST;
1447 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001448 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001449 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001450 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001451 }
dan661d71a2011-03-30 19:08:03 +00001452
drh2ac3ee92004-06-07 16:27:46 +00001453 /* Drop the temporary PENDING lock */
1454 lock.l_start = PENDING_BYTE;
1455 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001456 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001457 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1458 /* This could happen with a network mount */
1459 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001460 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001461 }
dan661d71a2011-03-30 19:08:03 +00001462
1463 if( rc ){
1464 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001465 pFile->lastErrno = tErrno;
1466 }
dan661d71a2011-03-30 19:08:03 +00001467 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001468 }else{
drh308c2a52010-05-14 11:30:18 +00001469 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001470 pInode->nLock++;
1471 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001472 }
drh8af6c222010-05-14 12:43:01 +00001473 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001474 /* We are trying for an exclusive lock but another thread in this
1475 ** same process is still holding a shared lock. */
1476 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001477 }else{
drh3cde3bb2004-06-12 02:17:14 +00001478 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001479 ** assumed that there is a SHARED or greater lock on the file
1480 ** already.
1481 */
drh308c2a52010-05-14 11:30:18 +00001482 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001483 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001484
1485 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1486 if( eFileLock==RESERVED_LOCK ){
1487 lock.l_start = RESERVED_BYTE;
1488 lock.l_len = 1L;
1489 }else{
1490 lock.l_start = SHARED_FIRST;
1491 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001492 }
dan661d71a2011-03-30 19:08:03 +00001493
1494 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001495 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001496 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001497 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001498 pFile->lastErrno = tErrno;
1499 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001500 }
drhbbd42a62004-05-22 17:41:58 +00001501 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001502
drh8f941bc2009-01-14 23:03:40 +00001503
1504#ifndef NDEBUG
1505 /* Set up the transaction-counter change checking flags when
1506 ** transitioning from a SHARED to a RESERVED lock. The change
1507 ** from SHARED to RESERVED marks the beginning of a normal
1508 ** write operation (not a hot journal rollback).
1509 */
1510 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001511 && pFile->eFileLock<=SHARED_LOCK
1512 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001513 ){
1514 pFile->transCntrChng = 0;
1515 pFile->dbUpdate = 0;
1516 pFile->inNormalWrite = 1;
1517 }
1518#endif
1519
1520
danielk1977ecb2a962004-06-02 06:30:16 +00001521 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001522 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001523 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001524 }else if( eFileLock==EXCLUSIVE_LOCK ){
1525 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001526 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001527 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001528
1529end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001530 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001531 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1532 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001533 return rc;
1534}
1535
1536/*
dan08da86a2009-08-21 17:18:03 +00001537** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001538** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001539*/
1540static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001541 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001542 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001543 p->pNext = pInode->pUnused;
1544 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001545 pFile->h = -1;
1546 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001547}
1548
1549/*
drh308c2a52010-05-14 11:30:18 +00001550** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001551** must be either NO_LOCK or SHARED_LOCK.
1552**
1553** If the locking level of the file descriptor is already at or below
1554** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001555**
1556** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1557** the byte range is divided into 2 parts and the first part is unlocked then
1558** set to a read lock, then the other part is simply unlocked. This works
1559** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1560** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001561*/
drha7e61d82011-03-12 17:02:57 +00001562static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001563 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001564 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001565 struct flock lock;
1566 int rc = SQLITE_OK;
1567 int h;
drha6abd042004-06-09 17:37:22 +00001568
drh054889e2005-11-30 03:20:31 +00001569 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001570 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001571 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001572 getpid()));
drha6abd042004-06-09 17:37:22 +00001573
drh308c2a52010-05-14 11:30:18 +00001574 assert( eFileLock<=SHARED_LOCK );
1575 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001576 return SQLITE_OK;
1577 }
drh6c7d5c52008-11-21 20:32:33 +00001578 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001579 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001580 pInode = pFile->pInode;
1581 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001582 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001584 SimulateIOErrorBenign(1);
1585 SimulateIOError( h=(-1) )
1586 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001587
1588#ifndef NDEBUG
1589 /* When reducing a lock such that other processes can start
1590 ** reading the database file again, make sure that the
1591 ** transaction counter was updated if any part of the database
1592 ** file changed. If the transaction counter is not updated,
1593 ** other connections to the same file might not realize that
1594 ** the file has changed and hence might not know to flush their
1595 ** cache. The use of a stale cache can lead to database corruption.
1596 */
dan7c246102010-04-12 19:00:29 +00001597#if 0
drh8f941bc2009-01-14 23:03:40 +00001598 assert( pFile->inNormalWrite==0
1599 || pFile->dbUpdate==0
1600 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001601#endif
drh8f941bc2009-01-14 23:03:40 +00001602 pFile->inNormalWrite = 0;
1603#endif
1604
drh7ed97b92010-01-20 13:07:21 +00001605 /* downgrading to a shared lock on NFS involves clearing the write lock
1606 ** before establishing the readlock - to avoid a race condition we downgrade
1607 ** the lock in 2 blocks, so that part of the range will be covered by a
1608 ** write lock until the rest is covered by a read lock:
1609 ** 1: [WWWWW]
1610 ** 2: [....W]
1611 ** 3: [RRRRW]
1612 ** 4: [RRRR.]
1613 */
drh308c2a52010-05-14 11:30:18 +00001614 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001615
1616#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001617 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001618 assert( handleNFSUnlock==0 );
1619#endif
1620#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001621 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001622 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001623 off_t divSize = SHARED_SIZE - 1;
1624
1625 lock.l_type = F_UNLCK;
1626 lock.l_whence = SEEK_SET;
1627 lock.l_start = SHARED_FIRST;
1628 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001629 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001630 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001631 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001632 if( IS_LOCK_ERROR(rc) ){
1633 pFile->lastErrno = tErrno;
1634 }
1635 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001636 }
drh7ed97b92010-01-20 13:07:21 +00001637 lock.l_type = F_RDLCK;
1638 lock.l_whence = SEEK_SET;
1639 lock.l_start = SHARED_FIRST;
1640 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001641 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001642 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001643 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1644 if( IS_LOCK_ERROR(rc) ){
1645 pFile->lastErrno = tErrno;
1646 }
1647 goto end_unlock;
1648 }
1649 lock.l_type = F_UNLCK;
1650 lock.l_whence = SEEK_SET;
1651 lock.l_start = SHARED_FIRST+divSize;
1652 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001653 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001654 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001655 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001656 if( IS_LOCK_ERROR(rc) ){
1657 pFile->lastErrno = tErrno;
1658 }
1659 goto end_unlock;
1660 }
drh30f776f2011-02-25 03:25:07 +00001661 }else
1662#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1663 {
drh7ed97b92010-01-20 13:07:21 +00001664 lock.l_type = F_RDLCK;
1665 lock.l_whence = SEEK_SET;
1666 lock.l_start = SHARED_FIRST;
1667 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001668 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001669 /* In theory, the call to unixFileLock() cannot fail because another
1670 ** process is holding an incompatible lock. If it does, this
1671 ** indicates that the other process is not following the locking
1672 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1673 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1674 ** an assert to fail). */
1675 rc = SQLITE_IOERR_RDLOCK;
1676 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001677 goto end_unlock;
1678 }
drh9c105bb2004-10-02 20:38:28 +00001679 }
1680 }
drhbbd42a62004-05-22 17:41:58 +00001681 lock.l_type = F_UNLCK;
1682 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001683 lock.l_start = PENDING_BYTE;
1684 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001685 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001686 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001687 }else{
danea83bc62011-04-01 11:56:32 +00001688 rc = SQLITE_IOERR_UNLOCK;
1689 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001690 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001691 }
drhbbd42a62004-05-22 17:41:58 +00001692 }
drh308c2a52010-05-14 11:30:18 +00001693 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001694 /* Decrement the shared lock counter. Release the lock using an
1695 ** OS call only when all threads in this same process have released
1696 ** the lock.
1697 */
drh8af6c222010-05-14 12:43:01 +00001698 pInode->nShared--;
1699 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001700 lock.l_type = F_UNLCK;
1701 lock.l_whence = SEEK_SET;
1702 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001703 SimulateIOErrorBenign(1);
1704 SimulateIOError( h=(-1) )
1705 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001706 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001707 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001708 }else{
danea83bc62011-04-01 11:56:32 +00001709 rc = SQLITE_IOERR_UNLOCK;
1710 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001711 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001712 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001713 }
drha6abd042004-06-09 17:37:22 +00001714 }
1715
drhbbd42a62004-05-22 17:41:58 +00001716 /* Decrement the count of locks against this same file. When the
1717 ** count reaches zero, close any other file descriptors whose close
1718 ** was deferred because of outstanding locks.
1719 */
drh8af6c222010-05-14 12:43:01 +00001720 pInode->nLock--;
1721 assert( pInode->nLock>=0 );
1722 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001723 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001724 }
1725 }
aswift5b1a2562008-08-22 00:22:35 +00001726
1727end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001728 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001729 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001730 return rc;
drhbbd42a62004-05-22 17:41:58 +00001731}
1732
1733/*
drh308c2a52010-05-14 11:30:18 +00001734** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001735** must be either NO_LOCK or SHARED_LOCK.
1736**
1737** If the locking level of the file descriptor is already at or below
1738** the requested locking level, this routine is a no-op.
1739*/
drh308c2a52010-05-14 11:30:18 +00001740static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001741 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001742}
1743
1744/*
danielk1977e339d652008-06-28 11:23:00 +00001745** This function performs the parts of the "close file" operation
1746** common to all locking schemes. It closes the directory and file
1747** handles, if they are valid, and sets all fields of the unixFile
1748** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001749**
1750** It is *not* necessary to hold the mutex when this routine is called,
1751** even on VxWorks. A mutex will be acquired on VxWorks by the
1752** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001753*/
1754static int closeUnixFile(sqlite3_file *id){
1755 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001756 if( pFile->h>=0 ){
1757 robust_close(pFile, pFile->h, __LINE__);
1758 pFile->h = -1;
1759 }
1760#if OS_VXWORKS
1761 if( pFile->pId ){
1762 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001763 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001764 }
1765 vxworksReleaseFileId(pFile->pId);
1766 pFile->pId = 0;
1767 }
1768#endif
1769 OSTRACE(("CLOSE %-3d\n", pFile->h));
1770 OpenCounter(-1);
1771 sqlite3_free(pFile->pUnused);
1772 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001773 return SQLITE_OK;
1774}
1775
1776/*
danielk1977e3026632004-06-22 11:29:02 +00001777** Close a file.
1778*/
danielk197762079062007-08-15 17:08:46 +00001779static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001780 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001781 unixFile *pFile = (unixFile *)id;
1782 unixUnlock(id, NO_LOCK);
1783 unixEnterMutex();
1784
1785 /* unixFile.pInode is always valid here. Otherwise, a different close
1786 ** routine (e.g. nolockClose()) would be called instead.
1787 */
1788 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1789 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1790 /* If there are outstanding locks, do not actually close the file just
1791 ** yet because that would clear those locks. Instead, add the file
1792 ** descriptor to pInode->pUnused list. It will be automatically closed
1793 ** when the last lock is cleared.
1794 */
1795 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001796 }
dan661d71a2011-03-30 19:08:03 +00001797 releaseInodeInfo(pFile);
1798 rc = closeUnixFile(id);
1799 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001800 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001801}
1802
drh734c9862008-11-28 15:37:20 +00001803/************** End of the posix advisory lock implementation *****************
1804******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001805
drh734c9862008-11-28 15:37:20 +00001806/******************************************************************************
1807****************************** No-op Locking **********************************
1808**
1809** Of the various locking implementations available, this is by far the
1810** simplest: locking is ignored. No attempt is made to lock the database
1811** file for reading or writing.
1812**
1813** This locking mode is appropriate for use on read-only databases
1814** (ex: databases that are burned into CD-ROM, for example.) It can
1815** also be used if the application employs some external mechanism to
1816** prevent simultaneous access of the same database by two or more
1817** database connections. But there is a serious risk of database
1818** corruption if this locking mode is used in situations where multiple
1819** database connections are accessing the same database file at the same
1820** time and one or more of those connections are writing.
1821*/
drhbfe66312006-10-03 17:40:40 +00001822
drh734c9862008-11-28 15:37:20 +00001823static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1824 UNUSED_PARAMETER(NotUsed);
1825 *pResOut = 0;
1826 return SQLITE_OK;
1827}
drh734c9862008-11-28 15:37:20 +00001828static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1829 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1830 return SQLITE_OK;
1831}
drh734c9862008-11-28 15:37:20 +00001832static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1833 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1834 return SQLITE_OK;
1835}
1836
1837/*
drh9b35ea62008-11-29 02:20:26 +00001838** Close the file.
drh734c9862008-11-28 15:37:20 +00001839*/
1840static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001841 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001842}
1843
1844/******************* End of the no-op lock implementation *********************
1845******************************************************************************/
1846
1847/******************************************************************************
1848************************* Begin dot-file Locking ******************************
1849**
drh0c2694b2009-09-03 16:23:44 +00001850** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001851** files in order to control access to the database. This works on just
1852** about every filesystem imaginable. But there are serious downsides:
1853**
1854** (1) There is zero concurrency. A single reader blocks all other
1855** connections from reading or writing the database.
1856**
1857** (2) An application crash or power loss can leave stale lock files
1858** sitting around that need to be cleared manually.
1859**
1860** Nevertheless, a dotlock is an appropriate locking mode for use if no
1861** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001862**
1863** Dotfile locking works by creating a file in the same directory as the
1864** database and with the same name but with a ".lock" extension added.
1865** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1866** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001867*/
1868
1869/*
1870** The file suffix added to the data base filename in order to create the
1871** lock file.
1872*/
1873#define DOTLOCK_SUFFIX ".lock"
1874
drh7708e972008-11-29 00:56:52 +00001875/*
1876** This routine checks if there is a RESERVED lock held on the specified
1877** file by this or any other process. If such a lock is held, set *pResOut
1878** to a non-zero value otherwise *pResOut is set to zero. The return value
1879** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1880**
1881** In dotfile locking, either a lock exists or it does not. So in this
1882** variation of CheckReservedLock(), *pResOut is set to true if any lock
1883** is held on the file and false if the file is unlocked.
1884*/
drh734c9862008-11-28 15:37:20 +00001885static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1886 int rc = SQLITE_OK;
1887 int reserved = 0;
1888 unixFile *pFile = (unixFile*)id;
1889
1890 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1891
1892 assert( pFile );
1893
1894 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001895 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001896 /* Either this connection or some other connection in the same process
1897 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001898 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001899 }else{
1900 /* The lock is held if and only if the lockfile exists */
1901 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001902 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001903 }
drh308c2a52010-05-14 11:30:18 +00001904 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001905 *pResOut = reserved;
1906 return rc;
1907}
1908
drh7708e972008-11-29 00:56:52 +00001909/*
drh308c2a52010-05-14 11:30:18 +00001910** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001911** of the following:
1912**
1913** (1) SHARED_LOCK
1914** (2) RESERVED_LOCK
1915** (3) PENDING_LOCK
1916** (4) EXCLUSIVE_LOCK
1917**
1918** Sometimes when requesting one lock state, additional lock states
1919** are inserted in between. The locking might fail on one of the later
1920** transitions leaving the lock state different from what it started but
1921** still short of its goal. The following chart shows the allowed
1922** transitions and the inserted intermediate states:
1923**
1924** UNLOCKED -> SHARED
1925** SHARED -> RESERVED
1926** SHARED -> (PENDING) -> EXCLUSIVE
1927** RESERVED -> (PENDING) -> EXCLUSIVE
1928** PENDING -> EXCLUSIVE
1929**
1930** This routine will only increase a lock. Use the sqlite3OsUnlock()
1931** routine to lower a locking level.
1932**
1933** With dotfile locking, we really only support state (4): EXCLUSIVE.
1934** But we track the other locking levels internally.
1935*/
drh308c2a52010-05-14 11:30:18 +00001936static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001937 unixFile *pFile = (unixFile*)id;
1938 int fd;
1939 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001940 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001941
drh7708e972008-11-29 00:56:52 +00001942
1943 /* If we have any lock, then the lock file already exists. All we have
1944 ** to do is adjust our internal record of the lock level.
1945 */
drh308c2a52010-05-14 11:30:18 +00001946 if( pFile->eFileLock > NO_LOCK ){
1947 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001948 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001949#ifdef HAVE_UTIME
1950 utime(zLockFile, NULL);
1951#else
drh734c9862008-11-28 15:37:20 +00001952 utimes(zLockFile, NULL);
1953#endif
drh7708e972008-11-29 00:56:52 +00001954 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001955 }
1956
1957 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001958 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001959 if( fd<0 ){
1960 /* failed to open/create the file, someone else may have stolen the lock */
1961 int tErrno = errno;
1962 if( EEXIST == tErrno ){
1963 rc = SQLITE_BUSY;
1964 } else {
1965 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1966 if( IS_LOCK_ERROR(rc) ){
1967 pFile->lastErrno = tErrno;
1968 }
1969 }
drh7708e972008-11-29 00:56:52 +00001970 return rc;
drh734c9862008-11-28 15:37:20 +00001971 }
drh0e9365c2011-03-02 02:08:13 +00001972 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001973
1974 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001975 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001976 return rc;
1977}
1978
drh7708e972008-11-29 00:56:52 +00001979/*
drh308c2a52010-05-14 11:30:18 +00001980** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001981** must be either NO_LOCK or SHARED_LOCK.
1982**
1983** If the locking level of the file descriptor is already at or below
1984** the requested locking level, this routine is a no-op.
1985**
1986** When the locking level reaches NO_LOCK, delete the lock file.
1987*/
drh308c2a52010-05-14 11:30:18 +00001988static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001989 unixFile *pFile = (unixFile*)id;
1990 char *zLockFile = (char *)pFile->lockingContext;
1991
1992 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001993 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1994 pFile->eFileLock, getpid()));
1995 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001996
1997 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001998 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001999 return SQLITE_OK;
2000 }
drh7708e972008-11-29 00:56:52 +00002001
2002 /* To downgrade to shared, simply update our internal notion of the
2003 ** lock state. No need to mess with the file on disk.
2004 */
drh308c2a52010-05-14 11:30:18 +00002005 if( eFileLock==SHARED_LOCK ){
2006 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002007 return SQLITE_OK;
2008 }
2009
drh7708e972008-11-29 00:56:52 +00002010 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002011 assert( eFileLock==NO_LOCK );
drh036ac7f2011-08-08 23:18:05 +00002012 if( osUnlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002013 int rc = 0;
2014 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002015 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002016 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002017 }
2018 if( IS_LOCK_ERROR(rc) ){
2019 pFile->lastErrno = tErrno;
2020 }
2021 return rc;
2022 }
drh308c2a52010-05-14 11:30:18 +00002023 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002024 return SQLITE_OK;
2025}
2026
2027/*
drh9b35ea62008-11-29 02:20:26 +00002028** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002029*/
2030static int dotlockClose(sqlite3_file *id) {
2031 int rc;
2032 if( id ){
2033 unixFile *pFile = (unixFile*)id;
2034 dotlockUnlock(id, NO_LOCK);
2035 sqlite3_free(pFile->lockingContext);
2036 }
drh734c9862008-11-28 15:37:20 +00002037 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002038 return rc;
2039}
2040/****************** End of the dot-file lock implementation *******************
2041******************************************************************************/
2042
2043/******************************************************************************
2044************************** Begin flock Locking ********************************
2045**
2046** Use the flock() system call to do file locking.
2047**
drh6b9d6dd2008-12-03 19:34:47 +00002048** flock() locking is like dot-file locking in that the various
2049** fine-grain locking levels supported by SQLite are collapsed into
2050** a single exclusive lock. In other words, SHARED, RESERVED, and
2051** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2052** still works when you do this, but concurrency is reduced since
2053** only a single process can be reading the database at a time.
2054**
drh734c9862008-11-28 15:37:20 +00002055** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2056** compiling for VXWORKS.
2057*/
2058#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002059
drh6b9d6dd2008-12-03 19:34:47 +00002060/*
drhff812312011-02-23 13:33:46 +00002061** Retry flock() calls that fail with EINTR
2062*/
2063#ifdef EINTR
2064static int robust_flock(int fd, int op){
2065 int rc;
2066 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2067 return rc;
2068}
2069#else
drh5c819272011-02-23 14:00:12 +00002070# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002071#endif
2072
2073
2074/*
drh6b9d6dd2008-12-03 19:34:47 +00002075** This routine checks if there is a RESERVED lock held on the specified
2076** file by this or any other process. If such a lock is held, set *pResOut
2077** to a non-zero value otherwise *pResOut is set to zero. The return value
2078** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2079*/
drh734c9862008-11-28 15:37:20 +00002080static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2081 int rc = SQLITE_OK;
2082 int reserved = 0;
2083 unixFile *pFile = (unixFile*)id;
2084
2085 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2086
2087 assert( pFile );
2088
2089 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002090 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002091 reserved = 1;
2092 }
2093
2094 /* Otherwise see if some other process holds it. */
2095 if( !reserved ){
2096 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002097 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002098 if( !lrc ){
2099 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002100 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002101 if ( lrc ) {
2102 int tErrno = errno;
2103 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002104 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002105 if( IS_LOCK_ERROR(lrc) ){
2106 pFile->lastErrno = tErrno;
2107 rc = lrc;
2108 }
2109 }
2110 } else {
2111 int tErrno = errno;
2112 reserved = 1;
2113 /* someone else might have it reserved */
2114 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2115 if( IS_LOCK_ERROR(lrc) ){
2116 pFile->lastErrno = tErrno;
2117 rc = lrc;
2118 }
2119 }
2120 }
drh308c2a52010-05-14 11:30:18 +00002121 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002122
2123#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2124 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2125 rc = SQLITE_OK;
2126 reserved=1;
2127 }
2128#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2129 *pResOut = reserved;
2130 return rc;
2131}
2132
drh6b9d6dd2008-12-03 19:34:47 +00002133/*
drh308c2a52010-05-14 11:30:18 +00002134** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002135** of the following:
2136**
2137** (1) SHARED_LOCK
2138** (2) RESERVED_LOCK
2139** (3) PENDING_LOCK
2140** (4) EXCLUSIVE_LOCK
2141**
2142** Sometimes when requesting one lock state, additional lock states
2143** are inserted in between. The locking might fail on one of the later
2144** transitions leaving the lock state different from what it started but
2145** still short of its goal. The following chart shows the allowed
2146** transitions and the inserted intermediate states:
2147**
2148** UNLOCKED -> SHARED
2149** SHARED -> RESERVED
2150** SHARED -> (PENDING) -> EXCLUSIVE
2151** RESERVED -> (PENDING) -> EXCLUSIVE
2152** PENDING -> EXCLUSIVE
2153**
2154** flock() only really support EXCLUSIVE locks. We track intermediate
2155** lock states in the sqlite3_file structure, but all locks SHARED or
2156** above are really EXCLUSIVE locks and exclude all other processes from
2157** access the file.
2158**
2159** This routine will only increase a lock. Use the sqlite3OsUnlock()
2160** routine to lower a locking level.
2161*/
drh308c2a52010-05-14 11:30:18 +00002162static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002163 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002164 unixFile *pFile = (unixFile*)id;
2165
2166 assert( pFile );
2167
2168 /* if we already have a lock, it is exclusive.
2169 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002170 if (pFile->eFileLock > NO_LOCK) {
2171 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002172 return SQLITE_OK;
2173 }
2174
2175 /* grab an exclusive lock */
2176
drhff812312011-02-23 13:33:46 +00002177 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002178 int tErrno = errno;
2179 /* didn't get, must be busy */
2180 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2181 if( IS_LOCK_ERROR(rc) ){
2182 pFile->lastErrno = tErrno;
2183 }
2184 } else {
2185 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002186 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002187 }
drh308c2a52010-05-14 11:30:18 +00002188 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2189 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002190#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2191 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2192 rc = SQLITE_BUSY;
2193 }
2194#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2195 return rc;
2196}
2197
drh6b9d6dd2008-12-03 19:34:47 +00002198
2199/*
drh308c2a52010-05-14 11:30:18 +00002200** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002201** must be either NO_LOCK or SHARED_LOCK.
2202**
2203** If the locking level of the file descriptor is already at or below
2204** the requested locking level, this routine is a no-op.
2205*/
drh308c2a52010-05-14 11:30:18 +00002206static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002207 unixFile *pFile = (unixFile*)id;
2208
2209 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002210 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2211 pFile->eFileLock, getpid()));
2212 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002213
2214 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002215 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002216 return SQLITE_OK;
2217 }
2218
2219 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002220 if (eFileLock==SHARED_LOCK) {
2221 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
2225 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002226 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002227#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002228 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002229#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002230 return SQLITE_IOERR_UNLOCK;
2231 }else{
drh308c2a52010-05-14 11:30:18 +00002232 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002233 return SQLITE_OK;
2234 }
2235}
2236
2237/*
2238** Close a file.
2239*/
2240static int flockClose(sqlite3_file *id) {
2241 if( id ){
2242 flockUnlock(id, NO_LOCK);
2243 }
2244 return closeUnixFile(id);
2245}
2246
2247#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2248
2249/******************* End of the flock lock implementation *********************
2250******************************************************************************/
2251
2252/******************************************************************************
2253************************ Begin Named Semaphore Locking ************************
2254**
2255** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002256**
2257** Semaphore locking is like dot-lock and flock in that it really only
2258** supports EXCLUSIVE locking. Only a single process can read or write
2259** the database file at a time. This reduces potential concurrency, but
2260** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002261*/
2262#if OS_VXWORKS
2263
drh6b9d6dd2008-12-03 19:34:47 +00002264/*
2265** This routine checks if there is a RESERVED lock held on the specified
2266** file by this or any other process. If such a lock is held, set *pResOut
2267** to a non-zero value otherwise *pResOut is set to zero. The return value
2268** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2269*/
drh734c9862008-11-28 15:37:20 +00002270static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2271 int rc = SQLITE_OK;
2272 int reserved = 0;
2273 unixFile *pFile = (unixFile*)id;
2274
2275 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2276
2277 assert( pFile );
2278
2279 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002280 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002281 reserved = 1;
2282 }
2283
2284 /* Otherwise see if some other process holds it. */
2285 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002286 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002287 struct stat statBuf;
2288
2289 if( sem_trywait(pSem)==-1 ){
2290 int tErrno = errno;
2291 if( EAGAIN != tErrno ){
2292 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2293 pFile->lastErrno = tErrno;
2294 } else {
2295 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002296 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002297 }
2298 }else{
2299 /* we could have it if we want it */
2300 sem_post(pSem);
2301 }
2302 }
drh308c2a52010-05-14 11:30:18 +00002303 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002304
2305 *pResOut = reserved;
2306 return rc;
2307}
2308
drh6b9d6dd2008-12-03 19:34:47 +00002309/*
drh308c2a52010-05-14 11:30:18 +00002310** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002311** of the following:
2312**
2313** (1) SHARED_LOCK
2314** (2) RESERVED_LOCK
2315** (3) PENDING_LOCK
2316** (4) EXCLUSIVE_LOCK
2317**
2318** Sometimes when requesting one lock state, additional lock states
2319** are inserted in between. The locking might fail on one of the later
2320** transitions leaving the lock state different from what it started but
2321** still short of its goal. The following chart shows the allowed
2322** transitions and the inserted intermediate states:
2323**
2324** UNLOCKED -> SHARED
2325** SHARED -> RESERVED
2326** SHARED -> (PENDING) -> EXCLUSIVE
2327** RESERVED -> (PENDING) -> EXCLUSIVE
2328** PENDING -> EXCLUSIVE
2329**
2330** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2331** lock states in the sqlite3_file structure, but all locks SHARED or
2332** above are really EXCLUSIVE locks and exclude all other processes from
2333** access the file.
2334**
2335** This routine will only increase a lock. Use the sqlite3OsUnlock()
2336** routine to lower a locking level.
2337*/
drh308c2a52010-05-14 11:30:18 +00002338static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002339 unixFile *pFile = (unixFile*)id;
2340 int fd;
drh8af6c222010-05-14 12:43:01 +00002341 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002342 int rc = SQLITE_OK;
2343
2344 /* if we already have a lock, it is exclusive.
2345 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002346 if (pFile->eFileLock > NO_LOCK) {
2347 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002348 rc = SQLITE_OK;
2349 goto sem_end_lock;
2350 }
2351
2352 /* lock semaphore now but bail out when already locked. */
2353 if( sem_trywait(pSem)==-1 ){
2354 rc = SQLITE_BUSY;
2355 goto sem_end_lock;
2356 }
2357
2358 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002359 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002360
2361 sem_end_lock:
2362 return rc;
2363}
2364
drh6b9d6dd2008-12-03 19:34:47 +00002365/*
drh308c2a52010-05-14 11:30:18 +00002366** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002367** must be either NO_LOCK or SHARED_LOCK.
2368**
2369** If the locking level of the file descriptor is already at or below
2370** the requested locking level, this routine is a no-op.
2371*/
drh308c2a52010-05-14 11:30:18 +00002372static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002373 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002374 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002375
2376 assert( pFile );
2377 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002378 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2379 pFile->eFileLock, getpid()));
2380 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002381
2382 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002383 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002384 return SQLITE_OK;
2385 }
2386
2387 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002388 if (eFileLock==SHARED_LOCK) {
2389 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002390 return SQLITE_OK;
2391 }
2392
2393 /* no, really unlock. */
2394 if ( sem_post(pSem)==-1 ) {
2395 int rc, tErrno = errno;
2396 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2397 if( IS_LOCK_ERROR(rc) ){
2398 pFile->lastErrno = tErrno;
2399 }
2400 return rc;
2401 }
drh308c2a52010-05-14 11:30:18 +00002402 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404}
2405
2406/*
2407 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002408 */
drh734c9862008-11-28 15:37:20 +00002409static int semClose(sqlite3_file *id) {
2410 if( id ){
2411 unixFile *pFile = (unixFile*)id;
2412 semUnlock(id, NO_LOCK);
2413 assert( pFile );
2414 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002415 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002416 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002417 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002418 }
2419 return SQLITE_OK;
2420}
2421
2422#endif /* OS_VXWORKS */
2423/*
2424** Named semaphore locking is only available on VxWorks.
2425**
2426*************** End of the named semaphore lock implementation ****************
2427******************************************************************************/
2428
2429
2430/******************************************************************************
2431*************************** Begin AFP Locking *********************************
2432**
2433** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2434** on Apple Macintosh computers - both OS9 and OSX.
2435**
2436** Third-party implementations of AFP are available. But this code here
2437** only works on OSX.
2438*/
2439
drhd2cb50b2009-01-09 21:41:17 +00002440#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002441/*
2442** The afpLockingContext structure contains all afp lock specific state
2443*/
drhbfe66312006-10-03 17:40:40 +00002444typedef struct afpLockingContext afpLockingContext;
2445struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002446 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002447 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002448};
2449
2450struct ByteRangeLockPB2
2451{
2452 unsigned long long offset; /* offset to first byte to lock */
2453 unsigned long long length; /* nbr of bytes to lock */
2454 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2455 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2456 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2457 int fd; /* file desc to assoc this lock with */
2458};
2459
drhfd131da2007-08-07 17:13:03 +00002460#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002461
drh6b9d6dd2008-12-03 19:34:47 +00002462/*
2463** This is a utility for setting or clearing a bit-range lock on an
2464** AFP filesystem.
2465**
2466** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2467*/
2468static int afpSetLock(
2469 const char *path, /* Name of the file to be locked or unlocked */
2470 unixFile *pFile, /* Open file descriptor on path */
2471 unsigned long long offset, /* First byte to be locked */
2472 unsigned long long length, /* Number of bytes to lock */
2473 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002474){
drh6b9d6dd2008-12-03 19:34:47 +00002475 struct ByteRangeLockPB2 pb;
2476 int err;
drhbfe66312006-10-03 17:40:40 +00002477
2478 pb.unLockFlag = setLockFlag ? 0 : 1;
2479 pb.startEndFlag = 0;
2480 pb.offset = offset;
2481 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002482 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002483
drh308c2a52010-05-14 11:30:18 +00002484 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002485 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002486 offset, length));
drhbfe66312006-10-03 17:40:40 +00002487 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2488 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002489 int rc;
2490 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002491 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2492 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002493#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2494 rc = SQLITE_BUSY;
2495#else
drh734c9862008-11-28 15:37:20 +00002496 rc = sqliteErrorFromPosixError(tErrno,
2497 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002498#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002499 if( IS_LOCK_ERROR(rc) ){
2500 pFile->lastErrno = tErrno;
2501 }
2502 return rc;
drhbfe66312006-10-03 17:40:40 +00002503 } else {
aswift5b1a2562008-08-22 00:22:35 +00002504 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002505 }
2506}
2507
drh6b9d6dd2008-12-03 19:34:47 +00002508/*
2509** This routine checks if there is a RESERVED lock held on the specified
2510** file by this or any other process. If such a lock is held, set *pResOut
2511** to a non-zero value otherwise *pResOut is set to zero. The return value
2512** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2513*/
danielk1977e339d652008-06-28 11:23:00 +00002514static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002515 int rc = SQLITE_OK;
2516 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002517 unixFile *pFile = (unixFile*)id;
2518
aswift5b1a2562008-08-22 00:22:35 +00002519 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2520
2521 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002522 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002523 if( context->reserved ){
2524 *pResOut = 1;
2525 return SQLITE_OK;
2526 }
drh8af6c222010-05-14 12:43:01 +00002527 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002528
2529 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002530 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002531 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002532 }
2533
2534 /* Otherwise see if some other process holds it.
2535 */
aswift5b1a2562008-08-22 00:22:35 +00002536 if( !reserved ){
2537 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002538 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002539 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002540 /* if we succeeded in taking the reserved lock, unlock it to restore
2541 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002542 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002543 } else {
2544 /* if we failed to get the lock then someone else must have it */
2545 reserved = 1;
2546 }
2547 if( IS_LOCK_ERROR(lrc) ){
2548 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002549 }
2550 }
drhbfe66312006-10-03 17:40:40 +00002551
drh7ed97b92010-01-20 13:07:21 +00002552 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002553 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002554
2555 *pResOut = reserved;
2556 return rc;
drhbfe66312006-10-03 17:40:40 +00002557}
2558
drh6b9d6dd2008-12-03 19:34:47 +00002559/*
drh308c2a52010-05-14 11:30:18 +00002560** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002561** of the following:
2562**
2563** (1) SHARED_LOCK
2564** (2) RESERVED_LOCK
2565** (3) PENDING_LOCK
2566** (4) EXCLUSIVE_LOCK
2567**
2568** Sometimes when requesting one lock state, additional lock states
2569** are inserted in between. The locking might fail on one of the later
2570** transitions leaving the lock state different from what it started but
2571** still short of its goal. The following chart shows the allowed
2572** transitions and the inserted intermediate states:
2573**
2574** UNLOCKED -> SHARED
2575** SHARED -> RESERVED
2576** SHARED -> (PENDING) -> EXCLUSIVE
2577** RESERVED -> (PENDING) -> EXCLUSIVE
2578** PENDING -> EXCLUSIVE
2579**
2580** This routine will only increase a lock. Use the sqlite3OsUnlock()
2581** routine to lower a locking level.
2582*/
drh308c2a52010-05-14 11:30:18 +00002583static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002584 int rc = SQLITE_OK;
2585 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002586 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002587 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002588
2589 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002590 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2591 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002592 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002593
drhbfe66312006-10-03 17:40:40 +00002594 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002595 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002596 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002597 */
drh308c2a52010-05-14 11:30:18 +00002598 if( pFile->eFileLock>=eFileLock ){
2599 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2600 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002601 return SQLITE_OK;
2602 }
2603
2604 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002605 ** (1) We never move from unlocked to anything higher than shared lock.
2606 ** (2) SQLite never explicitly requests a pendig lock.
2607 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002608 */
drh308c2a52010-05-14 11:30:18 +00002609 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2610 assert( eFileLock!=PENDING_LOCK );
2611 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002612
drh8af6c222010-05-14 12:43:01 +00002613 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002614 */
drh6c7d5c52008-11-21 20:32:33 +00002615 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002616 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002617
2618 /* If some thread using this PID has a lock via a different unixFile*
2619 ** handle that precludes the requested lock, return BUSY.
2620 */
drh8af6c222010-05-14 12:43:01 +00002621 if( (pFile->eFileLock!=pInode->eFileLock &&
2622 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002623 ){
2624 rc = SQLITE_BUSY;
2625 goto afp_end_lock;
2626 }
2627
2628 /* If a SHARED lock is requested, and some thread using this PID already
2629 ** has a SHARED or RESERVED lock, then increment reference counts and
2630 ** return SQLITE_OK.
2631 */
drh308c2a52010-05-14 11:30:18 +00002632 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002633 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002634 assert( eFileLock==SHARED_LOCK );
2635 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002636 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002637 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002638 pInode->nShared++;
2639 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002640 goto afp_end_lock;
2641 }
drhbfe66312006-10-03 17:40:40 +00002642
2643 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002644 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2645 ** be released.
2646 */
drh308c2a52010-05-14 11:30:18 +00002647 if( eFileLock==SHARED_LOCK
2648 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002649 ){
2650 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002651 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002652 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002653 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002654 goto afp_end_lock;
2655 }
2656 }
2657
2658 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002659 ** operating system calls for the specified lock.
2660 */
drh308c2a52010-05-14 11:30:18 +00002661 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002662 int lrc1, lrc2, lrc1Errno;
2663 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002664
drh8af6c222010-05-14 12:43:01 +00002665 assert( pInode->nShared==0 );
2666 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002667
2668 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002669 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002670 /* note that the quality of the randomness doesn't matter that much */
2671 lk = random();
drh8af6c222010-05-14 12:43:01 +00002672 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002673 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002674 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002675 if( IS_LOCK_ERROR(lrc1) ){
2676 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002677 }
aswift5b1a2562008-08-22 00:22:35 +00002678 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002679 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002680
aswift5b1a2562008-08-22 00:22:35 +00002681 if( IS_LOCK_ERROR(lrc1) ) {
2682 pFile->lastErrno = lrc1Errno;
2683 rc = lrc1;
2684 goto afp_end_lock;
2685 } else if( IS_LOCK_ERROR(lrc2) ){
2686 rc = lrc2;
2687 goto afp_end_lock;
2688 } else if( lrc1 != SQLITE_OK ) {
2689 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002690 } else {
drh308c2a52010-05-14 11:30:18 +00002691 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002692 pInode->nLock++;
2693 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002694 }
drh8af6c222010-05-14 12:43:01 +00002695 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002696 /* We are trying for an exclusive lock but another thread in this
2697 ** same process is still holding a shared lock. */
2698 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002699 }else{
2700 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2701 ** assumed that there is a SHARED or greater lock on the file
2702 ** already.
2703 */
2704 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002705 assert( 0!=pFile->eFileLock );
2706 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002707 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002708 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002709 if( !failed ){
2710 context->reserved = 1;
2711 }
drhbfe66312006-10-03 17:40:40 +00002712 }
drh308c2a52010-05-14 11:30:18 +00002713 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002714 /* Acquire an EXCLUSIVE lock */
2715
2716 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002717 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002718 */
drh6b9d6dd2008-12-03 19:34:47 +00002719 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002720 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002721 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002722 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002723 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002724 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002725 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002726 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002727 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2728 ** a critical I/O error
2729 */
2730 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2731 SQLITE_IOERR_LOCK;
2732 goto afp_end_lock;
2733 }
2734 }else{
aswift5b1a2562008-08-22 00:22:35 +00002735 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002736 }
2737 }
aswift5b1a2562008-08-22 00:22:35 +00002738 if( failed ){
2739 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002740 }
2741 }
2742
2743 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002744 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002745 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002746 }else if( eFileLock==EXCLUSIVE_LOCK ){
2747 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002748 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002749 }
2750
2751afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002752 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002753 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2754 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002755 return rc;
2756}
2757
2758/*
drh308c2a52010-05-14 11:30:18 +00002759** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002760** must be either NO_LOCK or SHARED_LOCK.
2761**
2762** If the locking level of the file descriptor is already at or below
2763** the requested locking level, this routine is a no-op.
2764*/
drh308c2a52010-05-14 11:30:18 +00002765static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002766 int rc = SQLITE_OK;
2767 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002768 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002769 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2770 int skipShared = 0;
2771#ifdef SQLITE_TEST
2772 int h = pFile->h;
2773#endif
drhbfe66312006-10-03 17:40:40 +00002774
2775 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002776 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002777 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002778 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002779
drh308c2a52010-05-14 11:30:18 +00002780 assert( eFileLock<=SHARED_LOCK );
2781 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002782 return SQLITE_OK;
2783 }
drh6c7d5c52008-11-21 20:32:33 +00002784 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002785 pInode = pFile->pInode;
2786 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002787 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002788 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002789 SimulateIOErrorBenign(1);
2790 SimulateIOError( h=(-1) )
2791 SimulateIOErrorBenign(0);
2792
2793#ifndef NDEBUG
2794 /* When reducing a lock such that other processes can start
2795 ** reading the database file again, make sure that the
2796 ** transaction counter was updated if any part of the database
2797 ** file changed. If the transaction counter is not updated,
2798 ** other connections to the same file might not realize that
2799 ** the file has changed and hence might not know to flush their
2800 ** cache. The use of a stale cache can lead to database corruption.
2801 */
2802 assert( pFile->inNormalWrite==0
2803 || pFile->dbUpdate==0
2804 || pFile->transCntrChng==1 );
2805 pFile->inNormalWrite = 0;
2806#endif
aswiftaebf4132008-11-21 00:10:35 +00002807
drh308c2a52010-05-14 11:30:18 +00002808 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002809 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002810 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002811 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002812 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002813 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2814 } else {
2815 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002816 }
2817 }
drh308c2a52010-05-14 11:30:18 +00002818 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002819 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002820 }
drh308c2a52010-05-14 11:30:18 +00002821 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002822 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2823 if( !rc ){
2824 context->reserved = 0;
2825 }
aswiftaebf4132008-11-21 00:10:35 +00002826 }
drh8af6c222010-05-14 12:43:01 +00002827 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2828 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002829 }
aswiftaebf4132008-11-21 00:10:35 +00002830 }
drh308c2a52010-05-14 11:30:18 +00002831 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002832
drh7ed97b92010-01-20 13:07:21 +00002833 /* Decrement the shared lock counter. Release the lock using an
2834 ** OS call only when all threads in this same process have released
2835 ** the lock.
2836 */
drh8af6c222010-05-14 12:43:01 +00002837 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2838 pInode->nShared--;
2839 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002840 SimulateIOErrorBenign(1);
2841 SimulateIOError( h=(-1) )
2842 SimulateIOErrorBenign(0);
2843 if( !skipShared ){
2844 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2845 }
2846 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002847 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002848 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002849 }
2850 }
2851 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002852 pInode->nLock--;
2853 assert( pInode->nLock>=0 );
2854 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002855 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002856 }
2857 }
drhbfe66312006-10-03 17:40:40 +00002858 }
drh7ed97b92010-01-20 13:07:21 +00002859
drh6c7d5c52008-11-21 20:32:33 +00002860 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002861 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002862 return rc;
2863}
2864
2865/*
drh339eb0b2008-03-07 15:34:11 +00002866** Close a file & cleanup AFP specific locking context
2867*/
danielk1977e339d652008-06-28 11:23:00 +00002868static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002869 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002870 if( id ){
2871 unixFile *pFile = (unixFile*)id;
2872 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002873 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002874 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002875 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002876 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002877 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002878 ** the last lock is cleared.
2879 */
dan08da86a2009-08-21 17:18:03 +00002880 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002881 }
danb0ac3e32010-06-16 10:55:42 +00002882 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002883 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002884 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002885 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002886 }
drh7ed97b92010-01-20 13:07:21 +00002887 return rc;
drhbfe66312006-10-03 17:40:40 +00002888}
2889
drhd2cb50b2009-01-09 21:41:17 +00002890#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002891/*
2892** The code above is the AFP lock implementation. The code is specific
2893** to MacOSX and does not work on other unix platforms. No alternative
2894** is available. If you don't compile for a mac, then the "unix-afp"
2895** VFS is not available.
2896**
2897********************* End of the AFP lock implementation **********************
2898******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002899
drh7ed97b92010-01-20 13:07:21 +00002900/******************************************************************************
2901*************************** Begin NFS Locking ********************************/
2902
2903#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2904/*
drh308c2a52010-05-14 11:30:18 +00002905 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002906 ** must be either NO_LOCK or SHARED_LOCK.
2907 **
2908 ** If the locking level of the file descriptor is already at or below
2909 ** the requested locking level, this routine is a no-op.
2910 */
drh308c2a52010-05-14 11:30:18 +00002911static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002912 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002913}
2914
2915#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2916/*
2917** The code above is the NFS lock implementation. The code is specific
2918** to MacOSX and does not work on other unix platforms. No alternative
2919** is available.
2920**
2921********************* End of the NFS lock implementation **********************
2922******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002923
2924/******************************************************************************
2925**************** Non-locking sqlite3_file methods *****************************
2926**
2927** The next division contains implementations for all methods of the
2928** sqlite3_file object other than the locking methods. The locking
2929** methods were defined in divisions above (one locking method per
2930** division). Those methods that are common to all locking modes
2931** are gather together into this division.
2932*/
drhbfe66312006-10-03 17:40:40 +00002933
2934/*
drh734c9862008-11-28 15:37:20 +00002935** Seek to the offset passed as the second argument, then read cnt
2936** bytes into pBuf. Return the number of bytes actually read.
2937**
2938** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2939** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2940** one system to another. Since SQLite does not define USE_PREAD
2941** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2942** See tickets #2741 and #2681.
2943**
2944** To avoid stomping the errno value on a failed read the lastErrno value
2945** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002946*/
drh734c9862008-11-28 15:37:20 +00002947static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2948 int got;
drh7ed97b92010-01-20 13:07:21 +00002949#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002950 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002951#endif
drh734c9862008-11-28 15:37:20 +00002952 TIMER_START;
2953#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002954 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002955 SimulateIOError( got = -1 );
2956#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002957 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002958 SimulateIOError( got = -1 );
2959#else
2960 newOffset = lseek(id->h, offset, SEEK_SET);
2961 SimulateIOError( newOffset-- );
2962 if( newOffset!=offset ){
2963 if( newOffset == -1 ){
2964 ((unixFile*)id)->lastErrno = errno;
2965 }else{
2966 ((unixFile*)id)->lastErrno = 0;
2967 }
2968 return -1;
2969 }
drhe562be52011-03-02 18:01:10 +00002970 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002971#endif
2972 TIMER_END;
2973 if( got<0 ){
2974 ((unixFile*)id)->lastErrno = errno;
2975 }
drh308c2a52010-05-14 11:30:18 +00002976 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002977 return got;
drhbfe66312006-10-03 17:40:40 +00002978}
2979
2980/*
drh734c9862008-11-28 15:37:20 +00002981** Read data from a file into a buffer. Return SQLITE_OK if all
2982** bytes were read successfully and SQLITE_IOERR if anything goes
2983** wrong.
drh339eb0b2008-03-07 15:34:11 +00002984*/
drh734c9862008-11-28 15:37:20 +00002985static int unixRead(
2986 sqlite3_file *id,
2987 void *pBuf,
2988 int amt,
2989 sqlite3_int64 offset
2990){
dan08da86a2009-08-21 17:18:03 +00002991 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002992 int got;
2993 assert( id );
drh08c6d442009-02-09 17:34:07 +00002994
dan08da86a2009-08-21 17:18:03 +00002995 /* If this is a database file (not a journal, master-journal or temp
2996 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002997#if 0
dane946c392009-08-22 11:39:46 +00002998 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002999 || offset>=PENDING_BYTE+512
3000 || offset+amt<=PENDING_BYTE
3001 );
dan7c246102010-04-12 19:00:29 +00003002#endif
drh08c6d442009-02-09 17:34:07 +00003003
dan08da86a2009-08-21 17:18:03 +00003004 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003005 if( got==amt ){
3006 return SQLITE_OK;
3007 }else if( got<0 ){
3008 /* lastErrno set by seekAndRead */
3009 return SQLITE_IOERR_READ;
3010 }else{
dan08da86a2009-08-21 17:18:03 +00003011 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003012 /* Unread parts of the buffer must be zero-filled */
3013 memset(&((char*)pBuf)[got], 0, amt-got);
3014 return SQLITE_IOERR_SHORT_READ;
3015 }
3016}
3017
3018/*
3019** Seek to the offset in id->offset then read cnt bytes into pBuf.
3020** Return the number of bytes actually read. Update the offset.
3021**
3022** To avoid stomping the errno value on a failed write the lastErrno value
3023** is set before returning.
3024*/
3025static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3026 int got;
drh7ed97b92010-01-20 13:07:21 +00003027#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003028 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003029#endif
drh734c9862008-11-28 15:37:20 +00003030 TIMER_START;
3031#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003032 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003033#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003034 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003035#else
3036 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003037 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003038 if( newOffset!=offset ){
3039 if( newOffset == -1 ){
3040 ((unixFile*)id)->lastErrno = errno;
3041 }else{
3042 ((unixFile*)id)->lastErrno = 0;
3043 }
3044 return -1;
3045 }
drhe562be52011-03-02 18:01:10 +00003046 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003047#endif
3048 TIMER_END;
3049 if( got<0 ){
3050 ((unixFile*)id)->lastErrno = errno;
3051 }
3052
drh308c2a52010-05-14 11:30:18 +00003053 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003054 return got;
3055}
3056
3057
3058/*
3059** Write data from a buffer into a file. Return SQLITE_OK on success
3060** or some other error code on failure.
3061*/
3062static int unixWrite(
3063 sqlite3_file *id,
3064 const void *pBuf,
3065 int amt,
3066 sqlite3_int64 offset
3067){
dan08da86a2009-08-21 17:18:03 +00003068 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003069 int wrote = 0;
3070 assert( id );
3071 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003072
dan08da86a2009-08-21 17:18:03 +00003073 /* If this is a database file (not a journal, master-journal or temp
3074 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003075#if 0
dane946c392009-08-22 11:39:46 +00003076 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003077 || offset>=PENDING_BYTE+512
3078 || offset+amt<=PENDING_BYTE
3079 );
dan7c246102010-04-12 19:00:29 +00003080#endif
drh08c6d442009-02-09 17:34:07 +00003081
drh8f941bc2009-01-14 23:03:40 +00003082#ifndef NDEBUG
3083 /* If we are doing a normal write to a database file (as opposed to
3084 ** doing a hot-journal rollback or a write to some file other than a
3085 ** normal database file) then record the fact that the database
3086 ** has changed. If the transaction counter is modified, record that
3087 ** fact too.
3088 */
dan08da86a2009-08-21 17:18:03 +00003089 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003090 pFile->dbUpdate = 1; /* The database has been modified */
3091 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003092 int rc;
drh8f941bc2009-01-14 23:03:40 +00003093 char oldCntr[4];
3094 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003095 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003096 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003097 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003098 pFile->transCntrChng = 1; /* The transaction counter has changed */
3099 }
3100 }
3101 }
3102#endif
3103
dan08da86a2009-08-21 17:18:03 +00003104 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003105 amt -= wrote;
3106 offset += wrote;
3107 pBuf = &((char*)pBuf)[wrote];
3108 }
3109 SimulateIOError(( wrote=(-1), amt=1 ));
3110 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003111
drh734c9862008-11-28 15:37:20 +00003112 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003113 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003114 /* lastErrno set by seekAndWrite */
3115 return SQLITE_IOERR_WRITE;
3116 }else{
dan08da86a2009-08-21 17:18:03 +00003117 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003118 return SQLITE_FULL;
3119 }
3120 }
dan6e09d692010-07-27 18:34:15 +00003121
drh734c9862008-11-28 15:37:20 +00003122 return SQLITE_OK;
3123}
3124
3125#ifdef SQLITE_TEST
3126/*
3127** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003128** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003129*/
3130int sqlite3_sync_count = 0;
3131int sqlite3_fullsync_count = 0;
3132#endif
3133
3134/*
drh89240432009-03-25 01:06:01 +00003135** We do not trust systems to provide a working fdatasync(). Some do.
3136** Others do no. To be safe, we will stick with the (slower) fsync().
3137** If you know that your system does support fdatasync() correctly,
3138** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003139*/
drh89240432009-03-25 01:06:01 +00003140#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003141# define fdatasync fsync
3142#endif
3143
3144/*
3145** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3146** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3147** only available on Mac OS X. But that could change.
3148*/
3149#ifdef F_FULLFSYNC
3150# define HAVE_FULLFSYNC 1
3151#else
3152# define HAVE_FULLFSYNC 0
3153#endif
3154
3155
3156/*
3157** The fsync() system call does not work as advertised on many
3158** unix systems. The following procedure is an attempt to make
3159** it work better.
3160**
3161** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3162** for testing when we want to run through the test suite quickly.
3163** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3164** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3165** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003166**
3167** SQLite sets the dataOnly flag if the size of the file is unchanged.
3168** The idea behind dataOnly is that it should only write the file content
3169** to disk, not the inode. We only set dataOnly if the file size is
3170** unchanged since the file size is part of the inode. However,
3171** Ted Ts'o tells us that fdatasync() will also write the inode if the
3172** file size has changed. The only real difference between fdatasync()
3173** and fsync(), Ted tells us, is that fdatasync() will not flush the
3174** inode if the mtime or owner or other inode attributes have changed.
3175** We only care about the file size, not the other file attributes, so
3176** as far as SQLite is concerned, an fdatasync() is always adequate.
3177** So, we always use fdatasync() if it is available, regardless of
3178** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003179*/
3180static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003181 int rc;
drh734c9862008-11-28 15:37:20 +00003182
3183 /* The following "ifdef/elif/else/" block has the same structure as
3184 ** the one below. It is replicated here solely to avoid cluttering
3185 ** up the real code with the UNUSED_PARAMETER() macros.
3186 */
3187#ifdef SQLITE_NO_SYNC
3188 UNUSED_PARAMETER(fd);
3189 UNUSED_PARAMETER(fullSync);
3190 UNUSED_PARAMETER(dataOnly);
3191#elif HAVE_FULLFSYNC
3192 UNUSED_PARAMETER(dataOnly);
3193#else
3194 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003195 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003196#endif
3197
3198 /* Record the number of times that we do a normal fsync() and
3199 ** FULLSYNC. This is used during testing to verify that this procedure
3200 ** gets called with the correct arguments.
3201 */
3202#ifdef SQLITE_TEST
3203 if( fullSync ) sqlite3_fullsync_count++;
3204 sqlite3_sync_count++;
3205#endif
3206
3207 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3208 ** no-op
3209 */
3210#ifdef SQLITE_NO_SYNC
3211 rc = SQLITE_OK;
3212#elif HAVE_FULLFSYNC
3213 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003214 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003215 }else{
3216 rc = 1;
3217 }
3218 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003219 ** It shouldn't be possible for fullfsync to fail on the local
3220 ** file system (on OSX), so failure indicates that FULLFSYNC
3221 ** isn't supported for this file system. So, attempt an fsync
3222 ** and (for now) ignore the overhead of a superfluous fcntl call.
3223 ** It'd be better to detect fullfsync support once and avoid
3224 ** the fcntl call every time sync is called.
3225 */
drh734c9862008-11-28 15:37:20 +00003226 if( rc ) rc = fsync(fd);
3227
drh7ed97b92010-01-20 13:07:21 +00003228#elif defined(__APPLE__)
3229 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3230 ** so currently we default to the macro that redefines fdatasync to fsync
3231 */
3232 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003233#else
drh0b647ff2009-03-21 14:41:04 +00003234 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003235#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003236 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003237 rc = fsync(fd);
3238 }
drh0b647ff2009-03-21 14:41:04 +00003239#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003240#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3241
3242 if( OS_VXWORKS && rc!= -1 ){
3243 rc = 0;
3244 }
chw97185482008-11-17 08:05:31 +00003245 return rc;
drhbfe66312006-10-03 17:40:40 +00003246}
3247
drh734c9862008-11-28 15:37:20 +00003248/*
drh0059eae2011-08-08 23:48:40 +00003249** Open a file descriptor to the directory containing file zFilename.
3250** If successful, *pFd is set to the opened file descriptor and
3251** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3252** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3253** value.
3254**
3255** If SQLITE_OK is returned, the caller is responsible for closing
3256** the file descriptor *pFd using close().
3257*/
3258static int openDirectory(const char *zFilename, int *pFd){
3259 int ii;
3260 int fd = -1;
3261 char zDirname[MAX_PATHNAME+1];
3262
3263 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3264 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3265 if( ii>0 ){
3266 zDirname[ii] = '\0';
3267 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3268 if( fd>=0 ){
3269#ifdef FD_CLOEXEC
3270 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3271#endif
3272 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3273 }
3274 }
3275 *pFd = fd;
3276 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3277}
3278
3279/*
drh734c9862008-11-28 15:37:20 +00003280** Make sure all writes to a particular file are committed to disk.
3281**
3282** If dataOnly==0 then both the file itself and its metadata (file
3283** size, access time, etc) are synced. If dataOnly!=0 then only the
3284** file data is synced.
3285**
3286** Under Unix, also make sure that the directory entry for the file
3287** has been created by fsync-ing the directory that contains the file.
3288** If we do not do this and we encounter a power failure, the directory
3289** entry for the journal might not exist after we reboot. The next
3290** SQLite to access the file will not know that the journal exists (because
3291** the directory entry for the journal was never created) and the transaction
3292** will not roll back - possibly leading to database corruption.
3293*/
3294static int unixSync(sqlite3_file *id, int flags){
3295 int rc;
3296 unixFile *pFile = (unixFile*)id;
3297
3298 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3299 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3300
3301 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3302 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3303 || (flags&0x0F)==SQLITE_SYNC_FULL
3304 );
3305
3306 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3307 ** line is to test that doing so does not cause any problems.
3308 */
3309 SimulateDiskfullError( return SQLITE_FULL );
3310
3311 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003312 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003313 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3314 SimulateIOError( rc=1 );
3315 if( rc ){
3316 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003317 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003318 }
drh0059eae2011-08-08 23:48:40 +00003319
3320 /* Also fsync the directory containing the file if the DIRSYNC flag
3321 ** is set. This is a one-time occurrance. Many systems (examples: AIX
3322 ** or any process running inside a chromium sandbox) are unable to fsync a
3323 ** directory, so ignore errors.
3324 */
3325 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3326 int dirfd;
3327 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003328 HAVE_FULLFSYNC, isFullsync));
drh0059eae2011-08-08 23:48:40 +00003329 openDirectory(pFile->zPath, &dirfd);
3330 if( dirfd>=0 ){
3331 full_fsync(dirfd, 0, 0);
3332 robust_close(pFile, dirfd, __LINE__);
drh734c9862008-11-28 15:37:20 +00003333 }
drh0059eae2011-08-08 23:48:40 +00003334 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003335 }
3336 return rc;
3337}
3338
3339/*
3340** Truncate an open file to a specified size
3341*/
3342static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003343 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003344 int rc;
dan6e09d692010-07-27 18:34:15 +00003345 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003346 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003347
3348 /* If the user has configured a chunk-size for this file, truncate the
3349 ** file so that it consists of an integer number of chunks (i.e. the
3350 ** actual file size after the operation may be larger than the requested
3351 ** size).
3352 */
3353 if( pFile->szChunk ){
3354 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3355 }
3356
drhff812312011-02-23 13:33:46 +00003357 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003358 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003359 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003360 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003361 }else{
drh3313b142009-11-06 04:13:18 +00003362#ifndef NDEBUG
3363 /* If we are doing a normal write to a database file (as opposed to
3364 ** doing a hot-journal rollback or a write to some file other than a
3365 ** normal database file) and we truncate the file to zero length,
3366 ** that effectively updates the change counter. This might happen
3367 ** when restoring a database using the backup API from a zero-length
3368 ** source.
3369 */
dan6e09d692010-07-27 18:34:15 +00003370 if( pFile->inNormalWrite && nByte==0 ){
3371 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003372 }
3373#endif
3374
drh734c9862008-11-28 15:37:20 +00003375 return SQLITE_OK;
3376 }
3377}
3378
3379/*
3380** Determine the current size of a file in bytes
3381*/
3382static int unixFileSize(sqlite3_file *id, i64 *pSize){
3383 int rc;
3384 struct stat buf;
3385 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003386 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003387 SimulateIOError( rc=1 );
3388 if( rc!=0 ){
3389 ((unixFile*)id)->lastErrno = errno;
3390 return SQLITE_IOERR_FSTAT;
3391 }
3392 *pSize = buf.st_size;
3393
drh8af6c222010-05-14 12:43:01 +00003394 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003395 ** writes a single byte into that file in order to work around a bug
3396 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3397 ** layers, we need to report this file size as zero even though it is
3398 ** really 1. Ticket #3260.
3399 */
3400 if( *pSize==1 ) *pSize = 0;
3401
3402
3403 return SQLITE_OK;
3404}
3405
drhd2cb50b2009-01-09 21:41:17 +00003406#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003407/*
3408** Handler for proxy-locking file-control verbs. Defined below in the
3409** proxying locking division.
3410*/
3411static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003412#endif
drh715ff302008-12-03 22:32:44 +00003413
dan502019c2010-07-28 14:26:17 +00003414/*
3415** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3416** file-control operation.
3417**
3418** If the user has configured a chunk-size for this file, it could be
3419** that the file needs to be extended at this point. Otherwise, the
3420** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3421*/
3422static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003423 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003424 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003425 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003426 struct stat buf; /* Used to hold return values of fstat() */
3427
drh99ab3b12011-03-02 15:09:07 +00003428 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003429
drh7d2dc712011-07-25 23:25:47 +00003430 szChunk = pFile->szChunk;
3431 if( szChunk==0 ){
3432 nSize = nByte;
3433 }else{
3434 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3435 }
dan502019c2010-07-28 14:26:17 +00003436 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003437
dan502019c2010-07-28 14:26:17 +00003438#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003439 /* The code below is handling the return value of osFallocate()
3440 ** correctly. posix_fallocate() is defined to "returns zero on success,
3441 ** or an error number on failure". See the manpage for details. */
3442 int err;
drhff812312011-02-23 13:33:46 +00003443 do{
dan661d71a2011-03-30 19:08:03 +00003444 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3445 }while( err==EINTR );
3446 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003447#else
3448 /* If the OS does not have posix_fallocate(), fake it. First use
3449 ** ftruncate() to set the file size, then write a single byte to
3450 ** the last byte in each block within the extended region. This
3451 ** is the same technique used by glibc to implement posix_fallocate()
3452 ** on systems that do not have a real fallocate() system call.
3453 */
3454 int nBlk = buf.st_blksize; /* File-system block size */
3455 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003456
drhff812312011-02-23 13:33:46 +00003457 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003458 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003459 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003460 }
3461 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003462 while( iWrite<nSize ){
3463 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3464 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003465 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003466 }
dan502019c2010-07-28 14:26:17 +00003467#endif
3468 }
3469 }
3470
3471 return SQLITE_OK;
3472}
danielk1977ad94b582007-08-20 06:44:22 +00003473
danielk1977e3026632004-06-22 11:29:02 +00003474/*
drh9e33c2c2007-08-31 18:34:59 +00003475** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003476*/
drhcc6bb3e2007-08-31 16:11:35 +00003477static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003478 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003479 switch( op ){
3480 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003481 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003482 return SQLITE_OK;
3483 }
drh7708e972008-11-29 00:56:52 +00003484 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003485 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003486 return SQLITE_OK;
3487 }
dan6e09d692010-07-27 18:34:15 +00003488 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003489 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003490 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003491 }
drh9ff27ec2010-05-19 19:26:05 +00003492 case SQLITE_FCNTL_SIZE_HINT: {
drhf0b190d2011-07-26 16:03:07 +00003493 return fcntlSizeHint(pFile, *(i64 *)pArg);
3494 }
3495 case SQLITE_FCNTL_PERSIST_WAL: {
3496 int bPersist = *(int*)pArg;
3497 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003498 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003499 }else if( bPersist==0 ){
3500 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3501 }else{
3502 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3503 }
3504 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003505 }
drh8f941bc2009-01-14 23:03:40 +00003506#ifndef NDEBUG
3507 /* The pager calls this method to signal that it has done
3508 ** a rollback and that the database is therefore unchanged and
3509 ** it hence it is OK for the transaction change counter to be
3510 ** unchanged.
3511 */
3512 case SQLITE_FCNTL_DB_UNCHANGED: {
3513 ((unixFile*)id)->dbUpdate = 0;
3514 return SQLITE_OK;
3515 }
3516#endif
drhd2cb50b2009-01-09 21:41:17 +00003517#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003518 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003519 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003520 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003521 }
drhd2cb50b2009-01-09 21:41:17 +00003522#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003523 case SQLITE_FCNTL_SYNC_OMITTED: {
3524 return SQLITE_OK; /* A no-op */
3525 }
drh9e33c2c2007-08-31 18:34:59 +00003526 }
drh0b52b7d2011-01-26 19:46:22 +00003527 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003528}
3529
3530/*
danielk1977a3d4c882007-03-23 10:08:38 +00003531** Return the sector size in bytes of the underlying block device for
3532** the specified file. This is almost always 512 bytes, but may be
3533** larger for some devices.
3534**
3535** SQLite code assumes this function cannot fail. It also assumes that
3536** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003537** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003538** same for both.
3539*/
danielk1977397d65f2008-11-19 11:35:39 +00003540static int unixSectorSize(sqlite3_file *NotUsed){
3541 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003542 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003543}
3544
danielk197790949c22007-08-17 16:50:38 +00003545/*
danielk1977397d65f2008-11-19 11:35:39 +00003546** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003547*/
danielk1977397d65f2008-11-19 11:35:39 +00003548static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3549 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003550 return 0;
3551}
3552
drhd9e5c4f2010-05-12 18:01:39 +00003553#ifndef SQLITE_OMIT_WAL
3554
3555
3556/*
drhd91c68f2010-05-14 14:52:25 +00003557** Object used to represent an shared memory buffer.
3558**
3559** When multiple threads all reference the same wal-index, each thread
3560** has its own unixShm object, but they all point to a single instance
3561** of this unixShmNode object. In other words, each wal-index is opened
3562** only once per process.
3563**
3564** Each unixShmNode object is connected to a single unixInodeInfo object.
3565** We could coalesce this object into unixInodeInfo, but that would mean
3566** every open file that does not use shared memory (in other words, most
3567** open files) would have to carry around this extra information. So
3568** the unixInodeInfo object contains a pointer to this unixShmNode object
3569** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003570**
3571** unixMutexHeld() must be true when creating or destroying
3572** this object or while reading or writing the following fields:
3573**
3574** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003575**
3576** The following fields are read-only after the object is created:
3577**
3578** fid
3579** zFilename
3580**
drhd91c68f2010-05-14 14:52:25 +00003581** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003582** unixMutexHeld() is true when reading or writing any other field
3583** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003584*/
drhd91c68f2010-05-14 14:52:25 +00003585struct unixShmNode {
3586 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003587 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003588 char *zFilename; /* Name of the mmapped file */
3589 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003590 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003591 u16 nRegion; /* Size of array apRegion */
3592 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003593 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003594 int nRef; /* Number of unixShm objects pointing to this */
3595 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003596#ifdef SQLITE_DEBUG
3597 u8 exclMask; /* Mask of exclusive locks held */
3598 u8 sharedMask; /* Mask of shared locks held */
3599 u8 nextShmId; /* Next available unixShm.id value */
3600#endif
3601};
3602
3603/*
drhd9e5c4f2010-05-12 18:01:39 +00003604** Structure used internally by this VFS to record the state of an
3605** open shared memory connection.
3606**
drhd91c68f2010-05-14 14:52:25 +00003607** The following fields are initialized when this object is created and
3608** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003609**
drhd91c68f2010-05-14 14:52:25 +00003610** unixShm.pFile
3611** unixShm.id
3612**
3613** All other fields are read/write. The unixShm.pFile->mutex must be held
3614** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003615*/
3616struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003617 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3618 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003619 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003620 u16 sharedMask; /* Mask of shared locks held */
3621 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003622#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003623 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003624#endif
3625};
3626
3627/*
drhd9e5c4f2010-05-12 18:01:39 +00003628** Constants used for locking
3629*/
drhbd9676c2010-06-23 17:58:38 +00003630#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003631#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003632
drhd9e5c4f2010-05-12 18:01:39 +00003633/*
drh73b64e42010-05-30 19:55:15 +00003634** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003635**
3636** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3637** otherwise.
3638*/
3639static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003640 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3641 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003642 int ofst, /* First byte of the locking range */
3643 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003644){
3645 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003646 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003647
drhd91c68f2010-05-14 14:52:25 +00003648 /* Access to the unixShmNode object is serialized by the caller */
3649 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003650
drh73b64e42010-05-30 19:55:15 +00003651 /* Shared locks never span more than one byte */
3652 assert( n==1 || lockType!=F_RDLCK );
3653
3654 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003655 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003656
drh3cb93392011-03-12 18:10:44 +00003657 if( pShmNode->h>=0 ){
3658 /* Initialize the locking parameters */
3659 memset(&f, 0, sizeof(f));
3660 f.l_type = lockType;
3661 f.l_whence = SEEK_SET;
3662 f.l_start = ofst;
3663 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003664
drh3cb93392011-03-12 18:10:44 +00003665 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3666 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3667 }
drhd9e5c4f2010-05-12 18:01:39 +00003668
3669 /* Update the global lock state and do debug tracing */
3670#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003671 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003672 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003673 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003674 if( rc==SQLITE_OK ){
3675 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003676 OSTRACE(("unlock %d ok", ofst));
3677 pShmNode->exclMask &= ~mask;
3678 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003679 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003680 OSTRACE(("read-lock %d ok", ofst));
3681 pShmNode->exclMask &= ~mask;
3682 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003683 }else{
3684 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003685 OSTRACE(("write-lock %d ok", ofst));
3686 pShmNode->exclMask |= mask;
3687 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003688 }
3689 }else{
3690 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003691 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003692 }else if( lockType==F_RDLCK ){
3693 OSTRACE(("read-lock failed"));
3694 }else{
3695 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003696 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003697 }
3698 }
drh20e1f082010-05-31 16:10:12 +00003699 OSTRACE((" - afterwards %03x,%03x\n",
3700 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003701 }
drhd9e5c4f2010-05-12 18:01:39 +00003702#endif
3703
3704 return rc;
3705}
3706
drhd9e5c4f2010-05-12 18:01:39 +00003707
3708/*
drhd91c68f2010-05-14 14:52:25 +00003709** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003710**
3711** This is not a VFS shared-memory method; it is a utility function called
3712** by VFS shared-memory methods.
3713*/
drhd91c68f2010-05-14 14:52:25 +00003714static void unixShmPurge(unixFile *pFd){
3715 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003716 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003717 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003718 int i;
drhd91c68f2010-05-14 14:52:25 +00003719 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003720 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003721 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003722 if( p->h>=0 ){
3723 munmap(p->apRegion[i], p->szRegion);
3724 }else{
3725 sqlite3_free(p->apRegion[i]);
3726 }
dan13a3cb82010-06-11 19:04:21 +00003727 }
dan18801912010-06-14 14:07:50 +00003728 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003729 if( p->h>=0 ){
3730 robust_close(pFd, p->h, __LINE__);
3731 p->h = -1;
3732 }
drhd91c68f2010-05-14 14:52:25 +00003733 p->pInode->pShmNode = 0;
3734 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003735 }
3736}
3737
3738/*
danda9fe0c2010-07-13 18:44:03 +00003739** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003740** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003741**
drh7234c6d2010-06-19 15:10:09 +00003742** The file used to implement shared-memory is in the same directory
3743** as the open database file and has the same name as the open database
3744** file with the "-shm" suffix added. For example, if the database file
3745** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003746** for shared memory will be called "/home/user1/config.db-shm".
3747**
3748** Another approach to is to use files in /dev/shm or /dev/tmp or an
3749** some other tmpfs mount. But if a file in a different directory
3750** from the database file is used, then differing access permissions
3751** or a chroot() might cause two different processes on the same
3752** database to end up using different files for shared memory -
3753** meaning that their memory would not really be shared - resulting
3754** in database corruption. Nevertheless, this tmpfs file usage
3755** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3756** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3757** option results in an incompatible build of SQLite; builds of SQLite
3758** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3759** same database file at the same time, database corruption will likely
3760** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3761** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003762**
3763** When opening a new shared-memory file, if no other instances of that
3764** file are currently open, in this process or in other processes, then
3765** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003766**
3767** If the original database file (pDbFd) is using the "unix-excl" VFS
3768** that means that an exclusive lock is held on the database file and
3769** that no other processes are able to read or write the database. In
3770** that case, we do not really need shared memory. No shared memory
3771** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003772*/
danda9fe0c2010-07-13 18:44:03 +00003773static int unixOpenSharedMemory(unixFile *pDbFd){
3774 struct unixShm *p = 0; /* The connection to be opened */
3775 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3776 int rc; /* Result code */
3777 unixInodeInfo *pInode; /* The inode of fd */
3778 char *zShmFilename; /* Name of the file used for SHM */
3779 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003780
danda9fe0c2010-07-13 18:44:03 +00003781 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003782 p = sqlite3_malloc( sizeof(*p) );
3783 if( p==0 ) return SQLITE_NOMEM;
3784 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003785 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003786
danda9fe0c2010-07-13 18:44:03 +00003787 /* Check to see if a unixShmNode object already exists. Reuse an existing
3788 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003789 */
3790 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003791 pInode = pDbFd->pInode;
3792 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003793 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003794 struct stat sStat; /* fstat() info for database file */
3795
3796 /* Call fstat() to figure out the permissions on the database file. If
3797 ** a new *-shm file is created, an attempt will be made to create it
3798 ** with the same permissions. The actual permissions the file is created
3799 ** with are subject to the current umask setting.
3800 */
drh3cb93392011-03-12 18:10:44 +00003801 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003802 rc = SQLITE_IOERR_FSTAT;
3803 goto shm_open_err;
3804 }
3805
drha4ced192010-07-15 18:32:40 +00003806#ifdef SQLITE_SHM_DIRECTORY
3807 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3808#else
drh7234c6d2010-06-19 15:10:09 +00003809 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003810#endif
drh7234c6d2010-06-19 15:10:09 +00003811 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003812 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003813 rc = SQLITE_NOMEM;
3814 goto shm_open_err;
3815 }
drhd91c68f2010-05-14 14:52:25 +00003816 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003817 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003818#ifdef SQLITE_SHM_DIRECTORY
3819 sqlite3_snprintf(nShmFilename, zShmFilename,
3820 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3821 (u32)sStat.st_ino, (u32)sStat.st_dev);
3822#else
drh7234c6d2010-06-19 15:10:09 +00003823 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003824 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003825#endif
drhd91c68f2010-05-14 14:52:25 +00003826 pShmNode->h = -1;
3827 pDbFd->pInode->pShmNode = pShmNode;
3828 pShmNode->pInode = pDbFd->pInode;
3829 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3830 if( pShmNode->mutex==0 ){
3831 rc = SQLITE_NOMEM;
3832 goto shm_open_err;
3833 }
drhd9e5c4f2010-05-12 18:01:39 +00003834
drh3cb93392011-03-12 18:10:44 +00003835 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003836 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3837 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003838 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003839 const char *zRO;
3840 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003841 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003842 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3843 (sStat.st_mode & 0777));
3844 pShmNode->isReadonly = 1;
3845 }
3846 if( pShmNode->h<0 ){
3847 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3848 goto shm_open_err;
3849 }
drhd9e5c4f2010-05-12 18:01:39 +00003850 }
drh3cb93392011-03-12 18:10:44 +00003851
3852 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003853 ** If not, truncate the file to zero length.
3854 */
3855 rc = SQLITE_OK;
3856 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3857 if( robust_ftruncate(pShmNode->h, 0) ){
3858 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003859 }
3860 }
drh66dfec8b2011-06-01 20:01:49 +00003861 if( rc==SQLITE_OK ){
3862 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3863 }
3864 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003865 }
drhd9e5c4f2010-05-12 18:01:39 +00003866 }
3867
drhd91c68f2010-05-14 14:52:25 +00003868 /* Make the new connection a child of the unixShmNode */
3869 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003870#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003871 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003872#endif
drhd91c68f2010-05-14 14:52:25 +00003873 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003874 pDbFd->pShm = p;
3875 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003876
3877 /* The reference count on pShmNode has already been incremented under
3878 ** the cover of the unixEnterMutex() mutex and the pointer from the
3879 ** new (struct unixShm) object to the pShmNode has been set. All that is
3880 ** left to do is to link the new object into the linked list starting
3881 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3882 ** mutex.
3883 */
3884 sqlite3_mutex_enter(pShmNode->mutex);
3885 p->pNext = pShmNode->pFirst;
3886 pShmNode->pFirst = p;
3887 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003888 return SQLITE_OK;
3889
3890 /* Jump here on any error */
3891shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003892 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003893 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003894 unixLeaveMutex();
3895 return rc;
3896}
3897
3898/*
danda9fe0c2010-07-13 18:44:03 +00003899** This function is called to obtain a pointer to region iRegion of the
3900** shared-memory associated with the database file fd. Shared-memory regions
3901** are numbered starting from zero. Each shared-memory region is szRegion
3902** bytes in size.
3903**
3904** If an error occurs, an error code is returned and *pp is set to NULL.
3905**
3906** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3907** region has not been allocated (by any client, including one running in a
3908** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3909** bExtend is non-zero and the requested shared-memory region has not yet
3910** been allocated, it is allocated by this function.
3911**
3912** If the shared-memory region has already been allocated or is allocated by
3913** this call as described above, then it is mapped into this processes
3914** address space (if it is not already), *pp is set to point to the mapped
3915** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003916*/
danda9fe0c2010-07-13 18:44:03 +00003917static int unixShmMap(
3918 sqlite3_file *fd, /* Handle open on database file */
3919 int iRegion, /* Region to retrieve */
3920 int szRegion, /* Size of regions */
3921 int bExtend, /* True to extend file if necessary */
3922 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003923){
danda9fe0c2010-07-13 18:44:03 +00003924 unixFile *pDbFd = (unixFile*)fd;
3925 unixShm *p;
3926 unixShmNode *pShmNode;
3927 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003928
danda9fe0c2010-07-13 18:44:03 +00003929 /* If the shared-memory file has not yet been opened, open it now. */
3930 if( pDbFd->pShm==0 ){
3931 rc = unixOpenSharedMemory(pDbFd);
3932 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003933 }
drhd9e5c4f2010-05-12 18:01:39 +00003934
danda9fe0c2010-07-13 18:44:03 +00003935 p = pDbFd->pShm;
3936 pShmNode = p->pShmNode;
3937 sqlite3_mutex_enter(pShmNode->mutex);
3938 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003939 assert( pShmNode->pInode==pDbFd->pInode );
3940 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3941 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003942
3943 if( pShmNode->nRegion<=iRegion ){
3944 char **apNew; /* New apRegion[] array */
3945 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3946 struct stat sStat; /* Used by fstat() */
3947
3948 pShmNode->szRegion = szRegion;
3949
drh3cb93392011-03-12 18:10:44 +00003950 if( pShmNode->h>=0 ){
3951 /* The requested region is not mapped into this processes address space.
3952 ** Check to see if it has been allocated (i.e. if the wal-index file is
3953 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003954 */
drh3cb93392011-03-12 18:10:44 +00003955 if( osFstat(pShmNode->h, &sStat) ){
3956 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003957 goto shmpage_out;
3958 }
drh3cb93392011-03-12 18:10:44 +00003959
3960 if( sStat.st_size<nByte ){
3961 /* The requested memory region does not exist. If bExtend is set to
3962 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3963 **
3964 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3965 ** the requested memory region.
3966 */
3967 if( !bExtend ) goto shmpage_out;
3968 if( robust_ftruncate(pShmNode->h, nByte) ){
3969 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3970 pShmNode->zFilename);
3971 goto shmpage_out;
3972 }
3973 }
danda9fe0c2010-07-13 18:44:03 +00003974 }
3975
3976 /* Map the requested memory region into this processes address space. */
3977 apNew = (char **)sqlite3_realloc(
3978 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3979 );
3980 if( !apNew ){
3981 rc = SQLITE_IOERR_NOMEM;
3982 goto shmpage_out;
3983 }
3984 pShmNode->apRegion = apNew;
3985 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003986 void *pMem;
3987 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00003988 pMem = mmap(0, szRegion,
3989 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00003990 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3991 );
3992 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003993 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003994 goto shmpage_out;
3995 }
3996 }else{
3997 pMem = sqlite3_malloc(szRegion);
3998 if( pMem==0 ){
3999 rc = SQLITE_NOMEM;
4000 goto shmpage_out;
4001 }
4002 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004003 }
4004 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4005 pShmNode->nRegion++;
4006 }
4007 }
4008
4009shmpage_out:
4010 if( pShmNode->nRegion>iRegion ){
4011 *pp = pShmNode->apRegion[iRegion];
4012 }else{
4013 *pp = 0;
4014 }
drh66dfec8b2011-06-01 20:01:49 +00004015 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004016 sqlite3_mutex_leave(pShmNode->mutex);
4017 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004018}
4019
4020/*
drhd9e5c4f2010-05-12 18:01:39 +00004021** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004022**
4023** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4024** different here than in posix. In xShmLock(), one can go from unlocked
4025** to shared and back or from unlocked to exclusive and back. But one may
4026** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004027*/
4028static int unixShmLock(
4029 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004030 int ofst, /* First lock to acquire or release */
4031 int n, /* Number of locks to acquire or release */
4032 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004033){
drh73b64e42010-05-30 19:55:15 +00004034 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4035 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4036 unixShm *pX; /* For looping over all siblings */
4037 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4038 int rc = SQLITE_OK; /* Result code */
4039 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004040
drhd91c68f2010-05-14 14:52:25 +00004041 assert( pShmNode==pDbFd->pInode->pShmNode );
4042 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004043 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004044 assert( n>=1 );
4045 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4046 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4047 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4048 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4049 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004050 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4051 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004052
drhc99597c2010-05-31 01:41:15 +00004053 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004054 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004055 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004056 if( flags & SQLITE_SHM_UNLOCK ){
4057 u16 allMask = 0; /* Mask of locks held by siblings */
4058
4059 /* See if any siblings hold this same lock */
4060 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4061 if( pX==p ) continue;
4062 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4063 allMask |= pX->sharedMask;
4064 }
4065
4066 /* Unlock the system-level locks */
4067 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004068 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004069 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004070 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004071 }
drh73b64e42010-05-30 19:55:15 +00004072
4073 /* Undo the local locks */
4074 if( rc==SQLITE_OK ){
4075 p->exclMask &= ~mask;
4076 p->sharedMask &= ~mask;
4077 }
4078 }else if( flags & SQLITE_SHM_SHARED ){
4079 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4080
4081 /* Find out which shared locks are already held by sibling connections.
4082 ** If any sibling already holds an exclusive lock, go ahead and return
4083 ** SQLITE_BUSY.
4084 */
4085 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004086 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004087 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004088 break;
4089 }
4090 allShared |= pX->sharedMask;
4091 }
4092
4093 /* Get shared locks at the system level, if necessary */
4094 if( rc==SQLITE_OK ){
4095 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004096 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004097 }else{
drh73b64e42010-05-30 19:55:15 +00004098 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004099 }
drhd9e5c4f2010-05-12 18:01:39 +00004100 }
drh73b64e42010-05-30 19:55:15 +00004101
4102 /* Get the local shared locks */
4103 if( rc==SQLITE_OK ){
4104 p->sharedMask |= mask;
4105 }
4106 }else{
4107 /* Make sure no sibling connections hold locks that will block this
4108 ** lock. If any do, return SQLITE_BUSY right away.
4109 */
4110 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004111 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4112 rc = SQLITE_BUSY;
4113 break;
4114 }
4115 }
4116
4117 /* Get the exclusive locks at the system level. Then if successful
4118 ** also mark the local connection as being locked.
4119 */
4120 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004121 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004122 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004123 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004124 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004125 }
drhd9e5c4f2010-05-12 18:01:39 +00004126 }
4127 }
drhd91c68f2010-05-14 14:52:25 +00004128 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004129 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4130 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004131 return rc;
4132}
4133
drh286a2882010-05-20 23:51:06 +00004134/*
4135** Implement a memory barrier or memory fence on shared memory.
4136**
4137** All loads and stores begun before the barrier must complete before
4138** any load or store begun after the barrier.
4139*/
4140static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004141 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004142){
drhff828942010-06-26 21:34:06 +00004143 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004144 unixEnterMutex();
4145 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004146}
4147
dan18801912010-06-14 14:07:50 +00004148/*
danda9fe0c2010-07-13 18:44:03 +00004149** Close a connection to shared-memory. Delete the underlying
4150** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004151**
4152** If there is no shared memory associated with the connection then this
4153** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004154*/
danda9fe0c2010-07-13 18:44:03 +00004155static int unixShmUnmap(
4156 sqlite3_file *fd, /* The underlying database file */
4157 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004158){
danda9fe0c2010-07-13 18:44:03 +00004159 unixShm *p; /* The connection to be closed */
4160 unixShmNode *pShmNode; /* The underlying shared-memory file */
4161 unixShm **pp; /* For looping over sibling connections */
4162 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004163
danda9fe0c2010-07-13 18:44:03 +00004164 pDbFd = (unixFile*)fd;
4165 p = pDbFd->pShm;
4166 if( p==0 ) return SQLITE_OK;
4167 pShmNode = p->pShmNode;
4168
4169 assert( pShmNode==pDbFd->pInode->pShmNode );
4170 assert( pShmNode->pInode==pDbFd->pInode );
4171
4172 /* Remove connection p from the set of connections associated
4173 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004174 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004175 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4176 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004177
danda9fe0c2010-07-13 18:44:03 +00004178 /* Free the connection p */
4179 sqlite3_free(p);
4180 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004181 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004182
4183 /* If pShmNode->nRef has reached 0, then close the underlying
4184 ** shared-memory file, too */
4185 unixEnterMutex();
4186 assert( pShmNode->nRef>0 );
4187 pShmNode->nRef--;
4188 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004189 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004190 unixShmPurge(pDbFd);
4191 }
4192 unixLeaveMutex();
4193
4194 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004195}
drh286a2882010-05-20 23:51:06 +00004196
danda9fe0c2010-07-13 18:44:03 +00004197
drhd9e5c4f2010-05-12 18:01:39 +00004198#else
drh6b017cc2010-06-14 18:01:46 +00004199# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004200# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004201# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004202# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004203#endif /* #ifndef SQLITE_OMIT_WAL */
4204
drh734c9862008-11-28 15:37:20 +00004205/*
4206** Here ends the implementation of all sqlite3_file methods.
4207**
4208********************** End sqlite3_file Methods *******************************
4209******************************************************************************/
4210
4211/*
drh6b9d6dd2008-12-03 19:34:47 +00004212** This division contains definitions of sqlite3_io_methods objects that
4213** implement various file locking strategies. It also contains definitions
4214** of "finder" functions. A finder-function is used to locate the appropriate
4215** sqlite3_io_methods object for a particular database file. The pAppData
4216** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4217** the correct finder-function for that VFS.
4218**
4219** Most finder functions return a pointer to a fixed sqlite3_io_methods
4220** object. The only interesting finder-function is autolockIoFinder, which
4221** looks at the filesystem type and tries to guess the best locking
4222** strategy from that.
4223**
drh1875f7a2008-12-08 18:19:17 +00004224** For finder-funtion F, two objects are created:
4225**
4226** (1) The real finder-function named "FImpt()".
4227**
dane946c392009-08-22 11:39:46 +00004228** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004229**
4230**
4231** A pointer to the F pointer is used as the pAppData value for VFS
4232** objects. We have to do this instead of letting pAppData point
4233** directly at the finder-function since C90 rules prevent a void*
4234** from be cast into a function pointer.
4235**
drh6b9d6dd2008-12-03 19:34:47 +00004236**
drh7708e972008-11-29 00:56:52 +00004237** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004238**
drh7708e972008-11-29 00:56:52 +00004239** * A constant sqlite3_io_methods object call METHOD that has locking
4240** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4241**
4242** * An I/O method finder function called FINDER that returns a pointer
4243** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004244*/
drhd9e5c4f2010-05-12 18:01:39 +00004245#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004246static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004247 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004248 CLOSE, /* xClose */ \
4249 unixRead, /* xRead */ \
4250 unixWrite, /* xWrite */ \
4251 unixTruncate, /* xTruncate */ \
4252 unixSync, /* xSync */ \
4253 unixFileSize, /* xFileSize */ \
4254 LOCK, /* xLock */ \
4255 UNLOCK, /* xUnlock */ \
4256 CKLOCK, /* xCheckReservedLock */ \
4257 unixFileControl, /* xFileControl */ \
4258 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004259 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004260 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004261 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004262 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004263 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004264}; \
drh0c2694b2009-09-03 16:23:44 +00004265static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4266 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004267 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004268} \
drh0c2694b2009-09-03 16:23:44 +00004269static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004270 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004271
4272/*
4273** Here are all of the sqlite3_io_methods objects for each of the
4274** locking strategies. Functions that return pointers to these methods
4275** are also created.
4276*/
4277IOMETHODS(
4278 posixIoFinder, /* Finder function name */
4279 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004280 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004281 unixClose, /* xClose method */
4282 unixLock, /* xLock method */
4283 unixUnlock, /* xUnlock method */
4284 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004285)
drh7708e972008-11-29 00:56:52 +00004286IOMETHODS(
4287 nolockIoFinder, /* Finder function name */
4288 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004289 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004290 nolockClose, /* xClose method */
4291 nolockLock, /* xLock method */
4292 nolockUnlock, /* xUnlock method */
4293 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004294)
drh7708e972008-11-29 00:56:52 +00004295IOMETHODS(
4296 dotlockIoFinder, /* Finder function name */
4297 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004298 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004299 dotlockClose, /* xClose method */
4300 dotlockLock, /* xLock method */
4301 dotlockUnlock, /* xUnlock method */
4302 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004303)
drh7708e972008-11-29 00:56:52 +00004304
chw78a13182009-04-07 05:35:03 +00004305#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004306IOMETHODS(
4307 flockIoFinder, /* Finder function name */
4308 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004309 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004310 flockClose, /* xClose method */
4311 flockLock, /* xLock method */
4312 flockUnlock, /* xUnlock method */
4313 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004314)
drh7708e972008-11-29 00:56:52 +00004315#endif
4316
drh6c7d5c52008-11-21 20:32:33 +00004317#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004318IOMETHODS(
4319 semIoFinder, /* Finder function name */
4320 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004321 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004322 semClose, /* xClose method */
4323 semLock, /* xLock method */
4324 semUnlock, /* xUnlock method */
4325 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004326)
aswiftaebf4132008-11-21 00:10:35 +00004327#endif
drh7708e972008-11-29 00:56:52 +00004328
drhd2cb50b2009-01-09 21:41:17 +00004329#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004330IOMETHODS(
4331 afpIoFinder, /* Finder function name */
4332 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004333 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004334 afpClose, /* xClose method */
4335 afpLock, /* xLock method */
4336 afpUnlock, /* xUnlock method */
4337 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004338)
drh715ff302008-12-03 22:32:44 +00004339#endif
4340
4341/*
4342** The proxy locking method is a "super-method" in the sense that it
4343** opens secondary file descriptors for the conch and lock files and
4344** it uses proxy, dot-file, AFP, and flock() locking methods on those
4345** secondary files. For this reason, the division that implements
4346** proxy locking is located much further down in the file. But we need
4347** to go ahead and define the sqlite3_io_methods and finder function
4348** for proxy locking here. So we forward declare the I/O methods.
4349*/
drhd2cb50b2009-01-09 21:41:17 +00004350#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004351static int proxyClose(sqlite3_file*);
4352static int proxyLock(sqlite3_file*, int);
4353static int proxyUnlock(sqlite3_file*, int);
4354static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004355IOMETHODS(
4356 proxyIoFinder, /* Finder function name */
4357 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004358 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004359 proxyClose, /* xClose method */
4360 proxyLock, /* xLock method */
4361 proxyUnlock, /* xUnlock method */
4362 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004363)
aswiftaebf4132008-11-21 00:10:35 +00004364#endif
drh7708e972008-11-29 00:56:52 +00004365
drh7ed97b92010-01-20 13:07:21 +00004366/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4367#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4368IOMETHODS(
4369 nfsIoFinder, /* Finder function name */
4370 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004371 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004372 unixClose, /* xClose method */
4373 unixLock, /* xLock method */
4374 nfsUnlock, /* xUnlock method */
4375 unixCheckReservedLock /* xCheckReservedLock method */
4376)
4377#endif
drh7708e972008-11-29 00:56:52 +00004378
drhd2cb50b2009-01-09 21:41:17 +00004379#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004380/*
drh6b9d6dd2008-12-03 19:34:47 +00004381** This "finder" function attempts to determine the best locking strategy
4382** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004383** object that implements that strategy.
4384**
4385** This is for MacOSX only.
4386*/
drh1875f7a2008-12-08 18:19:17 +00004387static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004388 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004389 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004390){
4391 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004392 const char *zFilesystem; /* Filesystem type name */
4393 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004394 } aMap[] = {
4395 { "hfs", &posixIoMethods },
4396 { "ufs", &posixIoMethods },
4397 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004398 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004399 { "webdav", &nolockIoMethods },
4400 { 0, 0 }
4401 };
4402 int i;
4403 struct statfs fsInfo;
4404 struct flock lockInfo;
4405
4406 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004407 /* If filePath==NULL that means we are dealing with a transient file
4408 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004409 return &nolockIoMethods;
4410 }
4411 if( statfs(filePath, &fsInfo) != -1 ){
4412 if( fsInfo.f_flags & MNT_RDONLY ){
4413 return &nolockIoMethods;
4414 }
4415 for(i=0; aMap[i].zFilesystem; i++){
4416 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4417 return aMap[i].pMethods;
4418 }
4419 }
4420 }
4421
4422 /* Default case. Handles, amongst others, "nfs".
4423 ** Test byte-range lock using fcntl(). If the call succeeds,
4424 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004425 */
drh7708e972008-11-29 00:56:52 +00004426 lockInfo.l_len = 1;
4427 lockInfo.l_start = 0;
4428 lockInfo.l_whence = SEEK_SET;
4429 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004430 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004431 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4432 return &nfsIoMethods;
4433 } else {
4434 return &posixIoMethods;
4435 }
drh7708e972008-11-29 00:56:52 +00004436 }else{
4437 return &dotlockIoMethods;
4438 }
4439}
drh0c2694b2009-09-03 16:23:44 +00004440static const sqlite3_io_methods
4441 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004442
drhd2cb50b2009-01-09 21:41:17 +00004443#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004444
chw78a13182009-04-07 05:35:03 +00004445#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4446/*
4447** This "finder" function attempts to determine the best locking strategy
4448** for the database file "filePath". It then returns the sqlite3_io_methods
4449** object that implements that strategy.
4450**
4451** This is for VXWorks only.
4452*/
4453static const sqlite3_io_methods *autolockIoFinderImpl(
4454 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004455 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004456){
4457 struct flock lockInfo;
4458
4459 if( !filePath ){
4460 /* If filePath==NULL that means we are dealing with a transient file
4461 ** that does not need to be locked. */
4462 return &nolockIoMethods;
4463 }
4464
4465 /* Test if fcntl() is supported and use POSIX style locks.
4466 ** Otherwise fall back to the named semaphore method.
4467 */
4468 lockInfo.l_len = 1;
4469 lockInfo.l_start = 0;
4470 lockInfo.l_whence = SEEK_SET;
4471 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004472 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004473 return &posixIoMethods;
4474 }else{
4475 return &semIoMethods;
4476 }
4477}
drh0c2694b2009-09-03 16:23:44 +00004478static const sqlite3_io_methods
4479 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004480
4481#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4482
drh7708e972008-11-29 00:56:52 +00004483/*
4484** An abstract type for a pointer to a IO method finder function:
4485*/
drh0c2694b2009-09-03 16:23:44 +00004486typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004487
aswiftaebf4132008-11-21 00:10:35 +00004488
drh734c9862008-11-28 15:37:20 +00004489/****************************************************************************
4490**************************** sqlite3_vfs methods ****************************
4491**
4492** This division contains the implementation of methods on the
4493** sqlite3_vfs object.
4494*/
4495
danielk1977a3d4c882007-03-23 10:08:38 +00004496/*
danielk1977e339d652008-06-28 11:23:00 +00004497** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004498*/
4499static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004500 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004501 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004502 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004503 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004504 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004505 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004506 int isDelete, /* Delete on close if true */
4507 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004508){
drh7708e972008-11-29 00:56:52 +00004509 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004510 unixFile *pNew = (unixFile *)pId;
4511 int rc = SQLITE_OK;
4512
drh8af6c222010-05-14 12:43:01 +00004513 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004514
dane946c392009-08-22 11:39:46 +00004515 /* Parameter isDelete is only used on vxworks. Express this explicitly
4516 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004517 */
drh7708e972008-11-29 00:56:52 +00004518 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004519
dan00157392010-10-05 11:33:15 +00004520 /* Usually the path zFilename should not be a relative pathname. The
4521 ** exception is when opening the proxy "conch" file in builds that
4522 ** include the special Apple locking styles.
4523 */
dan00157392010-10-05 11:33:15 +00004524#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004525 assert( zFilename==0 || zFilename[0]=='/'
4526 || pVfs->pAppData==(void*)&autolockIoFinder );
4527#else
4528 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004529#endif
dan00157392010-10-05 11:33:15 +00004530
drh308c2a52010-05-14 11:30:18 +00004531 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004532 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004533 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004534 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4535 pNew->ctrlFlags = UNIXFILE_EXCL;
4536 }else{
4537 pNew->ctrlFlags = 0;
4538 }
drh77197112011-03-15 19:08:48 +00004539 if( isReadOnly ){
4540 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4541 }
drh0059eae2011-08-08 23:48:40 +00004542 if( syncDir ){
4543 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4544 }
drh339eb0b2008-03-07 15:34:11 +00004545
drh6c7d5c52008-11-21 20:32:33 +00004546#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004547 pNew->pId = vxworksFindFileId(zFilename);
4548 if( pNew->pId==0 ){
4549 noLock = 1;
4550 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004551 }
4552#endif
4553
drhda0e7682008-07-30 15:27:54 +00004554 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004555 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004556 }else{
drh0c2694b2009-09-03 16:23:44 +00004557 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004558#if SQLITE_ENABLE_LOCKING_STYLE
4559 /* Cache zFilename in the locking context (AFP and dotlock override) for
4560 ** proxyLock activation is possible (remote proxy is based on db name)
4561 ** zFilename remains valid until file is closed, to support */
4562 pNew->lockingContext = (void*)zFilename;
4563#endif
drhda0e7682008-07-30 15:27:54 +00004564 }
danielk1977e339d652008-06-28 11:23:00 +00004565
drh7ed97b92010-01-20 13:07:21 +00004566 if( pLockingStyle == &posixIoMethods
4567#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4568 || pLockingStyle == &nfsIoMethods
4569#endif
4570 ){
drh7708e972008-11-29 00:56:52 +00004571 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004572 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004573 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004574 /* If an error occured in findInodeInfo(), close the file descriptor
4575 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004576 ** in two scenarios:
4577 **
4578 ** (a) A call to fstat() failed.
4579 ** (b) A malloc failed.
4580 **
4581 ** Scenario (b) may only occur if the process is holding no other
4582 ** file descriptors open on the same file. If there were other file
4583 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004584 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004585 ** handle h - as it is guaranteed that no posix locks will be released
4586 ** by doing so.
4587 **
4588 ** If scenario (a) caused the error then things are not so safe. The
4589 ** implicit assumption here is that if fstat() fails, things are in
4590 ** such bad shape that dropping a lock or two doesn't matter much.
4591 */
drh0e9365c2011-03-02 02:08:13 +00004592 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004593 h = -1;
4594 }
drh7708e972008-11-29 00:56:52 +00004595 unixLeaveMutex();
4596 }
danielk1977e339d652008-06-28 11:23:00 +00004597
drhd2cb50b2009-01-09 21:41:17 +00004598#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004599 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004600 /* AFP locking uses the file path so it needs to be included in
4601 ** the afpLockingContext.
4602 */
4603 afpLockingContext *pCtx;
4604 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4605 if( pCtx==0 ){
4606 rc = SQLITE_NOMEM;
4607 }else{
4608 /* NB: zFilename exists and remains valid until the file is closed
4609 ** according to requirement F11141. So we do not need to make a
4610 ** copy of the filename. */
4611 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004612 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004613 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004614 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004615 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004616 if( rc!=SQLITE_OK ){
4617 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004618 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004619 h = -1;
4620 }
drh7708e972008-11-29 00:56:52 +00004621 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004622 }
drh7708e972008-11-29 00:56:52 +00004623 }
4624#endif
danielk1977e339d652008-06-28 11:23:00 +00004625
drh7708e972008-11-29 00:56:52 +00004626 else if( pLockingStyle == &dotlockIoMethods ){
4627 /* Dotfile locking uses the file path so it needs to be included in
4628 ** the dotlockLockingContext
4629 */
4630 char *zLockFile;
4631 int nFilename;
drhea678832008-12-10 19:26:22 +00004632 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004633 zLockFile = (char *)sqlite3_malloc(nFilename);
4634 if( zLockFile==0 ){
4635 rc = SQLITE_NOMEM;
4636 }else{
4637 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004638 }
drh7708e972008-11-29 00:56:52 +00004639 pNew->lockingContext = zLockFile;
4640 }
danielk1977e339d652008-06-28 11:23:00 +00004641
drh6c7d5c52008-11-21 20:32:33 +00004642#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004643 else if( pLockingStyle == &semIoMethods ){
4644 /* Named semaphore locking uses the file path so it needs to be
4645 ** included in the semLockingContext
4646 */
4647 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004648 rc = findInodeInfo(pNew, &pNew->pInode);
4649 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4650 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004651 int n;
drh2238dcc2009-08-27 17:56:20 +00004652 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004653 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004654 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004655 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004656 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4657 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004658 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004659 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004660 }
chw97185482008-11-17 08:05:31 +00004661 }
drh7708e972008-11-29 00:56:52 +00004662 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004663 }
drh7708e972008-11-29 00:56:52 +00004664#endif
aswift5b1a2562008-08-22 00:22:35 +00004665
4666 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004667#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004668 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004669 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004670 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004671 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004672 isDelete = 0;
4673 }
4674 pNew->isDelete = isDelete;
4675#endif
danielk1977e339d652008-06-28 11:23:00 +00004676 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004677 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004678 }else{
drh7708e972008-11-29 00:56:52 +00004679 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004680 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004681 }
danielk1977e339d652008-06-28 11:23:00 +00004682 return rc;
drh054889e2005-11-30 03:20:31 +00004683}
drh9c06c952005-11-26 00:25:00 +00004684
danielk1977ad94b582007-08-20 06:44:22 +00004685/*
drh8b3cf822010-06-01 21:02:51 +00004686** Return the name of a directory in which to put temporary files.
4687** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004688*/
drh7234c6d2010-06-19 15:10:09 +00004689static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004690 static const char *azDirs[] = {
4691 0,
aswiftaebf4132008-11-21 00:10:35 +00004692 0,
danielk197717b90b52008-06-06 11:11:25 +00004693 "/var/tmp",
4694 "/usr/tmp",
4695 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004696 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004697 };
drh8b3cf822010-06-01 21:02:51 +00004698 unsigned int i;
4699 struct stat buf;
4700 const char *zDir = 0;
4701
4702 azDirs[0] = sqlite3_temp_directory;
4703 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004704 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004705 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004706 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004707 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004708 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004709 break;
4710 }
4711 return zDir;
4712}
4713
4714/*
4715** Create a temporary file name in zBuf. zBuf must be allocated
4716** by the calling process and must be big enough to hold at least
4717** pVfs->mxPathname bytes.
4718*/
4719static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004720 static const unsigned char zChars[] =
4721 "abcdefghijklmnopqrstuvwxyz"
4722 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4723 "0123456789";
drh41022642008-11-21 00:24:42 +00004724 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004725 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004726
4727 /* It's odd to simulate an io-error here, but really this is just
4728 ** using the io-error infrastructure to test that SQLite handles this
4729 ** function failing.
4730 */
4731 SimulateIOError( return SQLITE_IOERR );
4732
drh7234c6d2010-06-19 15:10:09 +00004733 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004734 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004735
4736 /* Check that the output buffer is large enough for the temporary file
4737 ** name. If it is not, return SQLITE_ERROR.
4738 */
danielk197700e13612008-11-17 19:18:54 +00004739 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004740 return SQLITE_ERROR;
4741 }
4742
4743 do{
4744 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004745 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004746 sqlite3_randomness(15, &zBuf[j]);
4747 for(i=0; i<15; i++, j++){
4748 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4749 }
4750 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004751 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004752 return SQLITE_OK;
4753}
4754
drhd2cb50b2009-01-09 21:41:17 +00004755#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004756/*
4757** Routine to transform a unixFile into a proxy-locking unixFile.
4758** Implementation in the proxy-lock division, but used by unixOpen()
4759** if SQLITE_PREFER_PROXY_LOCKING is defined.
4760*/
4761static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004762#endif
drhc66d5b62008-12-03 22:48:32 +00004763
dan08da86a2009-08-21 17:18:03 +00004764/*
4765** Search for an unused file descriptor that was opened on the database
4766** file (not a journal or master-journal file) identified by pathname
4767** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4768** argument to this function.
4769**
4770** Such a file descriptor may exist if a database connection was closed
4771** but the associated file descriptor could not be closed because some
4772** other file descriptor open on the same file is holding a file-lock.
4773** Refer to comments in the unixClose() function and the lengthy comment
4774** describing "Posix Advisory Locking" at the start of this file for
4775** further details. Also, ticket #4018.
4776**
4777** If a suitable file descriptor is found, then it is returned. If no
4778** such file descriptor is located, -1 is returned.
4779*/
dane946c392009-08-22 11:39:46 +00004780static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4781 UnixUnusedFd *pUnused = 0;
4782
4783 /* Do not search for an unused file descriptor on vxworks. Not because
4784 ** vxworks would not benefit from the change (it might, we're not sure),
4785 ** but because no way to test it is currently available. It is better
4786 ** not to risk breaking vxworks support for the sake of such an obscure
4787 ** feature. */
4788#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004789 struct stat sStat; /* Results of stat() call */
4790
4791 /* A stat() call may fail for various reasons. If this happens, it is
4792 ** almost certain that an open() call on the same path will also fail.
4793 ** For this reason, if an error occurs in the stat() call here, it is
4794 ** ignored and -1 is returned. The caller will try to open a new file
4795 ** descriptor on the same path, fail, and return an error to SQLite.
4796 **
4797 ** Even if a subsequent open() call does succeed, the consequences of
4798 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004799 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004800 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004801
4802 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004803 pInode = inodeList;
4804 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4805 || pInode->fileId.ino!=sStat.st_ino) ){
4806 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004807 }
drh8af6c222010-05-14 12:43:01 +00004808 if( pInode ){
dane946c392009-08-22 11:39:46 +00004809 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004810 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004811 pUnused = *pp;
4812 if( pUnused ){
4813 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004814 }
4815 }
4816 unixLeaveMutex();
4817 }
dane946c392009-08-22 11:39:46 +00004818#endif /* if !OS_VXWORKS */
4819 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004820}
danielk197717b90b52008-06-06 11:11:25 +00004821
4822/*
danddb0ac42010-07-14 14:48:58 +00004823** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004824** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004825** and a value suitable for passing as the third argument to open(2) is
4826** written to *pMode. If an IO error occurs, an SQLite error code is
4827** returned and the value of *pMode is not modified.
4828**
4829** If the file being opened is a temporary file, it is always created with
4830** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004831** is a database or master journal file, it is created with the permissions
4832** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004833**
drh8ab58662010-07-15 18:38:39 +00004834** Finally, if the file being opened is a WAL or regular journal file, then
4835** this function queries the file-system for the permissions on the
4836** corresponding database file and sets *pMode to this value. Whenever
4837** possible, WAL and journal files are created using the same permissions
4838** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004839**
4840** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4841** original filename is unavailable. But 8_3_NAMES is only used for
4842** FAT filesystems and permissions do not matter there, so just use
4843** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004844*/
4845static int findCreateFileMode(
4846 const char *zPath, /* Path of file (possibly) being created */
4847 int flags, /* Flags passed as 4th argument to xOpen() */
4848 mode_t *pMode /* OUT: Permissions to open file with */
4849){
4850 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004851 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004852 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004853 char zDb[MAX_PATHNAME+1]; /* Database file path */
4854 int nDb; /* Number of valid bytes in zDb */
4855 struct stat sStat; /* Output of stat() on database file */
4856
dana0c989d2010-11-05 18:07:37 +00004857 /* zPath is a path to a WAL or journal file. The following block derives
4858 ** the path to the associated database file from zPath. This block handles
4859 ** the following naming conventions:
4860 **
4861 ** "<path to db>-journal"
4862 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004863 ** "<path to db>-journalNN"
4864 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004865 **
drh81cc5162011-05-17 20:36:21 +00004866 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004867 ** used by the test_multiplex.c module.
4868 */
4869 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004870 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4871 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004872 memcpy(zDb, zPath, nDb);
4873 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004874
drh58384f12011-07-28 00:14:45 +00004875 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004876 *pMode = sStat.st_mode & 0777;
4877 }else{
4878 rc = SQLITE_IOERR_FSTAT;
4879 }
4880 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4881 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004882 }
4883 return rc;
4884}
4885
4886/*
danielk1977ad94b582007-08-20 06:44:22 +00004887** Open the file zPath.
4888**
danielk1977b4b47412007-08-17 15:53:36 +00004889** Previously, the SQLite OS layer used three functions in place of this
4890** one:
4891**
4892** sqlite3OsOpenReadWrite();
4893** sqlite3OsOpenReadOnly();
4894** sqlite3OsOpenExclusive();
4895**
4896** These calls correspond to the following combinations of flags:
4897**
4898** ReadWrite() -> (READWRITE | CREATE)
4899** ReadOnly() -> (READONLY)
4900** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4901**
4902** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4903** true, the file was configured to be automatically deleted when the
4904** file handle closed. To achieve the same effect using this new
4905** interface, add the DELETEONCLOSE flag to those specified above for
4906** OpenExclusive().
4907*/
4908static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004909 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4910 const char *zPath, /* Pathname of file to be opened */
4911 sqlite3_file *pFile, /* The file descriptor to be filled in */
4912 int flags, /* Input flags to control the opening */
4913 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004914){
dan08da86a2009-08-21 17:18:03 +00004915 unixFile *p = (unixFile *)pFile;
4916 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004917 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004918 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004919 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004920 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004921
4922 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4923 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4924 int isCreate = (flags & SQLITE_OPEN_CREATE);
4925 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4926 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004927#if SQLITE_ENABLE_LOCKING_STYLE
4928 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4929#endif
danielk1977b4b47412007-08-17 15:53:36 +00004930
danielk1977fee2d252007-08-18 10:59:19 +00004931 /* If creating a master or main-file journal, this function will open
4932 ** a file-descriptor on the directory too. The first time unixSync()
4933 ** is called the directory file descriptor will be fsync()ed and close()d.
4934 */
drh0059eae2011-08-08 23:48:40 +00004935 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004936 eType==SQLITE_OPEN_MASTER_JOURNAL
4937 || eType==SQLITE_OPEN_MAIN_JOURNAL
4938 || eType==SQLITE_OPEN_WAL
4939 ));
danielk1977fee2d252007-08-18 10:59:19 +00004940
danielk197717b90b52008-06-06 11:11:25 +00004941 /* If argument zPath is a NULL pointer, this function is required to open
4942 ** a temporary file. Use this buffer to store the file name in.
4943 */
4944 char zTmpname[MAX_PATHNAME+1];
4945 const char *zName = zPath;
4946
danielk1977fee2d252007-08-18 10:59:19 +00004947 /* Check the following statements are true:
4948 **
4949 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4950 ** (b) if CREATE is set, then READWRITE must also be set, and
4951 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004952 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004953 */
danielk1977b4b47412007-08-17 15:53:36 +00004954 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004955 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004956 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004957 assert(isDelete==0 || isCreate);
4958
danddb0ac42010-07-14 14:48:58 +00004959 /* The main DB, main journal, WAL file and master journal are never
4960 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004961 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4962 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4963 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004964 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004965
danielk1977fee2d252007-08-18 10:59:19 +00004966 /* Assert that the upper layer has set one of the "file-type" flags. */
4967 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4968 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4969 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004970 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004971 );
4972
dan08da86a2009-08-21 17:18:03 +00004973 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004974
dan08da86a2009-08-21 17:18:03 +00004975 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004976 UnixUnusedFd *pUnused;
4977 pUnused = findReusableFd(zName, flags);
4978 if( pUnused ){
4979 fd = pUnused->fd;
4980 }else{
dan6aa657f2009-08-24 18:57:58 +00004981 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004982 if( !pUnused ){
4983 return SQLITE_NOMEM;
4984 }
4985 }
4986 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004987 }else if( !zName ){
4988 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00004989 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00004990 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004991 if( rc!=SQLITE_OK ){
4992 return rc;
4993 }
4994 zName = zTmpname;
4995 }
4996
dan08da86a2009-08-21 17:18:03 +00004997 /* Determine the value of the flags parameter passed to POSIX function
4998 ** open(). These must be calculated even if open() is not called, as
4999 ** they may be stored as part of the file handle and used by the
5000 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005001 if( isReadonly ) openFlags |= O_RDONLY;
5002 if( isReadWrite ) openFlags |= O_RDWR;
5003 if( isCreate ) openFlags |= O_CREAT;
5004 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5005 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005006
danielk1977b4b47412007-08-17 15:53:36 +00005007 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005008 mode_t openMode; /* Permissions to create file with */
5009 rc = findCreateFileMode(zName, flags, &openMode);
5010 if( rc!=SQLITE_OK ){
5011 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005012 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005013 return rc;
5014 }
drhad4f1e52011-03-04 15:43:57 +00005015 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005016 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005017 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5018 /* Failed to open the file for read/write access. Try read-only. */
5019 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005020 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005021 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005022 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005023 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005024 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005025 }
5026 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005027 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005028 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005029 }
danielk1977b4b47412007-08-17 15:53:36 +00005030 }
dan08da86a2009-08-21 17:18:03 +00005031 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005032 if( pOutFlags ){
5033 *pOutFlags = flags;
5034 }
5035
dane946c392009-08-22 11:39:46 +00005036 if( p->pUnused ){
5037 p->pUnused->fd = fd;
5038 p->pUnused->flags = flags;
5039 }
5040
danielk1977b4b47412007-08-17 15:53:36 +00005041 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005042#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005043 zPath = zName;
5044#else
drh036ac7f2011-08-08 23:18:05 +00005045 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005046#endif
danielk1977b4b47412007-08-17 15:53:36 +00005047 }
drh41022642008-11-21 00:24:42 +00005048#if SQLITE_ENABLE_LOCKING_STYLE
5049 else{
dan08da86a2009-08-21 17:18:03 +00005050 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005051 }
5052#endif
5053
danielk1977e339d652008-06-28 11:23:00 +00005054#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005055 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005056#endif
5057
drhda0e7682008-07-30 15:27:54 +00005058 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005059
drh7ed97b92010-01-20 13:07:21 +00005060
5061#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5062 struct statfs fsInfo;
5063 if( fstatfs(fd, &fsInfo) == -1 ){
5064 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005065 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005066 return SQLITE_IOERR_ACCESS;
5067 }
5068 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5069 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5070 }
5071#endif
5072
5073#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005074#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005075 isAutoProxy = 1;
5076#endif
5077 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005078 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5079 int useProxy = 0;
5080
dan08da86a2009-08-21 17:18:03 +00005081 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5082 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005083 if( envforce!=NULL ){
5084 useProxy = atoi(envforce)>0;
5085 }else{
5086 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005087 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005088 /* In theory, the close(fd) call is sub-optimal. If the file opened
5089 ** with fd is a database file, and there are other connections open
5090 ** on that file that are currently holding advisory locks on it,
5091 ** then the call to close() will cancel those locks. In practice,
5092 ** we're assuming that statfs() doesn't fail very often. At least
5093 ** not while other file descriptors opened by the same process on
5094 ** the same file are working. */
5095 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005096 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005097 rc = SQLITE_IOERR_ACCESS;
5098 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005099 }
5100 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5101 }
5102 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005103 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005104 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005105 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005106 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005107 if( rc!=SQLITE_OK ){
5108 /* Use unixClose to clean up the resources added in fillInUnixFile
5109 ** and clear all the structure's references. Specifically,
5110 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5111 */
5112 unixClose(pFile);
5113 return rc;
5114 }
aswiftaebf4132008-11-21 00:10:35 +00005115 }
dane946c392009-08-22 11:39:46 +00005116 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005117 }
5118 }
5119#endif
5120
drh0059eae2011-08-08 23:48:40 +00005121 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005122 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005123open_finished:
5124 if( rc!=SQLITE_OK ){
5125 sqlite3_free(p->pUnused);
5126 }
5127 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005128}
5129
dane946c392009-08-22 11:39:46 +00005130
danielk1977b4b47412007-08-17 15:53:36 +00005131/*
danielk1977fee2d252007-08-18 10:59:19 +00005132** Delete the file at zPath. If the dirSync argument is true, fsync()
5133** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005134*/
drh6b9d6dd2008-12-03 19:34:47 +00005135static int unixDelete(
5136 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5137 const char *zPath, /* Name of file to be deleted */
5138 int dirSync /* If true, fsync() directory after deleting file */
5139){
danielk1977fee2d252007-08-18 10:59:19 +00005140 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005141 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005142 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005143 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005144 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005145 }
danielk1977d39fa702008-10-16 13:27:40 +00005146#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005147 if( dirSync ){
5148 int fd;
5149 rc = openDirectory(zPath, &fd);
5150 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005151#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005152 if( fsync(fd)==-1 )
5153#else
5154 if( fsync(fd) )
5155#endif
5156 {
dane18d4952011-02-21 11:46:24 +00005157 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005158 }
drh0e9365c2011-03-02 02:08:13 +00005159 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005160 }
5161 }
danielk1977d138dd82008-10-15 16:02:48 +00005162#endif
danielk1977fee2d252007-08-18 10:59:19 +00005163 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005164}
5165
danielk197790949c22007-08-17 16:50:38 +00005166/*
5167** Test the existance of or access permissions of file zPath. The
5168** test performed depends on the value of flags:
5169**
5170** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5171** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5172** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5173**
5174** Otherwise return 0.
5175*/
danielk1977861f7452008-06-05 11:39:11 +00005176static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005177 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5178 const char *zPath, /* Path of the file to examine */
5179 int flags, /* What do we want to learn about the zPath file? */
5180 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005181){
rse25c0d1a2007-09-20 08:38:14 +00005182 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005183 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005184 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005185 switch( flags ){
5186 case SQLITE_ACCESS_EXISTS:
5187 amode = F_OK;
5188 break;
5189 case SQLITE_ACCESS_READWRITE:
5190 amode = W_OK|R_OK;
5191 break;
drh50d3f902007-08-27 21:10:36 +00005192 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005193 amode = R_OK;
5194 break;
5195
5196 default:
5197 assert(!"Invalid flags argument");
5198 }
drh99ab3b12011-03-02 15:09:07 +00005199 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005200 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5201 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005202 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005203 *pResOut = 0;
5204 }
5205 }
danielk1977861f7452008-06-05 11:39:11 +00005206 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005207}
5208
danielk1977b4b47412007-08-17 15:53:36 +00005209
5210/*
5211** Turn a relative pathname into a full pathname. The relative path
5212** is stored as a nul-terminated string in the buffer pointed to by
5213** zPath.
5214**
5215** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5216** (in this case, MAX_PATHNAME bytes). The full-path is written to
5217** this buffer before returning.
5218*/
danielk1977adfb9b02007-09-17 07:02:56 +00005219static int unixFullPathname(
5220 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5221 const char *zPath, /* Possibly relative input path */
5222 int nOut, /* Size of output buffer in bytes */
5223 char *zOut /* Output buffer */
5224){
danielk1977843e65f2007-09-01 16:16:15 +00005225
5226 /* It's odd to simulate an io-error here, but really this is just
5227 ** using the io-error infrastructure to test that SQLite handles this
5228 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005229 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005230 */
5231 SimulateIOError( return SQLITE_ERROR );
5232
drh153c62c2007-08-24 03:51:33 +00005233 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005234 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005235
drh3c7f2dc2007-12-06 13:26:20 +00005236 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005237 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005238 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005239 }else{
5240 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005241 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005242 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005243 }
drhea678832008-12-10 19:26:22 +00005244 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005245 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005246 }
5247 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005248}
5249
drh0ccebe72005-06-07 22:22:50 +00005250
drh761df872006-12-21 01:29:22 +00005251#ifndef SQLITE_OMIT_LOAD_EXTENSION
5252/*
5253** Interfaces for opening a shared library, finding entry points
5254** within the shared library, and closing the shared library.
5255*/
5256#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005257static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5258 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005259 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5260}
danielk197795c8a542007-09-01 06:51:27 +00005261
5262/*
5263** SQLite calls this function immediately after a call to unixDlSym() or
5264** unixDlOpen() fails (returns a null pointer). If a more detailed error
5265** message is available, it is written to zBufOut. If no error message
5266** is available, zBufOut is left unmodified and SQLite uses a default
5267** error message.
5268*/
danielk1977397d65f2008-11-19 11:35:39 +00005269static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005270 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005271 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005272 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005273 zErr = dlerror();
5274 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005275 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005276 }
drh6c7d5c52008-11-21 20:32:33 +00005277 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005278}
drh1875f7a2008-12-08 18:19:17 +00005279static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5280 /*
5281 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5282 ** cast into a pointer to a function. And yet the library dlsym() routine
5283 ** returns a void* which is really a pointer to a function. So how do we
5284 ** use dlsym() with -pedantic-errors?
5285 **
5286 ** Variable x below is defined to be a pointer to a function taking
5287 ** parameters void* and const char* and returning a pointer to a function.
5288 ** We initialize x by assigning it a pointer to the dlsym() function.
5289 ** (That assignment requires a cast.) Then we call the function that
5290 ** x points to.
5291 **
5292 ** This work-around is unlikely to work correctly on any system where
5293 ** you really cannot cast a function pointer into void*. But then, on the
5294 ** other hand, dlsym() will not work on such a system either, so we have
5295 ** not really lost anything.
5296 */
5297 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005298 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005299 x = (void(*(*)(void*,const char*))(void))dlsym;
5300 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005301}
danielk1977397d65f2008-11-19 11:35:39 +00005302static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5303 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005304 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005305}
danielk1977b4b47412007-08-17 15:53:36 +00005306#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5307 #define unixDlOpen 0
5308 #define unixDlError 0
5309 #define unixDlSym 0
5310 #define unixDlClose 0
5311#endif
5312
5313/*
danielk197790949c22007-08-17 16:50:38 +00005314** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005315*/
danielk1977397d65f2008-11-19 11:35:39 +00005316static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5317 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005318 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005319
drhbbd42a62004-05-22 17:41:58 +00005320 /* We have to initialize zBuf to prevent valgrind from reporting
5321 ** errors. The reports issued by valgrind are incorrect - we would
5322 ** prefer that the randomness be increased by making use of the
5323 ** uninitialized space in zBuf - but valgrind errors tend to worry
5324 ** some users. Rather than argue, it seems easier just to initialize
5325 ** the whole array and silence valgrind, even if that means less randomness
5326 ** in the random seed.
5327 **
5328 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005329 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005330 ** tests repeatable.
5331 */
danielk1977b4b47412007-08-17 15:53:36 +00005332 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005333#if !defined(SQLITE_TEST)
5334 {
drh842b8642005-01-21 17:53:17 +00005335 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005336 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005337 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005338 time_t t;
5339 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005340 memcpy(zBuf, &t, sizeof(t));
5341 pid = getpid();
5342 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005343 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005344 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005345 }else{
drhe562be52011-03-02 18:01:10 +00005346 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005347 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005348 }
drhbbd42a62004-05-22 17:41:58 +00005349 }
5350#endif
drh72cbd072008-10-14 17:58:38 +00005351 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005352}
5353
danielk1977b4b47412007-08-17 15:53:36 +00005354
drhbbd42a62004-05-22 17:41:58 +00005355/*
5356** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005357** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005358** The return value is the number of microseconds of sleep actually
5359** requested from the underlying operating system, a number which
5360** might be greater than or equal to the argument, but not less
5361** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005362*/
danielk1977397d65f2008-11-19 11:35:39 +00005363static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005364#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005365 struct timespec sp;
5366
5367 sp.tv_sec = microseconds / 1000000;
5368 sp.tv_nsec = (microseconds % 1000000) * 1000;
5369 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005370 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005371 return microseconds;
5372#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005373 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005374 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005375 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005376#else
danielk1977b4b47412007-08-17 15:53:36 +00005377 int seconds = (microseconds+999999)/1000000;
5378 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005379 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005380 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005381#endif
drh88f474a2006-01-02 20:00:12 +00005382}
5383
5384/*
drh6b9d6dd2008-12-03 19:34:47 +00005385** The following variable, if set to a non-zero value, is interpreted as
5386** the number of seconds since 1970 and is used to set the result of
5387** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005388*/
5389#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005390int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005391#endif
5392
5393/*
drhb7e8ea22010-05-03 14:32:30 +00005394** Find the current time (in Universal Coordinated Time). Write into *piNow
5395** the current time and date as a Julian Day number times 86_400_000. In
5396** other words, write into *piNow the number of milliseconds since the Julian
5397** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5398** proleptic Gregorian calendar.
5399**
5400** On success, return 0. Return 1 if the time and date cannot be found.
5401*/
5402static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5403 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5404#if defined(NO_GETTOD)
5405 time_t t;
5406 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005407 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005408#elif OS_VXWORKS
5409 struct timespec sNow;
5410 clock_gettime(CLOCK_REALTIME, &sNow);
5411 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5412#else
5413 struct timeval sNow;
5414 gettimeofday(&sNow, 0);
5415 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5416#endif
5417
5418#ifdef SQLITE_TEST
5419 if( sqlite3_current_time ){
5420 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5421 }
5422#endif
5423 UNUSED_PARAMETER(NotUsed);
5424 return 0;
5425}
5426
5427/*
drhbbd42a62004-05-22 17:41:58 +00005428** Find the current time (in Universal Coordinated Time). Write the
5429** current time and date as a Julian Day number into *prNow and
5430** return 0. Return 1 if the time and date cannot be found.
5431*/
danielk1977397d65f2008-11-19 11:35:39 +00005432static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005433 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005434 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005435 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005436 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005437 return 0;
5438}
danielk1977b4b47412007-08-17 15:53:36 +00005439
drh6b9d6dd2008-12-03 19:34:47 +00005440/*
5441** We added the xGetLastError() method with the intention of providing
5442** better low-level error messages when operating-system problems come up
5443** during SQLite operation. But so far, none of that has been implemented
5444** in the core. So this routine is never called. For now, it is merely
5445** a place-holder.
5446*/
danielk1977397d65f2008-11-19 11:35:39 +00005447static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5448 UNUSED_PARAMETER(NotUsed);
5449 UNUSED_PARAMETER(NotUsed2);
5450 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005451 return 0;
5452}
5453
drhf2424c52010-04-26 00:04:55 +00005454
5455/*
drh734c9862008-11-28 15:37:20 +00005456************************ End of sqlite3_vfs methods ***************************
5457******************************************************************************/
5458
drh715ff302008-12-03 22:32:44 +00005459/******************************************************************************
5460************************** Begin Proxy Locking ********************************
5461**
5462** Proxy locking is a "uber-locking-method" in this sense: It uses the
5463** other locking methods on secondary lock files. Proxy locking is a
5464** meta-layer over top of the primitive locking implemented above. For
5465** this reason, the division that implements of proxy locking is deferred
5466** until late in the file (here) after all of the other I/O methods have
5467** been defined - so that the primitive locking methods are available
5468** as services to help with the implementation of proxy locking.
5469**
5470****
5471**
5472** The default locking schemes in SQLite use byte-range locks on the
5473** database file to coordinate safe, concurrent access by multiple readers
5474** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5475** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5476** as POSIX read & write locks over fixed set of locations (via fsctl),
5477** on AFP and SMB only exclusive byte-range locks are available via fsctl
5478** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5479** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5480** address in the shared range is taken for a SHARED lock, the entire
5481** shared range is taken for an EXCLUSIVE lock):
5482**
5483** PENDING_BYTE 0x40000000
5484** RESERVED_BYTE 0x40000001
5485** SHARED_RANGE 0x40000002 -> 0x40000200
5486**
5487** This works well on the local file system, but shows a nearly 100x
5488** slowdown in read performance on AFP because the AFP client disables
5489** the read cache when byte-range locks are present. Enabling the read
5490** cache exposes a cache coherency problem that is present on all OS X
5491** supported network file systems. NFS and AFP both observe the
5492** close-to-open semantics for ensuring cache coherency
5493** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5494** address the requirements for concurrent database access by multiple
5495** readers and writers
5496** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5497**
5498** To address the performance and cache coherency issues, proxy file locking
5499** changes the way database access is controlled by limiting access to a
5500** single host at a time and moving file locks off of the database file
5501** and onto a proxy file on the local file system.
5502**
5503**
5504** Using proxy locks
5505** -----------------
5506**
5507** C APIs
5508**
5509** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5510** <proxy_path> | ":auto:");
5511** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5512**
5513**
5514** SQL pragmas
5515**
5516** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5517** PRAGMA [database.]lock_proxy_file
5518**
5519** Specifying ":auto:" means that if there is a conch file with a matching
5520** host ID in it, the proxy path in the conch file will be used, otherwise
5521** a proxy path based on the user's temp dir
5522** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5523** actual proxy file name is generated from the name and path of the
5524** database file. For example:
5525**
5526** For database path "/Users/me/foo.db"
5527** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5528**
5529** Once a lock proxy is configured for a database connection, it can not
5530** be removed, however it may be switched to a different proxy path via
5531** the above APIs (assuming the conch file is not being held by another
5532** connection or process).
5533**
5534**
5535** How proxy locking works
5536** -----------------------
5537**
5538** Proxy file locking relies primarily on two new supporting files:
5539**
5540** * conch file to limit access to the database file to a single host
5541** at a time
5542**
5543** * proxy file to act as a proxy for the advisory locks normally
5544** taken on the database
5545**
5546** The conch file - to use a proxy file, sqlite must first "hold the conch"
5547** by taking an sqlite-style shared lock on the conch file, reading the
5548** contents and comparing the host's unique host ID (see below) and lock
5549** proxy path against the values stored in the conch. The conch file is
5550** stored in the same directory as the database file and the file name
5551** is patterned after the database file name as ".<databasename>-conch".
5552** If the conch file does not exist, or it's contents do not match the
5553** host ID and/or proxy path, then the lock is escalated to an exclusive
5554** lock and the conch file contents is updated with the host ID and proxy
5555** path and the lock is downgraded to a shared lock again. If the conch
5556** is held by another process (with a shared lock), the exclusive lock
5557** will fail and SQLITE_BUSY is returned.
5558**
5559** The proxy file - a single-byte file used for all advisory file locks
5560** normally taken on the database file. This allows for safe sharing
5561** of the database file for multiple readers and writers on the same
5562** host (the conch ensures that they all use the same local lock file).
5563**
drh715ff302008-12-03 22:32:44 +00005564** Requesting the lock proxy does not immediately take the conch, it is
5565** only taken when the first request to lock database file is made.
5566** This matches the semantics of the traditional locking behavior, where
5567** opening a connection to a database file does not take a lock on it.
5568** The shared lock and an open file descriptor are maintained until
5569** the connection to the database is closed.
5570**
5571** The proxy file and the lock file are never deleted so they only need
5572** to be created the first time they are used.
5573**
5574** Configuration options
5575** ---------------------
5576**
5577** SQLITE_PREFER_PROXY_LOCKING
5578**
5579** Database files accessed on non-local file systems are
5580** automatically configured for proxy locking, lock files are
5581** named automatically using the same logic as
5582** PRAGMA lock_proxy_file=":auto:"
5583**
5584** SQLITE_PROXY_DEBUG
5585**
5586** Enables the logging of error messages during host id file
5587** retrieval and creation
5588**
drh715ff302008-12-03 22:32:44 +00005589** LOCKPROXYDIR
5590**
5591** Overrides the default directory used for lock proxy files that
5592** are named automatically via the ":auto:" setting
5593**
5594** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5595**
5596** Permissions to use when creating a directory for storing the
5597** lock proxy files, only used when LOCKPROXYDIR is not set.
5598**
5599**
5600** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5601** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5602** force proxy locking to be used for every database file opened, and 0
5603** will force automatic proxy locking to be disabled for all database
5604** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5605** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5606*/
5607
5608/*
5609** Proxy locking is only available on MacOSX
5610*/
drhd2cb50b2009-01-09 21:41:17 +00005611#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005612
drh715ff302008-12-03 22:32:44 +00005613/*
5614** The proxyLockingContext has the path and file structures for the remote
5615** and local proxy files in it
5616*/
5617typedef struct proxyLockingContext proxyLockingContext;
5618struct proxyLockingContext {
5619 unixFile *conchFile; /* Open conch file */
5620 char *conchFilePath; /* Name of the conch file */
5621 unixFile *lockProxy; /* Open proxy lock file */
5622 char *lockProxyPath; /* Name of the proxy lock file */
5623 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005624 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005625 void *oldLockingContext; /* Original lockingcontext to restore on close */
5626 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5627};
5628
drh7ed97b92010-01-20 13:07:21 +00005629/*
5630** The proxy lock file path for the database at dbPath is written into lPath,
5631** which must point to valid, writable memory large enough for a maxLen length
5632** file path.
drh715ff302008-12-03 22:32:44 +00005633*/
drh715ff302008-12-03 22:32:44 +00005634static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5635 int len;
5636 int dbLen;
5637 int i;
5638
5639#ifdef LOCKPROXYDIR
5640 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5641#else
5642# ifdef _CS_DARWIN_USER_TEMP_DIR
5643 {
drh7ed97b92010-01-20 13:07:21 +00005644 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005645 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5646 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005647 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005648 }
drh7ed97b92010-01-20 13:07:21 +00005649 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005650 }
5651# else
5652 len = strlcpy(lPath, "/tmp/", maxLen);
5653# endif
5654#endif
5655
5656 if( lPath[len-1]!='/' ){
5657 len = strlcat(lPath, "/", maxLen);
5658 }
5659
5660 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005661 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005662 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005663 char c = dbPath[i];
5664 lPath[i+len] = (c=='/')?'_':c;
5665 }
5666 lPath[i+len]='\0';
5667 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005668 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005669 return SQLITE_OK;
5670}
5671
drh7ed97b92010-01-20 13:07:21 +00005672/*
5673 ** Creates the lock file and any missing directories in lockPath
5674 */
5675static int proxyCreateLockPath(const char *lockPath){
5676 int i, len;
5677 char buf[MAXPATHLEN];
5678 int start = 0;
5679
5680 assert(lockPath!=NULL);
5681 /* try to create all the intermediate directories */
5682 len = (int)strlen(lockPath);
5683 buf[0] = lockPath[0];
5684 for( i=1; i<len; i++ ){
5685 if( lockPath[i] == '/' && (i - start > 0) ){
5686 /* only mkdir if leaf dir != "." or "/" or ".." */
5687 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5688 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5689 buf[i]='\0';
5690 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5691 int err=errno;
5692 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005693 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005694 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005695 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005696 return err;
5697 }
5698 }
5699 }
5700 start=i+1;
5701 }
5702 buf[i] = lockPath[i];
5703 }
drh308c2a52010-05-14 11:30:18 +00005704 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005705 return 0;
5706}
5707
drh715ff302008-12-03 22:32:44 +00005708/*
5709** Create a new VFS file descriptor (stored in memory obtained from
5710** sqlite3_malloc) and open the file named "path" in the file descriptor.
5711**
5712** The caller is responsible not only for closing the file descriptor
5713** but also for freeing the memory associated with the file descriptor.
5714*/
drh7ed97b92010-01-20 13:07:21 +00005715static int proxyCreateUnixFile(
5716 const char *path, /* path for the new unixFile */
5717 unixFile **ppFile, /* unixFile created and returned by ref */
5718 int islockfile /* if non zero missing dirs will be created */
5719) {
5720 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005721 unixFile *pNew;
5722 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005723 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005724 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005725 int terrno = 0;
5726 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005727
drh7ed97b92010-01-20 13:07:21 +00005728 /* 1. first try to open/create the file
5729 ** 2. if that fails, and this is a lock file (not-conch), try creating
5730 ** the parent directories and then try again.
5731 ** 3. if that fails, try to open the file read-only
5732 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5733 */
5734 pUnused = findReusableFd(path, openFlags);
5735 if( pUnused ){
5736 fd = pUnused->fd;
5737 }else{
5738 pUnused = sqlite3_malloc(sizeof(*pUnused));
5739 if( !pUnused ){
5740 return SQLITE_NOMEM;
5741 }
5742 }
5743 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005744 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005745 terrno = errno;
5746 if( fd<0 && errno==ENOENT && islockfile ){
5747 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005748 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005749 }
5750 }
5751 }
5752 if( fd<0 ){
5753 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005754 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005755 terrno = errno;
5756 }
5757 if( fd<0 ){
5758 if( islockfile ){
5759 return SQLITE_BUSY;
5760 }
5761 switch (terrno) {
5762 case EACCES:
5763 return SQLITE_PERM;
5764 case EIO:
5765 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5766 default:
drh9978c972010-02-23 17:36:32 +00005767 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005768 }
5769 }
5770
5771 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5772 if( pNew==NULL ){
5773 rc = SQLITE_NOMEM;
5774 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005775 }
5776 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005777 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005778 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005779 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005780 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005781 pUnused->fd = fd;
5782 pUnused->flags = openFlags;
5783 pNew->pUnused = pUnused;
5784
drh0059eae2011-08-08 23:48:40 +00005785 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005786 if( rc==SQLITE_OK ){
5787 *ppFile = pNew;
5788 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005789 }
drh7ed97b92010-01-20 13:07:21 +00005790end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005791 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005792 sqlite3_free(pNew);
5793 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005794 return rc;
5795}
5796
drh7ed97b92010-01-20 13:07:21 +00005797#ifdef SQLITE_TEST
5798/* simulate multiple hosts by creating unique hostid file paths */
5799int sqlite3_hostid_num = 0;
5800#endif
5801
5802#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5803
drh0ab216a2010-07-02 17:10:40 +00005804/* Not always defined in the headers as it ought to be */
5805extern int gethostuuid(uuid_t id, const struct timespec *wait);
5806
drh7ed97b92010-01-20 13:07:21 +00005807/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5808** bytes of writable memory.
5809*/
5810static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005811 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5812 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005813#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5814 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005815 {
5816 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5817 if( gethostuuid(pHostID, &timeout) ){
5818 int err = errno;
5819 if( pError ){
5820 *pError = err;
5821 }
5822 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005823 }
drh7ed97b92010-01-20 13:07:21 +00005824 }
drhe8b0c9b2010-09-25 14:13:17 +00005825#endif
drh7ed97b92010-01-20 13:07:21 +00005826#ifdef SQLITE_TEST
5827 /* simulate multiple hosts by creating unique hostid file paths */
5828 if( sqlite3_hostid_num != 0){
5829 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5830 }
5831#endif
5832
5833 return SQLITE_OK;
5834}
5835
5836/* The conch file contains the header, host id and lock file path
5837 */
5838#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5839#define PROXY_HEADERLEN 1 /* conch file header length */
5840#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5841#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5842
5843/*
5844** Takes an open conch file, copies the contents to a new path and then moves
5845** it back. The newly created file's file descriptor is assigned to the
5846** conch file structure and finally the original conch file descriptor is
5847** closed. Returns zero if successful.
5848*/
5849static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5850 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5851 unixFile *conchFile = pCtx->conchFile;
5852 char tPath[MAXPATHLEN];
5853 char buf[PROXY_MAXCONCHLEN];
5854 char *cPath = pCtx->conchFilePath;
5855 size_t readLen = 0;
5856 size_t pathLen = 0;
5857 char errmsg[64] = "";
5858 int fd = -1;
5859 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005860 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005861
5862 /* create a new path by replace the trailing '-conch' with '-break' */
5863 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5864 if( pathLen>MAXPATHLEN || pathLen<6 ||
5865 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005866 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005867 goto end_breaklock;
5868 }
5869 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005870 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005871 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005872 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005873 goto end_breaklock;
5874 }
5875 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005876 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5877 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005878 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005879 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005880 goto end_breaklock;
5881 }
drhe562be52011-03-02 18:01:10 +00005882 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005883 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005884 goto end_breaklock;
5885 }
5886 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005887 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005888 goto end_breaklock;
5889 }
5890 rc = 0;
5891 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005892 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005893 conchFile->h = fd;
5894 conchFile->openFlags = O_RDWR | O_CREAT;
5895
5896end_breaklock:
5897 if( rc ){
5898 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005899 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005900 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005901 }
5902 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5903 }
5904 return rc;
5905}
5906
5907/* Take the requested lock on the conch file and break a stale lock if the
5908** host id matches.
5909*/
5910static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5911 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5912 unixFile *conchFile = pCtx->conchFile;
5913 int rc = SQLITE_OK;
5914 int nTries = 0;
5915 struct timespec conchModTime;
5916
5917 do {
5918 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5919 nTries ++;
5920 if( rc==SQLITE_BUSY ){
5921 /* If the lock failed (busy):
5922 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5923 * 2nd try: fail if the mod time changed or host id is different, wait
5924 * 10 sec and try again
5925 * 3rd try: break the lock unless the mod time has changed.
5926 */
5927 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005928 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005929 pFile->lastErrno = errno;
5930 return SQLITE_IOERR_LOCK;
5931 }
5932
5933 if( nTries==1 ){
5934 conchModTime = buf.st_mtimespec;
5935 usleep(500000); /* wait 0.5 sec and try the lock again*/
5936 continue;
5937 }
5938
5939 assert( nTries>1 );
5940 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5941 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5942 return SQLITE_BUSY;
5943 }
5944
5945 if( nTries==2 ){
5946 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005947 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005948 if( len<0 ){
5949 pFile->lastErrno = errno;
5950 return SQLITE_IOERR_LOCK;
5951 }
5952 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5953 /* don't break the lock if the host id doesn't match */
5954 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5955 return SQLITE_BUSY;
5956 }
5957 }else{
5958 /* don't break the lock on short read or a version mismatch */
5959 return SQLITE_BUSY;
5960 }
5961 usleep(10000000); /* wait 10 sec and try the lock again */
5962 continue;
5963 }
5964
5965 assert( nTries==3 );
5966 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5967 rc = SQLITE_OK;
5968 if( lockType==EXCLUSIVE_LOCK ){
5969 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5970 }
5971 if( !rc ){
5972 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5973 }
5974 }
5975 }
5976 } while( rc==SQLITE_BUSY && nTries<3 );
5977
5978 return rc;
5979}
5980
5981/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005982** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5983** lockPath means that the lockPath in the conch file will be used if the
5984** host IDs match, or a new lock path will be generated automatically
5985** and written to the conch file.
5986*/
5987static int proxyTakeConch(unixFile *pFile){
5988 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5989
drh7ed97b92010-01-20 13:07:21 +00005990 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005991 return SQLITE_OK;
5992 }else{
5993 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005994 uuid_t myHostID;
5995 int pError = 0;
5996 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005997 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005998 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005999 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006000 int createConch = 0;
6001 int hostIdMatch = 0;
6002 int readLen = 0;
6003 int tryOldLockPath = 0;
6004 int forceNewLockPath = 0;
6005
drh308c2a52010-05-14 11:30:18 +00006006 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6007 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006008
drh7ed97b92010-01-20 13:07:21 +00006009 rc = proxyGetHostID(myHostID, &pError);
6010 if( (rc&0xff)==SQLITE_IOERR ){
6011 pFile->lastErrno = pError;
6012 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006013 }
drh7ed97b92010-01-20 13:07:21 +00006014 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006015 if( rc!=SQLITE_OK ){
6016 goto end_takeconch;
6017 }
drh7ed97b92010-01-20 13:07:21 +00006018 /* read the existing conch file */
6019 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6020 if( readLen<0 ){
6021 /* I/O error: lastErrno set by seekAndRead */
6022 pFile->lastErrno = conchFile->lastErrno;
6023 rc = SQLITE_IOERR_READ;
6024 goto end_takeconch;
6025 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6026 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6027 /* a short read or version format mismatch means we need to create a new
6028 ** conch file.
6029 */
6030 createConch = 1;
6031 }
6032 /* if the host id matches and the lock path already exists in the conch
6033 ** we'll try to use the path there, if we can't open that path, we'll
6034 ** retry with a new auto-generated path
6035 */
6036 do { /* in case we need to try again for an :auto: named lock file */
6037
6038 if( !createConch && !forceNewLockPath ){
6039 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6040 PROXY_HOSTIDLEN);
6041 /* if the conch has data compare the contents */
6042 if( !pCtx->lockProxyPath ){
6043 /* for auto-named local lock file, just check the host ID and we'll
6044 ** use the local lock file path that's already in there
6045 */
6046 if( hostIdMatch ){
6047 size_t pathLen = (readLen - PROXY_PATHINDEX);
6048
6049 if( pathLen>=MAXPATHLEN ){
6050 pathLen=MAXPATHLEN-1;
6051 }
6052 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6053 lockPath[pathLen] = 0;
6054 tempLockPath = lockPath;
6055 tryOldLockPath = 1;
6056 /* create a copy of the lock path if the conch is taken */
6057 goto end_takeconch;
6058 }
6059 }else if( hostIdMatch
6060 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6061 readLen-PROXY_PATHINDEX)
6062 ){
6063 /* conch host and lock path match */
6064 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006065 }
drh7ed97b92010-01-20 13:07:21 +00006066 }
6067
6068 /* if the conch isn't writable and doesn't match, we can't take it */
6069 if( (conchFile->openFlags&O_RDWR) == 0 ){
6070 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006071 goto end_takeconch;
6072 }
drh7ed97b92010-01-20 13:07:21 +00006073
6074 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006075 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006076 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6077 tempLockPath = lockPath;
6078 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006079 }
drh7ed97b92010-01-20 13:07:21 +00006080
6081 /* update conch with host and path (this will fail if other process
6082 ** has a shared lock already), if the host id matches, use the big
6083 ** stick.
drh715ff302008-12-03 22:32:44 +00006084 */
drh7ed97b92010-01-20 13:07:21 +00006085 futimes(conchFile->h, NULL);
6086 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006087 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006088 /* We are trying for an exclusive lock but another thread in this
6089 ** same process is still holding a shared lock. */
6090 rc = SQLITE_BUSY;
6091 } else {
6092 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006093 }
drh715ff302008-12-03 22:32:44 +00006094 }else{
drh7ed97b92010-01-20 13:07:21 +00006095 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006096 }
drh7ed97b92010-01-20 13:07:21 +00006097 if( rc==SQLITE_OK ){
6098 char writeBuffer[PROXY_MAXCONCHLEN];
6099 int writeSize = 0;
6100
6101 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6102 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6103 if( pCtx->lockProxyPath!=NULL ){
6104 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6105 }else{
6106 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6107 }
6108 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006109 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006110 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6111 fsync(conchFile->h);
6112 /* If we created a new conch file (not just updated the contents of a
6113 ** valid conch file), try to match the permissions of the database
6114 */
6115 if( rc==SQLITE_OK && createConch ){
6116 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006117 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006118 if( err==0 ){
6119 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6120 S_IROTH|S_IWOTH);
6121 /* try to match the database file R/W permissions, ignore failure */
6122#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006123 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006124#else
drhff812312011-02-23 13:33:46 +00006125 do{
drhe562be52011-03-02 18:01:10 +00006126 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006127 }while( rc==(-1) && errno==EINTR );
6128 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006129 int code = errno;
6130 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6131 cmode, code, strerror(code));
6132 } else {
6133 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6134 }
6135 }else{
6136 int code = errno;
6137 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6138 err, code, strerror(code));
6139#endif
6140 }
drh715ff302008-12-03 22:32:44 +00006141 }
6142 }
drh7ed97b92010-01-20 13:07:21 +00006143 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6144
6145 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006146 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006147 if( rc==SQLITE_OK && pFile->openFlags ){
6148 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006149 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006150 }
6151 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006152 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006153 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006154 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006155 if( fd>=0 ){
6156 pFile->h = fd;
6157 }else{
drh9978c972010-02-23 17:36:32 +00006158 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006159 during locking */
6160 }
6161 }
6162 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6163 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6164 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6165 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6166 /* we couldn't create the proxy lock file with the old lock file path
6167 ** so try again via auto-naming
6168 */
6169 forceNewLockPath = 1;
6170 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006171 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006172 }
6173 }
6174 if( rc==SQLITE_OK ){
6175 /* Need to make a copy of path if we extracted the value
6176 ** from the conch file or the path was allocated on the stack
6177 */
6178 if( tempLockPath ){
6179 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6180 if( !pCtx->lockProxyPath ){
6181 rc = SQLITE_NOMEM;
6182 }
6183 }
6184 }
6185 if( rc==SQLITE_OK ){
6186 pCtx->conchHeld = 1;
6187
6188 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6189 afpLockingContext *afpCtx;
6190 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6191 afpCtx->dbPath = pCtx->lockProxyPath;
6192 }
6193 } else {
6194 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6195 }
drh308c2a52010-05-14 11:30:18 +00006196 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6197 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006198 return rc;
drh308c2a52010-05-14 11:30:18 +00006199 } while (1); /* in case we need to retry the :auto: lock file -
6200 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006201 }
6202}
6203
6204/*
6205** If pFile holds a lock on a conch file, then release that lock.
6206*/
6207static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006208 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006209 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6210 unixFile *conchFile; /* Name of the conch file */
6211
6212 pCtx = (proxyLockingContext *)pFile->lockingContext;
6213 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006214 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006215 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006216 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006217 if( pCtx->conchHeld>0 ){
6218 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6219 }
drh715ff302008-12-03 22:32:44 +00006220 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006221 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6222 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006223 return rc;
6224}
6225
6226/*
6227** Given the name of a database file, compute the name of its conch file.
6228** Store the conch filename in memory obtained from sqlite3_malloc().
6229** Make *pConchPath point to the new name. Return SQLITE_OK on success
6230** or SQLITE_NOMEM if unable to obtain memory.
6231**
6232** The caller is responsible for ensuring that the allocated memory
6233** space is eventually freed.
6234**
6235** *pConchPath is set to NULL if a memory allocation error occurs.
6236*/
6237static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6238 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006239 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006240 char *conchPath; /* buffer in which to construct conch name */
6241
6242 /* Allocate space for the conch filename and initialize the name to
6243 ** the name of the original database file. */
6244 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6245 if( conchPath==0 ){
6246 return SQLITE_NOMEM;
6247 }
6248 memcpy(conchPath, dbPath, len+1);
6249
6250 /* now insert a "." before the last / character */
6251 for( i=(len-1); i>=0; i-- ){
6252 if( conchPath[i]=='/' ){
6253 i++;
6254 break;
6255 }
6256 }
6257 conchPath[i]='.';
6258 while ( i<len ){
6259 conchPath[i+1]=dbPath[i];
6260 i++;
6261 }
6262
6263 /* append the "-conch" suffix to the file */
6264 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006265 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006266
6267 return SQLITE_OK;
6268}
6269
6270
6271/* Takes a fully configured proxy locking-style unix file and switches
6272** the local lock file path
6273*/
6274static int switchLockProxyPath(unixFile *pFile, const char *path) {
6275 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6276 char *oldPath = pCtx->lockProxyPath;
6277 int rc = SQLITE_OK;
6278
drh308c2a52010-05-14 11:30:18 +00006279 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006280 return SQLITE_BUSY;
6281 }
6282
6283 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6284 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6285 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6286 return SQLITE_OK;
6287 }else{
6288 unixFile *lockProxy = pCtx->lockProxy;
6289 pCtx->lockProxy=NULL;
6290 pCtx->conchHeld = 0;
6291 if( lockProxy!=NULL ){
6292 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6293 if( rc ) return rc;
6294 sqlite3_free(lockProxy);
6295 }
6296 sqlite3_free(oldPath);
6297 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6298 }
6299
6300 return rc;
6301}
6302
6303/*
6304** pFile is a file that has been opened by a prior xOpen call. dbPath
6305** is a string buffer at least MAXPATHLEN+1 characters in size.
6306**
6307** This routine find the filename associated with pFile and writes it
6308** int dbPath.
6309*/
6310static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006311#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006312 if( pFile->pMethod == &afpIoMethods ){
6313 /* afp style keeps a reference to the db path in the filePath field
6314 ** of the struct */
drhea678832008-12-10 19:26:22 +00006315 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006316 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6317 } else
drh715ff302008-12-03 22:32:44 +00006318#endif
6319 if( pFile->pMethod == &dotlockIoMethods ){
6320 /* dot lock style uses the locking context to store the dot lock
6321 ** file path */
6322 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6323 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6324 }else{
6325 /* all other styles use the locking context to store the db file path */
6326 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006327 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006328 }
6329 return SQLITE_OK;
6330}
6331
6332/*
6333** Takes an already filled in unix file and alters it so all file locking
6334** will be performed on the local proxy lock file. The following fields
6335** are preserved in the locking context so that they can be restored and
6336** the unix structure properly cleaned up at close time:
6337** ->lockingContext
6338** ->pMethod
6339*/
6340static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6341 proxyLockingContext *pCtx;
6342 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6343 char *lockPath=NULL;
6344 int rc = SQLITE_OK;
6345
drh308c2a52010-05-14 11:30:18 +00006346 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006347 return SQLITE_BUSY;
6348 }
6349 proxyGetDbPathForUnixFile(pFile, dbPath);
6350 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6351 lockPath=NULL;
6352 }else{
6353 lockPath=(char *)path;
6354 }
6355
drh308c2a52010-05-14 11:30:18 +00006356 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6357 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006358
6359 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6360 if( pCtx==0 ){
6361 return SQLITE_NOMEM;
6362 }
6363 memset(pCtx, 0, sizeof(*pCtx));
6364
6365 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6366 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006367 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6368 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6369 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6370 ** (c) the file system is read-only, then enable no-locking access.
6371 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6372 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6373 */
6374 struct statfs fsInfo;
6375 struct stat conchInfo;
6376 int goLockless = 0;
6377
drh99ab3b12011-03-02 15:09:07 +00006378 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006379 int err = errno;
6380 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6381 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6382 }
6383 }
6384 if( goLockless ){
6385 pCtx->conchHeld = -1; /* read only FS/ lockless */
6386 rc = SQLITE_OK;
6387 }
6388 }
drh715ff302008-12-03 22:32:44 +00006389 }
6390 if( rc==SQLITE_OK && lockPath ){
6391 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6392 }
6393
6394 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006395 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6396 if( pCtx->dbPath==NULL ){
6397 rc = SQLITE_NOMEM;
6398 }
6399 }
6400 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006401 /* all memory is allocated, proxys are created and assigned,
6402 ** switch the locking context and pMethod then return.
6403 */
drh715ff302008-12-03 22:32:44 +00006404 pCtx->oldLockingContext = pFile->lockingContext;
6405 pFile->lockingContext = pCtx;
6406 pCtx->pOldMethod = pFile->pMethod;
6407 pFile->pMethod = &proxyIoMethods;
6408 }else{
6409 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006410 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006411 sqlite3_free(pCtx->conchFile);
6412 }
drhd56b1212010-08-11 06:14:15 +00006413 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006414 sqlite3_free(pCtx->conchFilePath);
6415 sqlite3_free(pCtx);
6416 }
drh308c2a52010-05-14 11:30:18 +00006417 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6418 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006419 return rc;
6420}
6421
6422
6423/*
6424** This routine handles sqlite3_file_control() calls that are specific
6425** to proxy locking.
6426*/
6427static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6428 switch( op ){
6429 case SQLITE_GET_LOCKPROXYFILE: {
6430 unixFile *pFile = (unixFile*)id;
6431 if( pFile->pMethod == &proxyIoMethods ){
6432 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6433 proxyTakeConch(pFile);
6434 if( pCtx->lockProxyPath ){
6435 *(const char **)pArg = pCtx->lockProxyPath;
6436 }else{
6437 *(const char **)pArg = ":auto: (not held)";
6438 }
6439 } else {
6440 *(const char **)pArg = NULL;
6441 }
6442 return SQLITE_OK;
6443 }
6444 case SQLITE_SET_LOCKPROXYFILE: {
6445 unixFile *pFile = (unixFile*)id;
6446 int rc = SQLITE_OK;
6447 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6448 if( pArg==NULL || (const char *)pArg==0 ){
6449 if( isProxyStyle ){
6450 /* turn off proxy locking - not supported */
6451 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6452 }else{
6453 /* turn off proxy locking - already off - NOOP */
6454 rc = SQLITE_OK;
6455 }
6456 }else{
6457 const char *proxyPath = (const char *)pArg;
6458 if( isProxyStyle ){
6459 proxyLockingContext *pCtx =
6460 (proxyLockingContext*)pFile->lockingContext;
6461 if( !strcmp(pArg, ":auto:")
6462 || (pCtx->lockProxyPath &&
6463 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6464 ){
6465 rc = SQLITE_OK;
6466 }else{
6467 rc = switchLockProxyPath(pFile, proxyPath);
6468 }
6469 }else{
6470 /* turn on proxy file locking */
6471 rc = proxyTransformUnixFile(pFile, proxyPath);
6472 }
6473 }
6474 return rc;
6475 }
6476 default: {
6477 assert( 0 ); /* The call assures that only valid opcodes are sent */
6478 }
6479 }
6480 /*NOTREACHED*/
6481 return SQLITE_ERROR;
6482}
6483
6484/*
6485** Within this division (the proxying locking implementation) the procedures
6486** above this point are all utilities. The lock-related methods of the
6487** proxy-locking sqlite3_io_method object follow.
6488*/
6489
6490
6491/*
6492** This routine checks if there is a RESERVED lock held on the specified
6493** file by this or any other process. If such a lock is held, set *pResOut
6494** to a non-zero value otherwise *pResOut is set to zero. The return value
6495** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6496*/
6497static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6498 unixFile *pFile = (unixFile*)id;
6499 int rc = proxyTakeConch(pFile);
6500 if( rc==SQLITE_OK ){
6501 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006502 if( pCtx->conchHeld>0 ){
6503 unixFile *proxy = pCtx->lockProxy;
6504 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6505 }else{ /* conchHeld < 0 is lockless */
6506 pResOut=0;
6507 }
drh715ff302008-12-03 22:32:44 +00006508 }
6509 return rc;
6510}
6511
6512/*
drh308c2a52010-05-14 11:30:18 +00006513** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006514** of the following:
6515**
6516** (1) SHARED_LOCK
6517** (2) RESERVED_LOCK
6518** (3) PENDING_LOCK
6519** (4) EXCLUSIVE_LOCK
6520**
6521** Sometimes when requesting one lock state, additional lock states
6522** are inserted in between. The locking might fail on one of the later
6523** transitions leaving the lock state different from what it started but
6524** still short of its goal. The following chart shows the allowed
6525** transitions and the inserted intermediate states:
6526**
6527** UNLOCKED -> SHARED
6528** SHARED -> RESERVED
6529** SHARED -> (PENDING) -> EXCLUSIVE
6530** RESERVED -> (PENDING) -> EXCLUSIVE
6531** PENDING -> EXCLUSIVE
6532**
6533** This routine will only increase a lock. Use the sqlite3OsUnlock()
6534** routine to lower a locking level.
6535*/
drh308c2a52010-05-14 11:30:18 +00006536static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006537 unixFile *pFile = (unixFile*)id;
6538 int rc = proxyTakeConch(pFile);
6539 if( rc==SQLITE_OK ){
6540 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006541 if( pCtx->conchHeld>0 ){
6542 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006543 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6544 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006545 }else{
6546 /* conchHeld < 0 is lockless */
6547 }
drh715ff302008-12-03 22:32:44 +00006548 }
6549 return rc;
6550}
6551
6552
6553/*
drh308c2a52010-05-14 11:30:18 +00006554** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006555** must be either NO_LOCK or SHARED_LOCK.
6556**
6557** If the locking level of the file descriptor is already at or below
6558** the requested locking level, this routine is a no-op.
6559*/
drh308c2a52010-05-14 11:30:18 +00006560static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006561 unixFile *pFile = (unixFile*)id;
6562 int rc = proxyTakeConch(pFile);
6563 if( rc==SQLITE_OK ){
6564 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006565 if( pCtx->conchHeld>0 ){
6566 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006567 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6568 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006569 }else{
6570 /* conchHeld < 0 is lockless */
6571 }
drh715ff302008-12-03 22:32:44 +00006572 }
6573 return rc;
6574}
6575
6576/*
6577** Close a file that uses proxy locks.
6578*/
6579static int proxyClose(sqlite3_file *id) {
6580 if( id ){
6581 unixFile *pFile = (unixFile*)id;
6582 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6583 unixFile *lockProxy = pCtx->lockProxy;
6584 unixFile *conchFile = pCtx->conchFile;
6585 int rc = SQLITE_OK;
6586
6587 if( lockProxy ){
6588 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6589 if( rc ) return rc;
6590 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6591 if( rc ) return rc;
6592 sqlite3_free(lockProxy);
6593 pCtx->lockProxy = 0;
6594 }
6595 if( conchFile ){
6596 if( pCtx->conchHeld ){
6597 rc = proxyReleaseConch(pFile);
6598 if( rc ) return rc;
6599 }
6600 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6601 if( rc ) return rc;
6602 sqlite3_free(conchFile);
6603 }
drhd56b1212010-08-11 06:14:15 +00006604 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006605 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006606 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006607 /* restore the original locking context and pMethod then close it */
6608 pFile->lockingContext = pCtx->oldLockingContext;
6609 pFile->pMethod = pCtx->pOldMethod;
6610 sqlite3_free(pCtx);
6611 return pFile->pMethod->xClose(id);
6612 }
6613 return SQLITE_OK;
6614}
6615
6616
6617
drhd2cb50b2009-01-09 21:41:17 +00006618#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006619/*
6620** The proxy locking style is intended for use with AFP filesystems.
6621** And since AFP is only supported on MacOSX, the proxy locking is also
6622** restricted to MacOSX.
6623**
6624**
6625******************* End of the proxy lock implementation **********************
6626******************************************************************************/
6627
drh734c9862008-11-28 15:37:20 +00006628/*
danielk1977e339d652008-06-28 11:23:00 +00006629** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006630**
6631** This routine registers all VFS implementations for unix-like operating
6632** systems. This routine, and the sqlite3_os_end() routine that follows,
6633** should be the only routines in this file that are visible from other
6634** files.
drh6b9d6dd2008-12-03 19:34:47 +00006635**
6636** This routine is called once during SQLite initialization and by a
6637** single thread. The memory allocation and mutex subsystems have not
6638** necessarily been initialized when this routine is called, and so they
6639** should not be used.
drh153c62c2007-08-24 03:51:33 +00006640*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006641int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006642 /*
6643 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006644 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6645 ** to the "finder" function. (pAppData is a pointer to a pointer because
6646 ** silly C90 rules prohibit a void* from being cast to a function pointer
6647 ** and so we have to go through the intermediate pointer to avoid problems
6648 ** when compiling with -pedantic-errors on GCC.)
6649 **
6650 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006651 ** finder-function. The finder-function returns a pointer to the
6652 ** sqlite_io_methods object that implements the desired locking
6653 ** behaviors. See the division above that contains the IOMETHODS
6654 ** macro for addition information on finder-functions.
6655 **
6656 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6657 ** object. But the "autolockIoFinder" available on MacOSX does a little
6658 ** more than that; it looks at the filesystem type that hosts the
6659 ** database file and tries to choose an locking method appropriate for
6660 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006661 */
drh7708e972008-11-29 00:56:52 +00006662 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006663 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006664 sizeof(unixFile), /* szOsFile */ \
6665 MAX_PATHNAME, /* mxPathname */ \
6666 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006667 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006668 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006669 unixOpen, /* xOpen */ \
6670 unixDelete, /* xDelete */ \
6671 unixAccess, /* xAccess */ \
6672 unixFullPathname, /* xFullPathname */ \
6673 unixDlOpen, /* xDlOpen */ \
6674 unixDlError, /* xDlError */ \
6675 unixDlSym, /* xDlSym */ \
6676 unixDlClose, /* xDlClose */ \
6677 unixRandomness, /* xRandomness */ \
6678 unixSleep, /* xSleep */ \
6679 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006680 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006681 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006682 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006683 unixGetSystemCall, /* xGetSystemCall */ \
6684 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006685 }
6686
drh6b9d6dd2008-12-03 19:34:47 +00006687 /*
6688 ** All default VFSes for unix are contained in the following array.
6689 **
6690 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6691 ** by the SQLite core when the VFS is registered. So the following
6692 ** array cannot be const.
6693 */
danielk1977e339d652008-06-28 11:23:00 +00006694 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006695#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006696 UNIXVFS("unix", autolockIoFinder ),
6697#else
6698 UNIXVFS("unix", posixIoFinder ),
6699#endif
6700 UNIXVFS("unix-none", nolockIoFinder ),
6701 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006702 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006703#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006704 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006705#endif
6706#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006707 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006708#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006709 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006710#endif
chw78a13182009-04-07 05:35:03 +00006711#endif
drhd2cb50b2009-01-09 21:41:17 +00006712#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006713 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006714 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006715 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006716#endif
drh153c62c2007-08-24 03:51:33 +00006717 };
drh6b9d6dd2008-12-03 19:34:47 +00006718 unsigned int i; /* Loop counter */
6719
drh2aa5a002011-04-13 13:42:25 +00006720 /* Double-check that the aSyscall[] array has been constructed
6721 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh036ac7f2011-08-08 23:18:05 +00006722 assert( ArraySize(aSyscall)==17 );
drh2aa5a002011-04-13 13:42:25 +00006723
drh6b9d6dd2008-12-03 19:34:47 +00006724 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006725 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006726 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006727 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006728 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006729}
danielk1977e339d652008-06-28 11:23:00 +00006730
6731/*
drh6b9d6dd2008-12-03 19:34:47 +00006732** Shutdown the operating system interface.
6733**
6734** Some operating systems might need to do some cleanup in this routine,
6735** to release dynamically allocated objects. But not on unix.
6736** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006737*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006738int sqlite3_os_end(void){
6739 return SQLITE_OK;
6740}
drhdce8bdb2007-08-16 13:01:44 +00006741
danielk197729bafea2008-06-26 10:41:19 +00006742#endif /* SQLITE_OS_UNIX */