blob: 5c648e3f9ce685e4d7261f7bbe677fd2851399c5 [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>
drhf2424c52010-04-26 00:04:55 +0000122#include <sys/mman.h>
danielk1977e339d652008-06-28 11:23:00 +0000123
drh40bbb0a2008-09-23 10:23:26 +0000124#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000125# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000126# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <semaphore.h>
128# include <limits.h>
129# else
drh9b35ea62008-11-29 02:20:26 +0000130# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000131# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
drhf8b4d8c2010-03-05 13:53:22 +0000135#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000136# include <sys/mount.h>
137#endif
138
drh9cbe6352005-11-29 03:13:21 +0000139/*
drh7ed97b92010-01-20 13:07:21 +0000140** Allowed values of unixFile.fsFlags
141*/
142#define SQLITE_FSFLAGS_IS_MSDOS 0x1
143
144/*
drhf1a221e2006-01-15 17:27:17 +0000145** If we are to be thread-safe, include the pthreads header and define
146** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000147*/
drhd677b3d2007-08-20 22:48:41 +0000148#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000149# include <pthread.h>
150# define SQLITE_UNIX_THREADS 1
151#endif
152
153/*
154** Default permissions when creating a new file
155*/
156#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
157# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
158#endif
159
danielk1977b4b47412007-08-17 15:53:36 +0000160/*
aswiftaebf4132008-11-21 00:10:35 +0000161 ** Default permissions when creating auto proxy dir
162 */
163#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
164# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
165#endif
166
167/*
danielk1977b4b47412007-08-17 15:53:36 +0000168** Maximum supported path-length.
169*/
170#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000171
drh734c9862008-11-28 15:37:20 +0000172/*
drh734c9862008-11-28 15:37:20 +0000173** Only set the lastErrno if the error code is a real error and not
174** a normal expected return code of SQLITE_BUSY or SQLITE_OK
175*/
176#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
177
drhd91c68f2010-05-14 14:52:25 +0000178/* Forward references */
179typedef struct unixShm unixShm; /* Connection shared memory */
180typedef struct unixShmNode unixShmNode; /* Shared memory instance */
181typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
182typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000183
184/*
dane946c392009-08-22 11:39:46 +0000185** Sometimes, after a file handle is closed by SQLite, the file descriptor
186** cannot be closed immediately. In these cases, instances of the following
187** structure are used to store the file descriptor while waiting for an
188** opportunity to either close or reuse it.
189*/
dane946c392009-08-22 11:39:46 +0000190struct UnixUnusedFd {
191 int fd; /* File descriptor to close */
192 int flags; /* Flags this file descriptor was opened with */
193 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
194};
195
196/*
drh9b35ea62008-11-29 02:20:26 +0000197** The unixFile structure is subclass of sqlite3_file specific to the unix
198** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000199*/
drh054889e2005-11-30 03:20:31 +0000200typedef struct unixFile unixFile;
201struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000202 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000203 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000204 int h; /* The file descriptor */
205 int dirfd; /* File descriptor for the directory */
206 unsigned char eFileLock; /* The type of lock held on this fd */
207 int lastErrno; /* The unix errno from last I/O error */
208 void *lockingContext; /* Locking style specific state */
209 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
210 int fileFlags; /* Miscellanous flags */
211 const char *zPath; /* Name of the file */
212 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000213 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000214#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000215 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000216#endif
drh7ed97b92010-01-20 13:07:21 +0000217#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000218 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000219#endif
220#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000221 int isDelete; /* Delete on close if true */
222 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000223#endif
drh8f941bc2009-01-14 23:03:40 +0000224#ifndef NDEBUG
225 /* The next group of variables are used to track whether or not the
226 ** transaction counter in bytes 24-27 of database files are updated
227 ** whenever any part of the database changes. An assertion fault will
228 ** occur if a file is updated without also updating the transaction
229 ** counter. This test is made to avoid new problems similar to the
230 ** one described by ticket #3584.
231 */
232 unsigned char transCntrChng; /* True if the transaction counter changed */
233 unsigned char dbUpdate; /* True if any part of database file changed */
234 unsigned char inNormalWrite; /* True if in a normal write operation */
235#endif
danielk1977967a4a12007-08-20 14:23:44 +0000236#ifdef SQLITE_TEST
237 /* In test mode, increase the size of this structure a bit so that
238 ** it is larger than the struct CrashFile defined in test6.c.
239 */
240 char aPadding[32];
241#endif
drh9cbe6352005-11-29 03:13:21 +0000242};
243
drh0ccebe72005-06-07 22:22:50 +0000244/*
drh0c2694b2009-09-03 16:23:44 +0000245** The following macros define bits in unixFile.fileFlags
246*/
247#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
248
249/*
drh198bf392006-01-06 21:52:49 +0000250** Include code that is common to all os_*.c files
251*/
252#include "os_common.h"
253
254/*
drh0ccebe72005-06-07 22:22:50 +0000255** Define various macros that are missing from some systems.
256*/
drhbbd42a62004-05-22 17:41:58 +0000257#ifndef O_LARGEFILE
258# define O_LARGEFILE 0
259#endif
260#ifdef SQLITE_DISABLE_LFS
261# undef O_LARGEFILE
262# define O_LARGEFILE 0
263#endif
264#ifndef O_NOFOLLOW
265# define O_NOFOLLOW 0
266#endif
267#ifndef O_BINARY
268# define O_BINARY 0
269#endif
270
271/*
272** The DJGPP compiler environment looks mostly like Unix, but it
273** lacks the fcntl() system call. So redefine fcntl() to be something
274** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000275** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000276*/
277#ifdef __DJGPP__
278# define fcntl(A,B,C) 0
279#endif
280
281/*
drh2b4b5962005-06-15 17:47:55 +0000282** The threadid macro resolves to the thread-id or to 0. Used for
283** testing and debugging only.
284*/
drhd677b3d2007-08-20 22:48:41 +0000285#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000286#define threadid pthread_self()
287#else
288#define threadid 0
289#endif
290
danielk197713adf8a2004-06-03 16:08:41 +0000291
drh107886a2008-11-21 22:21:50 +0000292/*
dan9359c7b2009-08-21 08:29:10 +0000293** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000294** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000295** vxworksFileId objects used by this file, all of which may be
296** shared by multiple threads.
297**
298** Function unixMutexHeld() is used to assert() that the global mutex
299** is held when required. This function is only used as part of assert()
300** statements. e.g.
301**
302** unixEnterMutex()
303** assert( unixMutexHeld() );
304** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000305*/
306static void unixEnterMutex(void){
307 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
308}
309static void unixLeaveMutex(void){
310 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
311}
dan9359c7b2009-08-21 08:29:10 +0000312#ifdef SQLITE_DEBUG
313static int unixMutexHeld(void) {
314 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
315}
316#endif
drh107886a2008-11-21 22:21:50 +0000317
drh734c9862008-11-28 15:37:20 +0000318
319#ifdef SQLITE_DEBUG
320/*
321** Helper function for printing out trace information from debugging
322** binaries. This returns the string represetation of the supplied
323** integer lock-type.
324*/
drh308c2a52010-05-14 11:30:18 +0000325static const char *azFileLock(int eFileLock){
326 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000327 case NO_LOCK: return "NONE";
328 case SHARED_LOCK: return "SHARED";
329 case RESERVED_LOCK: return "RESERVED";
330 case PENDING_LOCK: return "PENDING";
331 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000332 }
333 return "ERROR";
334}
335#endif
336
337#ifdef SQLITE_LOCK_TRACE
338/*
339** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000340**
drh734c9862008-11-28 15:37:20 +0000341** This routine is used for troubleshooting locks on multithreaded
342** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
343** command-line option on the compiler. This code is normally
344** turned off.
345*/
346static int lockTrace(int fd, int op, struct flock *p){
347 char *zOpName, *zType;
348 int s;
349 int savedErrno;
350 if( op==F_GETLK ){
351 zOpName = "GETLK";
352 }else if( op==F_SETLK ){
353 zOpName = "SETLK";
354 }else{
355 s = fcntl(fd, op, p);
356 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
357 return s;
358 }
359 if( p->l_type==F_RDLCK ){
360 zType = "RDLCK";
361 }else if( p->l_type==F_WRLCK ){
362 zType = "WRLCK";
363 }else if( p->l_type==F_UNLCK ){
364 zType = "UNLCK";
365 }else{
366 assert( 0 );
367 }
368 assert( p->l_whence==SEEK_SET );
369 s = fcntl(fd, op, p);
370 savedErrno = errno;
371 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
372 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
373 (int)p->l_pid, s);
374 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
375 struct flock l2;
376 l2 = *p;
377 fcntl(fd, F_GETLK, &l2);
378 if( l2.l_type==F_RDLCK ){
379 zType = "RDLCK";
380 }else if( l2.l_type==F_WRLCK ){
381 zType = "WRLCK";
382 }else if( l2.l_type==F_UNLCK ){
383 zType = "UNLCK";
384 }else{
385 assert( 0 );
386 }
387 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
388 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
389 }
390 errno = savedErrno;
391 return s;
392}
393#define fcntl lockTrace
394#endif /* SQLITE_LOCK_TRACE */
395
396
397
398/*
399** This routine translates a standard POSIX errno code into something
400** useful to the clients of the sqlite3 functions. Specifically, it is
401** intended to translate a variety of "try again" errors into SQLITE_BUSY
402** and a variety of "please close the file descriptor NOW" errors into
403** SQLITE_IOERR
404**
405** Errors during initialization of locks, or file system support for locks,
406** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
407*/
408static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
409 switch (posixError) {
410 case 0:
411 return SQLITE_OK;
412
413 case EAGAIN:
414 case ETIMEDOUT:
415 case EBUSY:
416 case EINTR:
417 case ENOLCK:
418 /* random NFS retry error, unless during file system support
419 * introspection, in which it actually means what it says */
420 return SQLITE_BUSY;
421
422 case EACCES:
423 /* EACCES is like EAGAIN during locking operations, but not any other time*/
424 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
425 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
426 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
427 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
428 return SQLITE_BUSY;
429 }
430 /* else fall through */
431 case EPERM:
432 return SQLITE_PERM;
433
434 case EDEADLK:
435 return SQLITE_IOERR_BLOCKED;
436
437#if EOPNOTSUPP!=ENOTSUP
438 case EOPNOTSUPP:
439 /* something went terribly awry, unless during file system support
440 * introspection, in which it actually means what it says */
441#endif
442#ifdef ENOTSUP
443 case ENOTSUP:
444 /* invalid fd, unless during file system support introspection, in which
445 * it actually means what it says */
446#endif
447 case EIO:
448 case EBADF:
449 case EINVAL:
450 case ENOTCONN:
451 case ENODEV:
452 case ENXIO:
453 case ENOENT:
454 case ESTALE:
455 case ENOSYS:
456 /* these should force the client to close the file and reconnect */
457
458 default:
459 return sqliteIOErr;
460 }
461}
462
463
464
465/******************************************************************************
466****************** Begin Unique File ID Utility Used By VxWorks ***************
467**
468** On most versions of unix, we can get a unique ID for a file by concatenating
469** the device number and the inode number. But this does not work on VxWorks.
470** On VxWorks, a unique file id must be based on the canonical filename.
471**
472** A pointer to an instance of the following structure can be used as a
473** unique file ID in VxWorks. Each instance of this structure contains
474** a copy of the canonical filename. There is also a reference count.
475** The structure is reclaimed when the number of pointers to it drops to
476** zero.
477**
478** There are never very many files open at one time and lookups are not
479** a performance-critical path, so it is sufficient to put these
480** structures on a linked list.
481*/
482struct vxworksFileId {
483 struct vxworksFileId *pNext; /* Next in a list of them all */
484 int nRef; /* Number of references to this one */
485 int nName; /* Length of the zCanonicalName[] string */
486 char *zCanonicalName; /* Canonical filename */
487};
488
489#if OS_VXWORKS
490/*
drh9b35ea62008-11-29 02:20:26 +0000491** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000492** variable:
493*/
494static struct vxworksFileId *vxworksFileList = 0;
495
496/*
497** Simplify a filename into its canonical form
498** by making the following changes:
499**
500** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000501** * convert /./ into just /
502** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000503**
504** Changes are made in-place. Return the new name length.
505**
506** The original filename is in z[0..n-1]. Return the number of
507** characters in the simplified name.
508*/
509static int vxworksSimplifyName(char *z, int n){
510 int i, j;
511 while( n>1 && z[n-1]=='/' ){ n--; }
512 for(i=j=0; i<n; i++){
513 if( z[i]=='/' ){
514 if( z[i+1]=='/' ) continue;
515 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
516 i += 1;
517 continue;
518 }
519 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
520 while( j>0 && z[j-1]!='/' ){ j--; }
521 if( j>0 ){ j--; }
522 i += 2;
523 continue;
524 }
525 }
526 z[j++] = z[i];
527 }
528 z[j] = 0;
529 return j;
530}
531
532/*
533** Find a unique file ID for the given absolute pathname. Return
534** a pointer to the vxworksFileId object. This pointer is the unique
535** file ID.
536**
537** The nRef field of the vxworksFileId object is incremented before
538** the object is returned. A new vxworksFileId object is created
539** and added to the global list if necessary.
540**
541** If a memory allocation error occurs, return NULL.
542*/
543static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
544 struct vxworksFileId *pNew; /* search key and new file ID */
545 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
546 int n; /* Length of zAbsoluteName string */
547
548 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000549 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000550 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
551 if( pNew==0 ) return 0;
552 pNew->zCanonicalName = (char*)&pNew[1];
553 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
554 n = vxworksSimplifyName(pNew->zCanonicalName, n);
555
556 /* Search for an existing entry that matching the canonical name.
557 ** If found, increment the reference count and return a pointer to
558 ** the existing file ID.
559 */
560 unixEnterMutex();
561 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
562 if( pCandidate->nName==n
563 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
564 ){
565 sqlite3_free(pNew);
566 pCandidate->nRef++;
567 unixLeaveMutex();
568 return pCandidate;
569 }
570 }
571
572 /* No match was found. We will make a new file ID */
573 pNew->nRef = 1;
574 pNew->nName = n;
575 pNew->pNext = vxworksFileList;
576 vxworksFileList = pNew;
577 unixLeaveMutex();
578 return pNew;
579}
580
581/*
582** Decrement the reference count on a vxworksFileId object. Free
583** the object when the reference count reaches zero.
584*/
585static void vxworksReleaseFileId(struct vxworksFileId *pId){
586 unixEnterMutex();
587 assert( pId->nRef>0 );
588 pId->nRef--;
589 if( pId->nRef==0 ){
590 struct vxworksFileId **pp;
591 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
592 assert( *pp==pId );
593 *pp = pId->pNext;
594 sqlite3_free(pId);
595 }
596 unixLeaveMutex();
597}
598#endif /* OS_VXWORKS */
599/*************** End of Unique File ID Utility Used By VxWorks ****************
600******************************************************************************/
601
602
603/******************************************************************************
604*************************** Posix Advisory Locking ****************************
605**
drh9b35ea62008-11-29 02:20:26 +0000606** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000607** section 6.5.2.2 lines 483 through 490 specify that when a process
608** sets or clears a lock, that operation overrides any prior locks set
609** by the same process. It does not explicitly say so, but this implies
610** that it overrides locks set by the same process using a different
611** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000612**
613** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000614** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
615**
616** Suppose ./file1 and ./file2 are really the same file (because
617** one is a hard or symbolic link to the other) then if you set
618** an exclusive lock on fd1, then try to get an exclusive lock
619** on fd2, it works. I would have expected the second lock to
620** fail since there was already a lock on the file due to fd1.
621** But not so. Since both locks came from the same process, the
622** second overrides the first, even though they were on different
623** file descriptors opened on different file names.
624**
drh734c9862008-11-28 15:37:20 +0000625** This means that we cannot use POSIX locks to synchronize file access
626** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000627** to synchronize access for threads in separate processes, but not
628** threads within the same process.
629**
630** To work around the problem, SQLite has to manage file locks internally
631** on its own. Whenever a new database is opened, we have to find the
632** specific inode of the database file (the inode is determined by the
633** st_dev and st_ino fields of the stat structure that fstat() fills in)
634** and check for locks already existing on that inode. When locks are
635** created or removed, we have to look at our own internal record of the
636** locks to see if another thread has previously set a lock on that same
637** inode.
638**
drh9b35ea62008-11-29 02:20:26 +0000639** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
640** For VxWorks, we have to use the alternative unique ID system based on
641** canonical filename and implemented in the previous division.)
642**
danielk1977ad94b582007-08-20 06:44:22 +0000643** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000644** descriptor. It is now a structure that holds the integer file
645** descriptor and a pointer to a structure that describes the internal
646** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000647** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000648** point to the same locking structure. The locking structure keeps
649** a reference count (so we will know when to delete it) and a "cnt"
650** field that tells us its internal lock status. cnt==0 means the
651** file is unlocked. cnt==-1 means the file has an exclusive lock.
652** cnt>0 means there are cnt shared locks on the file.
653**
654** Any attempt to lock or unlock a file first checks the locking
655** structure. The fcntl() system call is only invoked to set a
656** POSIX lock if the internal lock structure transitions between
657** a locked and an unlocked state.
658**
drh734c9862008-11-28 15:37:20 +0000659** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000660**
661** If you close a file descriptor that points to a file that has locks,
662** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000663** released. To work around this problem, each unixInodeInfo object
664** maintains a count of the number of pending locks on tha inode.
665** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000666** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000667** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000668** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000669** be closed and that list is walked (and cleared) when the last lock
670** clears.
671**
drh9b35ea62008-11-29 02:20:26 +0000672** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000673**
drh9b35ea62008-11-29 02:20:26 +0000674** Many older versions of linux use the LinuxThreads library which is
675** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000676** A cannot be modified or overridden by a different thread B.
677** Only thread A can modify the lock. Locking behavior is correct
678** if the appliation uses the newer Native Posix Thread Library (NPTL)
679** on linux - with NPTL a lock created by thread A can override locks
680** in thread B. But there is no way to know at compile-time which
681** threading library is being used. So there is no way to know at
682** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000683** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000684** current process.
drh5fdae772004-06-29 03:29:00 +0000685**
drh8af6c222010-05-14 12:43:01 +0000686** SQLite used to support LinuxThreads. But support for LinuxThreads
687** was dropped beginning with version 3.7.0. SQLite will still work with
688** LinuxThreads provided that (1) there is no more than one connection
689** per database file in the same process and (2) database connections
690** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000691*/
692
693/*
694** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000695** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000696*/
697struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000698 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000699#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000700 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000701#else
drh107886a2008-11-21 22:21:50 +0000702 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000703#endif
704};
705
706/*
drhbbd42a62004-05-22 17:41:58 +0000707** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000708** inode. Or, on LinuxThreads, there is one of these structures for
709** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000710**
danielk1977ad94b582007-08-20 06:44:22 +0000711** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000712** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000713** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000714*/
drh8af6c222010-05-14 12:43:01 +0000715struct unixInodeInfo {
716 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000717 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000718 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000719 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000720 unixShmNode *pShmNode; /* Shared memory associated with this inode */
721 int nLock; /* Number of outstanding file locks */
722 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
723 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
724 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000725#if defined(SQLITE_ENABLE_LOCKING_STYLE)
726 unsigned long long sharedByte; /* for AFP simulated shared lock */
727#endif
drh6c7d5c52008-11-21 20:32:33 +0000728#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000729 sem_t *pSem; /* Named POSIX semaphore */
730 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000731#endif
drhbbd42a62004-05-22 17:41:58 +0000732};
733
drhda0e7682008-07-30 15:27:54 +0000734/*
drh8af6c222010-05-14 12:43:01 +0000735** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000736*/
drhd91c68f2010-05-14 14:52:25 +0000737static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000738
drh5fdae772004-06-29 03:29:00 +0000739/*
danb0ac3e32010-06-16 10:55:42 +0000740** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
741** If all such file descriptors are closed without error, the list is
742** cleared and SQLITE_OK returned.
743**
744** Otherwise, if an error occurs, then successfully closed file descriptor
745** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
746** not deleted and SQLITE_IOERR_CLOSE returned.
747*/
748static int closePendingFds(unixFile *pFile){
749 int rc = SQLITE_OK;
750 unixInodeInfo *pInode = pFile->pInode;
751 UnixUnusedFd *pError = 0;
752 UnixUnusedFd *p;
753 UnixUnusedFd *pNext;
754 for(p=pInode->pUnused; p; p=pNext){
755 pNext = p->pNext;
756 if( close(p->fd) ){
757 pFile->lastErrno = errno;
758 rc = SQLITE_IOERR_CLOSE;
759 p->pNext = pError;
760 pError = p;
761 }else{
762 sqlite3_free(p);
763 }
764 }
765 pInode->pUnused = pError;
766 return rc;
767}
768
769/*
drh8af6c222010-05-14 12:43:01 +0000770** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000771**
772** The mutex entered using the unixEnterMutex() function must be held
773** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000774*/
danb0ac3e32010-06-16 10:55:42 +0000775static void releaseInodeInfo(unixFile *pFile){
776 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000777 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000778 if( pInode ){
779 pInode->nRef--;
780 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000781 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000782 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000783 if( pInode->pPrev ){
784 assert( pInode->pPrev->pNext==pInode );
785 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000786 }else{
drh8af6c222010-05-14 12:43:01 +0000787 assert( inodeList==pInode );
788 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000789 }
drh8af6c222010-05-14 12:43:01 +0000790 if( pInode->pNext ){
791 assert( pInode->pNext->pPrev==pInode );
792 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000793 }
drh8af6c222010-05-14 12:43:01 +0000794 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000795 }
drhbbd42a62004-05-22 17:41:58 +0000796 }
797}
798
799/*
drh8af6c222010-05-14 12:43:01 +0000800** Given a file descriptor, locate the unixInodeInfo object that
801** describes that file descriptor. Create a new one if necessary. The
802** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000803**
dan9359c7b2009-08-21 08:29:10 +0000804** The mutex entered using the unixEnterMutex() function must be held
805** when this function is called.
806**
drh6c7d5c52008-11-21 20:32:33 +0000807** Return an appropriate error code.
808*/
drh8af6c222010-05-14 12:43:01 +0000809static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000810 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000811 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000812){
813 int rc; /* System call return code */
814 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000815 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
816 struct stat statbuf; /* Low-level file information */
817 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000818
dan9359c7b2009-08-21 08:29:10 +0000819 assert( unixMutexHeld() );
820
drh6c7d5c52008-11-21 20:32:33 +0000821 /* Get low-level information about the file that we can used to
822 ** create a unique name for the file.
823 */
824 fd = pFile->h;
825 rc = fstat(fd, &statbuf);
826 if( rc!=0 ){
827 pFile->lastErrno = errno;
828#ifdef EOVERFLOW
829 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
830#endif
831 return SQLITE_IOERR;
832 }
833
drheb0d74f2009-02-03 15:27:02 +0000834#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000835 /* On OS X on an msdos filesystem, the inode number is reported
836 ** incorrectly for zero-size files. See ticket #3260. To work
837 ** around this problem (we consider it a bug in OS X, not SQLite)
838 ** we always increase the file size to 1 by writing a single byte
839 ** prior to accessing the inode number. The one byte written is
840 ** an ASCII 'S' character which also happens to be the first byte
841 ** in the header of every SQLite database. In this way, if there
842 ** is a race condition such that another thread has already populated
843 ** the first page of the database, no damage is done.
844 */
drh7ed97b92010-01-20 13:07:21 +0000845 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +0000846 rc = write(fd, "S", 1);
847 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000848 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000849 return SQLITE_IOERR;
850 }
drh6c7d5c52008-11-21 20:32:33 +0000851 rc = fstat(fd, &statbuf);
852 if( rc!=0 ){
853 pFile->lastErrno = errno;
854 return SQLITE_IOERR;
855 }
856 }
drheb0d74f2009-02-03 15:27:02 +0000857#endif
drh6c7d5c52008-11-21 20:32:33 +0000858
drh8af6c222010-05-14 12:43:01 +0000859 memset(&fileId, 0, sizeof(fileId));
860 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000861#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000862 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000863#else
drh8af6c222010-05-14 12:43:01 +0000864 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000865#endif
drh8af6c222010-05-14 12:43:01 +0000866 pInode = inodeList;
867 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
868 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000869 }
drh8af6c222010-05-14 12:43:01 +0000870 if( pInode==0 ){
871 pInode = sqlite3_malloc( sizeof(*pInode) );
872 if( pInode==0 ){
873 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000874 }
drh8af6c222010-05-14 12:43:01 +0000875 memset(pInode, 0, sizeof(*pInode));
876 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
877 pInode->nRef = 1;
878 pInode->pNext = inodeList;
879 pInode->pPrev = 0;
880 if( inodeList ) inodeList->pPrev = pInode;
881 inodeList = pInode;
882 }else{
883 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000884 }
drh8af6c222010-05-14 12:43:01 +0000885 *ppInode = pInode;
886 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000887}
drh6c7d5c52008-11-21 20:32:33 +0000888
aswift5b1a2562008-08-22 00:22:35 +0000889
890/*
danielk197713adf8a2004-06-03 16:08:41 +0000891** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000892** file by this or any other process. If such a lock is held, set *pResOut
893** to a non-zero value otherwise *pResOut is set to zero. The return value
894** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000895*/
danielk1977861f7452008-06-05 11:39:11 +0000896static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000897 int rc = SQLITE_OK;
898 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000899 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000900
danielk1977861f7452008-06-05 11:39:11 +0000901 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
902
drh054889e2005-11-30 03:20:31 +0000903 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000904 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000905
906 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000907 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000908 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000909 }
910
drh2ac3ee92004-06-07 16:27:46 +0000911 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000912 */
danielk197709480a92009-02-09 05:32:32 +0000913#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000914 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000915 struct flock lock;
916 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000917 lock.l_start = RESERVED_BYTE;
918 lock.l_len = 1;
919 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +0000920 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
921 int tErrno = errno;
922 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
923 pFile->lastErrno = tErrno;
924 } else if( lock.l_type!=F_UNLCK ){
925 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000926 }
927 }
danielk197709480a92009-02-09 05:32:32 +0000928#endif
danielk197713adf8a2004-06-03 16:08:41 +0000929
drh6c7d5c52008-11-21 20:32:33 +0000930 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +0000931 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +0000932
aswift5b1a2562008-08-22 00:22:35 +0000933 *pResOut = reserved;
934 return rc;
danielk197713adf8a2004-06-03 16:08:41 +0000935}
936
937/*
drh308c2a52010-05-14 11:30:18 +0000938** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +0000939** of the following:
940**
drh2ac3ee92004-06-07 16:27:46 +0000941** (1) SHARED_LOCK
942** (2) RESERVED_LOCK
943** (3) PENDING_LOCK
944** (4) EXCLUSIVE_LOCK
945**
drhb3e04342004-06-08 00:47:47 +0000946** Sometimes when requesting one lock state, additional lock states
947** are inserted in between. The locking might fail on one of the later
948** transitions leaving the lock state different from what it started but
949** still short of its goal. The following chart shows the allowed
950** transitions and the inserted intermediate states:
951**
952** UNLOCKED -> SHARED
953** SHARED -> RESERVED
954** SHARED -> (PENDING) -> EXCLUSIVE
955** RESERVED -> (PENDING) -> EXCLUSIVE
956** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000957**
drha6abd042004-06-09 17:37:22 +0000958** This routine will only increase a lock. Use the sqlite3OsUnlock()
959** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000960*/
drh308c2a52010-05-14 11:30:18 +0000961static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +0000962 /* The following describes the implementation of the various locks and
963 ** lock transitions in terms of the POSIX advisory shared and exclusive
964 ** lock primitives (called read-locks and write-locks below, to avoid
965 ** confusion with SQLite lock names). The algorithms are complicated
966 ** slightly in order to be compatible with windows systems simultaneously
967 ** accessing the same database file, in case that is ever required.
968 **
969 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
970 ** byte', each single bytes at well known offsets, and the 'shared byte
971 ** range', a range of 510 bytes at a well known offset.
972 **
973 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
974 ** byte'. If this is successful, a random byte from the 'shared byte
975 ** range' is read-locked and the lock on the 'pending byte' released.
976 **
danielk197790ba3bd2004-06-25 08:32:25 +0000977 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
978 ** A RESERVED lock is implemented by grabbing a write-lock on the
979 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000980 **
981 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000982 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
983 ** on the 'pending byte'. This ensures that no new SHARED locks can be
984 ** obtained, but existing SHARED locks are allowed to persist. A process
985 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
986 ** This property is used by the algorithm for rolling back a journal file
987 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000988 **
danielk197790ba3bd2004-06-25 08:32:25 +0000989 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
990 ** implemented by obtaining a write-lock on the entire 'shared byte
991 ** range'. Since all other locks require a read-lock on one of the bytes
992 ** within this range, this ensures that no other locks are held on the
993 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000994 **
995 ** The reason a single byte cannot be used instead of the 'shared byte
996 ** range' is that some versions of windows do not support read-locks. By
997 ** locking a random byte from a range, concurrent SHARED locks may exist
998 ** even if the locking primitive used is always a write-lock.
999 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001000 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001001 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001002 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001003 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001004 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001005 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001006
drh054889e2005-11-30 03:20:31 +00001007 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001008 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1009 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001010 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001011
1012 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001013 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001014 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001015 */
drh308c2a52010-05-14 11:30:18 +00001016 if( pFile->eFileLock>=eFileLock ){
1017 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1018 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001019 return SQLITE_OK;
1020 }
1021
drh0c2694b2009-09-03 16:23:44 +00001022 /* Make sure the locking sequence is correct.
1023 ** (1) We never move from unlocked to anything higher than shared lock.
1024 ** (2) SQLite never explicitly requests a pendig lock.
1025 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001026 */
drh308c2a52010-05-14 11:30:18 +00001027 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1028 assert( eFileLock!=PENDING_LOCK );
1029 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001030
drh8af6c222010-05-14 12:43:01 +00001031 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001032 */
drh6c7d5c52008-11-21 20:32:33 +00001033 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001034 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001035
danielk1977ad94b582007-08-20 06:44:22 +00001036 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001037 ** handle that precludes the requested lock, return BUSY.
1038 */
drh8af6c222010-05-14 12:43:01 +00001039 if( (pFile->eFileLock!=pInode->eFileLock &&
1040 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001041 ){
1042 rc = SQLITE_BUSY;
1043 goto end_lock;
1044 }
1045
1046 /* If a SHARED lock is requested, and some thread using this PID already
1047 ** has a SHARED or RESERVED lock, then increment reference counts and
1048 ** return SQLITE_OK.
1049 */
drh308c2a52010-05-14 11:30:18 +00001050 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001051 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001052 assert( eFileLock==SHARED_LOCK );
1053 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001054 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001055 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001056 pInode->nShared++;
1057 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001058 goto end_lock;
1059 }
1060
danielk19779a1d0ab2004-06-01 14:09:28 +00001061
drh3cde3bb2004-06-12 02:17:14 +00001062 /* A PENDING lock is needed before acquiring a SHARED lock and before
1063 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1064 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001065 */
drh0c2694b2009-09-03 16:23:44 +00001066 lock.l_len = 1L;
1067 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001068 if( eFileLock==SHARED_LOCK
1069 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001070 ){
drh308c2a52010-05-14 11:30:18 +00001071 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001072 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001073 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001074 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001075 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001076 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1077 if( IS_LOCK_ERROR(rc) ){
1078 pFile->lastErrno = tErrno;
1079 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001080 goto end_lock;
1081 }
drh3cde3bb2004-06-12 02:17:14 +00001082 }
1083
1084
1085 /* If control gets to this point, then actually go ahead and make
1086 ** operating system calls for the specified lock.
1087 */
drh308c2a52010-05-14 11:30:18 +00001088 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001089 assert( pInode->nShared==0 );
1090 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001091
drh2ac3ee92004-06-07 16:27:46 +00001092 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001093 lock.l_start = SHARED_FIRST;
1094 lock.l_len = SHARED_SIZE;
1095 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1096 tErrno = errno;
1097 }
drh2ac3ee92004-06-07 16:27:46 +00001098 /* Drop the temporary PENDING lock */
1099 lock.l_start = PENDING_BYTE;
1100 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001101 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001102 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001103 if( s != -1 ){
1104 /* This could happen with a network mount */
1105 tErrno = errno;
1106 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1107 if( IS_LOCK_ERROR(rc) ){
1108 pFile->lastErrno = tErrno;
1109 }
1110 goto end_lock;
1111 }
drh2b4b5962005-06-15 17:47:55 +00001112 }
drhe2396a12007-03-29 20:19:58 +00001113 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001114 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1115 if( IS_LOCK_ERROR(rc) ){
1116 pFile->lastErrno = tErrno;
1117 }
drhbbd42a62004-05-22 17:41:58 +00001118 }else{
drh308c2a52010-05-14 11:30:18 +00001119 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001120 pInode->nLock++;
1121 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001122 }
drh8af6c222010-05-14 12:43:01 +00001123 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001124 /* We are trying for an exclusive lock but another thread in this
1125 ** same process is still holding a shared lock. */
1126 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001127 }else{
drh3cde3bb2004-06-12 02:17:14 +00001128 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001129 ** assumed that there is a SHARED or greater lock on the file
1130 ** already.
1131 */
drh308c2a52010-05-14 11:30:18 +00001132 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001133 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001134 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001135 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001136 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001137 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001138 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001139 lock.l_start = SHARED_FIRST;
1140 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001141 break;
1142 default:
1143 assert(0);
1144 }
drh7ed97b92010-01-20 13:07:21 +00001145 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001146 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001147 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001148 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1149 if( IS_LOCK_ERROR(rc) ){
1150 pFile->lastErrno = tErrno;
1151 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001152 }
drhbbd42a62004-05-22 17:41:58 +00001153 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001154
drh8f941bc2009-01-14 23:03:40 +00001155
1156#ifndef NDEBUG
1157 /* Set up the transaction-counter change checking flags when
1158 ** transitioning from a SHARED to a RESERVED lock. The change
1159 ** from SHARED to RESERVED marks the beginning of a normal
1160 ** write operation (not a hot journal rollback).
1161 */
1162 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001163 && pFile->eFileLock<=SHARED_LOCK
1164 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001165 ){
1166 pFile->transCntrChng = 0;
1167 pFile->dbUpdate = 0;
1168 pFile->inNormalWrite = 1;
1169 }
1170#endif
1171
1172
danielk1977ecb2a962004-06-02 06:30:16 +00001173 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001174 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001175 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001176 }else if( eFileLock==EXCLUSIVE_LOCK ){
1177 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001178 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001179 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001180
1181end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001182 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001183 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1184 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001185 return rc;
1186}
1187
1188/*
dan08da86a2009-08-21 17:18:03 +00001189** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001190** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001191*/
1192static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001193 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001194 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001195 p->pNext = pInode->pUnused;
1196 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001197 pFile->h = -1;
1198 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001199}
1200
1201/*
drh308c2a52010-05-14 11:30:18 +00001202** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001203** must be either NO_LOCK or SHARED_LOCK.
1204**
1205** If the locking level of the file descriptor is already at or below
1206** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001207**
1208** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1209** the byte range is divided into 2 parts and the first part is unlocked then
1210** set to a read lock, then the other part is simply unlocked. This works
1211** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1212** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001213*/
drh308c2a52010-05-14 11:30:18 +00001214static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001215 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001216 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001217 struct flock lock;
1218 int rc = SQLITE_OK;
1219 int h;
drh0c2694b2009-09-03 16:23:44 +00001220 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001221
drh054889e2005-11-30 03:20:31 +00001222 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001223 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001224 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001225 getpid()));
drha6abd042004-06-09 17:37:22 +00001226
drh308c2a52010-05-14 11:30:18 +00001227 assert( eFileLock<=SHARED_LOCK );
1228 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001229 return SQLITE_OK;
1230 }
drh6c7d5c52008-11-21 20:32:33 +00001231 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001232 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001233 pInode = pFile->pInode;
1234 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001235 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001236 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001237 SimulateIOErrorBenign(1);
1238 SimulateIOError( h=(-1) )
1239 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001240
1241#ifndef NDEBUG
1242 /* When reducing a lock such that other processes can start
1243 ** reading the database file again, make sure that the
1244 ** transaction counter was updated if any part of the database
1245 ** file changed. If the transaction counter is not updated,
1246 ** other connections to the same file might not realize that
1247 ** the file has changed and hence might not know to flush their
1248 ** cache. The use of a stale cache can lead to database corruption.
1249 */
dan7c246102010-04-12 19:00:29 +00001250#if 0
drh8f941bc2009-01-14 23:03:40 +00001251 assert( pFile->inNormalWrite==0
1252 || pFile->dbUpdate==0
1253 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001254#endif
drh8f941bc2009-01-14 23:03:40 +00001255 pFile->inNormalWrite = 0;
1256#endif
1257
drh7ed97b92010-01-20 13:07:21 +00001258 /* downgrading to a shared lock on NFS involves clearing the write lock
1259 ** before establishing the readlock - to avoid a race condition we downgrade
1260 ** the lock in 2 blocks, so that part of the range will be covered by a
1261 ** write lock until the rest is covered by a read lock:
1262 ** 1: [WWWWW]
1263 ** 2: [....W]
1264 ** 3: [RRRRW]
1265 ** 4: [RRRR.]
1266 */
drh308c2a52010-05-14 11:30:18 +00001267 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001268 if( handleNFSUnlock ){
1269 off_t divSize = SHARED_SIZE - 1;
1270
1271 lock.l_type = F_UNLCK;
1272 lock.l_whence = SEEK_SET;
1273 lock.l_start = SHARED_FIRST;
1274 lock.l_len = divSize;
1275 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001276 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001277 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1278 if( IS_LOCK_ERROR(rc) ){
1279 pFile->lastErrno = tErrno;
1280 }
1281 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001282 }
drh7ed97b92010-01-20 13:07:21 +00001283 lock.l_type = F_RDLCK;
1284 lock.l_whence = SEEK_SET;
1285 lock.l_start = SHARED_FIRST;
1286 lock.l_len = divSize;
1287 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001288 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001289 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1290 if( IS_LOCK_ERROR(rc) ){
1291 pFile->lastErrno = tErrno;
1292 }
1293 goto end_unlock;
1294 }
1295 lock.l_type = F_UNLCK;
1296 lock.l_whence = SEEK_SET;
1297 lock.l_start = SHARED_FIRST+divSize;
1298 lock.l_len = SHARED_SIZE-divSize;
1299 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001300 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001301 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1302 if( IS_LOCK_ERROR(rc) ){
1303 pFile->lastErrno = tErrno;
1304 }
1305 goto end_unlock;
1306 }
1307 }else{
1308 lock.l_type = F_RDLCK;
1309 lock.l_whence = SEEK_SET;
1310 lock.l_start = SHARED_FIRST;
1311 lock.l_len = SHARED_SIZE;
1312 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001313 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001314 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1315 if( IS_LOCK_ERROR(rc) ){
1316 pFile->lastErrno = tErrno;
1317 }
1318 goto end_unlock;
1319 }
drh9c105bb2004-10-02 20:38:28 +00001320 }
1321 }
drhbbd42a62004-05-22 17:41:58 +00001322 lock.l_type = F_UNLCK;
1323 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001324 lock.l_start = PENDING_BYTE;
1325 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001326 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001327 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001328 }else{
drh0c2694b2009-09-03 16:23:44 +00001329 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001330 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1331 if( IS_LOCK_ERROR(rc) ){
1332 pFile->lastErrno = tErrno;
1333 }
drhcd731cf2009-03-28 23:23:02 +00001334 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001335 }
drhbbd42a62004-05-22 17:41:58 +00001336 }
drh308c2a52010-05-14 11:30:18 +00001337 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001338 /* Decrement the shared lock counter. Release the lock using an
1339 ** OS call only when all threads in this same process have released
1340 ** the lock.
1341 */
drh8af6c222010-05-14 12:43:01 +00001342 pInode->nShared--;
1343 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001344 lock.l_type = F_UNLCK;
1345 lock.l_whence = SEEK_SET;
1346 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001347 SimulateIOErrorBenign(1);
1348 SimulateIOError( h=(-1) )
1349 SimulateIOErrorBenign(0);
1350 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001351 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001352 }else{
drh0c2694b2009-09-03 16:23:44 +00001353 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001354 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001355 if( IS_LOCK_ERROR(rc) ){
1356 pFile->lastErrno = tErrno;
1357 }
drh8af6c222010-05-14 12:43:01 +00001358 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001359 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001360 }
drha6abd042004-06-09 17:37:22 +00001361 }
1362
drhbbd42a62004-05-22 17:41:58 +00001363 /* Decrement the count of locks against this same file. When the
1364 ** count reaches zero, close any other file descriptors whose close
1365 ** was deferred because of outstanding locks.
1366 */
drh8af6c222010-05-14 12:43:01 +00001367 pInode->nLock--;
1368 assert( pInode->nLock>=0 );
1369 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001370 int rc2 = closePendingFds(pFile);
1371 if( rc==SQLITE_OK ){
1372 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001373 }
drhbbd42a62004-05-22 17:41:58 +00001374 }
1375 }
aswift5b1a2562008-08-22 00:22:35 +00001376
1377end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001378 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001379 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001380 return rc;
drhbbd42a62004-05-22 17:41:58 +00001381}
1382
1383/*
drh308c2a52010-05-14 11:30:18 +00001384** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001385** must be either NO_LOCK or SHARED_LOCK.
1386**
1387** If the locking level of the file descriptor is already at or below
1388** the requested locking level, this routine is a no-op.
1389*/
drh308c2a52010-05-14 11:30:18 +00001390static int unixUnlock(sqlite3_file *id, int eFileLock){
1391 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001392}
1393
1394/*
danielk1977e339d652008-06-28 11:23:00 +00001395** This function performs the parts of the "close file" operation
1396** common to all locking schemes. It closes the directory and file
1397** handles, if they are valid, and sets all fields of the unixFile
1398** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001399**
1400** It is *not* necessary to hold the mutex when this routine is called,
1401** even on VxWorks. A mutex will be acquired on VxWorks by the
1402** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001403*/
1404static int closeUnixFile(sqlite3_file *id){
1405 unixFile *pFile = (unixFile*)id;
1406 if( pFile ){
1407 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001408 int err = close(pFile->dirfd);
1409 if( err ){
1410 pFile->lastErrno = errno;
1411 return SQLITE_IOERR_DIR_CLOSE;
1412 }else{
1413 pFile->dirfd=-1;
1414 }
danielk1977e339d652008-06-28 11:23:00 +00001415 }
1416 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001417 int err = close(pFile->h);
1418 if( err ){
1419 pFile->lastErrno = errno;
1420 return SQLITE_IOERR_CLOSE;
1421 }
danielk1977e339d652008-06-28 11:23:00 +00001422 }
drh6c7d5c52008-11-21 20:32:33 +00001423#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001424 if( pFile->pId ){
1425 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001426 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001427 }
drh107886a2008-11-21 22:21:50 +00001428 vxworksReleaseFileId(pFile->pId);
1429 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001430 }
1431#endif
drhff59a112010-05-14 20:15:51 +00001432 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001433 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001434 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001435 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001436 }
1437 return SQLITE_OK;
1438}
1439
1440/*
danielk1977e3026632004-06-22 11:29:02 +00001441** Close a file.
1442*/
danielk197762079062007-08-15 17:08:46 +00001443static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001444 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001445 if( id ){
1446 unixFile *pFile = (unixFile *)id;
1447 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001448 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001449 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001450 /* If there are outstanding locks, do not actually close the file just
1451 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001452 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001453 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001454 */
dan08da86a2009-08-21 17:18:03 +00001455 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001456 }
danb0ac3e32010-06-16 10:55:42 +00001457 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001458 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001459 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001460 }
aswiftaebf4132008-11-21 00:10:35 +00001461 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001462}
1463
drh734c9862008-11-28 15:37:20 +00001464/************** End of the posix advisory lock implementation *****************
1465******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001466
drh734c9862008-11-28 15:37:20 +00001467/******************************************************************************
1468****************************** No-op Locking **********************************
1469**
1470** Of the various locking implementations available, this is by far the
1471** simplest: locking is ignored. No attempt is made to lock the database
1472** file for reading or writing.
1473**
1474** This locking mode is appropriate for use on read-only databases
1475** (ex: databases that are burned into CD-ROM, for example.) It can
1476** also be used if the application employs some external mechanism to
1477** prevent simultaneous access of the same database by two or more
1478** database connections. But there is a serious risk of database
1479** corruption if this locking mode is used in situations where multiple
1480** database connections are accessing the same database file at the same
1481** time and one or more of those connections are writing.
1482*/
drhbfe66312006-10-03 17:40:40 +00001483
drh734c9862008-11-28 15:37:20 +00001484static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1485 UNUSED_PARAMETER(NotUsed);
1486 *pResOut = 0;
1487 return SQLITE_OK;
1488}
drh734c9862008-11-28 15:37:20 +00001489static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1490 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1491 return SQLITE_OK;
1492}
drh734c9862008-11-28 15:37:20 +00001493static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1494 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1495 return SQLITE_OK;
1496}
1497
1498/*
drh9b35ea62008-11-29 02:20:26 +00001499** Close the file.
drh734c9862008-11-28 15:37:20 +00001500*/
1501static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001502 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001503}
1504
1505/******************* End of the no-op lock implementation *********************
1506******************************************************************************/
1507
1508/******************************************************************************
1509************************* Begin dot-file Locking ******************************
1510**
drh0c2694b2009-09-03 16:23:44 +00001511** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001512** files in order to control access to the database. This works on just
1513** about every filesystem imaginable. But there are serious downsides:
1514**
1515** (1) There is zero concurrency. A single reader blocks all other
1516** connections from reading or writing the database.
1517**
1518** (2) An application crash or power loss can leave stale lock files
1519** sitting around that need to be cleared manually.
1520**
1521** Nevertheless, a dotlock is an appropriate locking mode for use if no
1522** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001523**
1524** Dotfile locking works by creating a file in the same directory as the
1525** database and with the same name but with a ".lock" extension added.
1526** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1527** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001528*/
1529
1530/*
1531** The file suffix added to the data base filename in order to create the
1532** lock file.
1533*/
1534#define DOTLOCK_SUFFIX ".lock"
1535
drh7708e972008-11-29 00:56:52 +00001536/*
1537** This routine checks if there is a RESERVED lock held on the specified
1538** file by this or any other process. If such a lock is held, set *pResOut
1539** to a non-zero value otherwise *pResOut is set to zero. The return value
1540** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1541**
1542** In dotfile locking, either a lock exists or it does not. So in this
1543** variation of CheckReservedLock(), *pResOut is set to true if any lock
1544** is held on the file and false if the file is unlocked.
1545*/
drh734c9862008-11-28 15:37:20 +00001546static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1547 int rc = SQLITE_OK;
1548 int reserved = 0;
1549 unixFile *pFile = (unixFile*)id;
1550
1551 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1552
1553 assert( pFile );
1554
1555 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001556 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001557 /* Either this connection or some other connection in the same process
1558 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001559 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001560 }else{
1561 /* The lock is held if and only if the lockfile exists */
1562 const char *zLockFile = (const char*)pFile->lockingContext;
1563 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001564 }
drh308c2a52010-05-14 11:30:18 +00001565 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001566 *pResOut = reserved;
1567 return rc;
1568}
1569
drh7708e972008-11-29 00:56:52 +00001570/*
drh308c2a52010-05-14 11:30:18 +00001571** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001572** of the following:
1573**
1574** (1) SHARED_LOCK
1575** (2) RESERVED_LOCK
1576** (3) PENDING_LOCK
1577** (4) EXCLUSIVE_LOCK
1578**
1579** Sometimes when requesting one lock state, additional lock states
1580** are inserted in between. The locking might fail on one of the later
1581** transitions leaving the lock state different from what it started but
1582** still short of its goal. The following chart shows the allowed
1583** transitions and the inserted intermediate states:
1584**
1585** UNLOCKED -> SHARED
1586** SHARED -> RESERVED
1587** SHARED -> (PENDING) -> EXCLUSIVE
1588** RESERVED -> (PENDING) -> EXCLUSIVE
1589** PENDING -> EXCLUSIVE
1590**
1591** This routine will only increase a lock. Use the sqlite3OsUnlock()
1592** routine to lower a locking level.
1593**
1594** With dotfile locking, we really only support state (4): EXCLUSIVE.
1595** But we track the other locking levels internally.
1596*/
drh308c2a52010-05-14 11:30:18 +00001597static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001598 unixFile *pFile = (unixFile*)id;
1599 int fd;
1600 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001601 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001602
drh7708e972008-11-29 00:56:52 +00001603
1604 /* If we have any lock, then the lock file already exists. All we have
1605 ** to do is adjust our internal record of the lock level.
1606 */
drh308c2a52010-05-14 11:30:18 +00001607 if( pFile->eFileLock > NO_LOCK ){
1608 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001609#if !OS_VXWORKS
1610 /* Always update the timestamp on the old file */
1611 utimes(zLockFile, NULL);
1612#endif
drh7708e972008-11-29 00:56:52 +00001613 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001614 }
1615
1616 /* grab an exclusive lock */
1617 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1618 if( fd<0 ){
1619 /* failed to open/create the file, someone else may have stolen the lock */
1620 int tErrno = errno;
1621 if( EEXIST == tErrno ){
1622 rc = SQLITE_BUSY;
1623 } else {
1624 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1625 if( IS_LOCK_ERROR(rc) ){
1626 pFile->lastErrno = tErrno;
1627 }
1628 }
drh7708e972008-11-29 00:56:52 +00001629 return rc;
drh734c9862008-11-28 15:37:20 +00001630 }
1631 if( close(fd) ){
1632 pFile->lastErrno = errno;
1633 rc = SQLITE_IOERR_CLOSE;
1634 }
1635
1636 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001637 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001638 return rc;
1639}
1640
drh7708e972008-11-29 00:56:52 +00001641/*
drh308c2a52010-05-14 11:30:18 +00001642** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001643** must be either NO_LOCK or SHARED_LOCK.
1644**
1645** If the locking level of the file descriptor is already at or below
1646** the requested locking level, this routine is a no-op.
1647**
1648** When the locking level reaches NO_LOCK, delete the lock file.
1649*/
drh308c2a52010-05-14 11:30:18 +00001650static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001651 unixFile *pFile = (unixFile*)id;
1652 char *zLockFile = (char *)pFile->lockingContext;
1653
1654 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001655 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1656 pFile->eFileLock, getpid()));
1657 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001658
1659 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001660 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001661 return SQLITE_OK;
1662 }
drh7708e972008-11-29 00:56:52 +00001663
1664 /* To downgrade to shared, simply update our internal notion of the
1665 ** lock state. No need to mess with the file on disk.
1666 */
drh308c2a52010-05-14 11:30:18 +00001667 if( eFileLock==SHARED_LOCK ){
1668 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001669 return SQLITE_OK;
1670 }
1671
drh7708e972008-11-29 00:56:52 +00001672 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001673 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001674 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001675 int rc = 0;
1676 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001677 if( ENOENT != tErrno ){
1678 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1679 }
1680 if( IS_LOCK_ERROR(rc) ){
1681 pFile->lastErrno = tErrno;
1682 }
1683 return rc;
1684 }
drh308c2a52010-05-14 11:30:18 +00001685 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001686 return SQLITE_OK;
1687}
1688
1689/*
drh9b35ea62008-11-29 02:20:26 +00001690** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001691*/
1692static int dotlockClose(sqlite3_file *id) {
1693 int rc;
1694 if( id ){
1695 unixFile *pFile = (unixFile*)id;
1696 dotlockUnlock(id, NO_LOCK);
1697 sqlite3_free(pFile->lockingContext);
1698 }
drh734c9862008-11-28 15:37:20 +00001699 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001700 return rc;
1701}
1702/****************** End of the dot-file lock implementation *******************
1703******************************************************************************/
1704
1705/******************************************************************************
1706************************** Begin flock Locking ********************************
1707**
1708** Use the flock() system call to do file locking.
1709**
drh6b9d6dd2008-12-03 19:34:47 +00001710** flock() locking is like dot-file locking in that the various
1711** fine-grain locking levels supported by SQLite are collapsed into
1712** a single exclusive lock. In other words, SHARED, RESERVED, and
1713** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1714** still works when you do this, but concurrency is reduced since
1715** only a single process can be reading the database at a time.
1716**
drh734c9862008-11-28 15:37:20 +00001717** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1718** compiling for VXWORKS.
1719*/
1720#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001721
drh6b9d6dd2008-12-03 19:34:47 +00001722/*
1723** This routine checks if there is a RESERVED lock held on the specified
1724** file by this or any other process. If such a lock is held, set *pResOut
1725** to a non-zero value otherwise *pResOut is set to zero. The return value
1726** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1727*/
drh734c9862008-11-28 15:37:20 +00001728static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1729 int rc = SQLITE_OK;
1730 int reserved = 0;
1731 unixFile *pFile = (unixFile*)id;
1732
1733 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1734
1735 assert( pFile );
1736
1737 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001738 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001739 reserved = 1;
1740 }
1741
1742 /* Otherwise see if some other process holds it. */
1743 if( !reserved ){
1744 /* attempt to get the lock */
1745 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1746 if( !lrc ){
1747 /* got the lock, unlock it */
1748 lrc = flock(pFile->h, LOCK_UN);
1749 if ( lrc ) {
1750 int tErrno = errno;
1751 /* unlock failed with an error */
1752 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1753 if( IS_LOCK_ERROR(lrc) ){
1754 pFile->lastErrno = tErrno;
1755 rc = lrc;
1756 }
1757 }
1758 } else {
1759 int tErrno = errno;
1760 reserved = 1;
1761 /* someone else might have it reserved */
1762 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1763 if( IS_LOCK_ERROR(lrc) ){
1764 pFile->lastErrno = tErrno;
1765 rc = lrc;
1766 }
1767 }
1768 }
drh308c2a52010-05-14 11:30:18 +00001769 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001770
1771#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1772 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1773 rc = SQLITE_OK;
1774 reserved=1;
1775 }
1776#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1777 *pResOut = reserved;
1778 return rc;
1779}
1780
drh6b9d6dd2008-12-03 19:34:47 +00001781/*
drh308c2a52010-05-14 11:30:18 +00001782** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001783** of the following:
1784**
1785** (1) SHARED_LOCK
1786** (2) RESERVED_LOCK
1787** (3) PENDING_LOCK
1788** (4) EXCLUSIVE_LOCK
1789**
1790** Sometimes when requesting one lock state, additional lock states
1791** are inserted in between. The locking might fail on one of the later
1792** transitions leaving the lock state different from what it started but
1793** still short of its goal. The following chart shows the allowed
1794** transitions and the inserted intermediate states:
1795**
1796** UNLOCKED -> SHARED
1797** SHARED -> RESERVED
1798** SHARED -> (PENDING) -> EXCLUSIVE
1799** RESERVED -> (PENDING) -> EXCLUSIVE
1800** PENDING -> EXCLUSIVE
1801**
1802** flock() only really support EXCLUSIVE locks. We track intermediate
1803** lock states in the sqlite3_file structure, but all locks SHARED or
1804** above are really EXCLUSIVE locks and exclude all other processes from
1805** access the file.
1806**
1807** This routine will only increase a lock. Use the sqlite3OsUnlock()
1808** routine to lower a locking level.
1809*/
drh308c2a52010-05-14 11:30:18 +00001810static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001811 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001812 unixFile *pFile = (unixFile*)id;
1813
1814 assert( pFile );
1815
1816 /* if we already have a lock, it is exclusive.
1817 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001818 if (pFile->eFileLock > NO_LOCK) {
1819 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001820 return SQLITE_OK;
1821 }
1822
1823 /* grab an exclusive lock */
1824
1825 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1826 int tErrno = errno;
1827 /* didn't get, must be busy */
1828 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1829 if( IS_LOCK_ERROR(rc) ){
1830 pFile->lastErrno = tErrno;
1831 }
1832 } else {
1833 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001834 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001835 }
drh308c2a52010-05-14 11:30:18 +00001836 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1837 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001838#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1839 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1840 rc = SQLITE_BUSY;
1841 }
1842#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1843 return rc;
1844}
1845
drh6b9d6dd2008-12-03 19:34:47 +00001846
1847/*
drh308c2a52010-05-14 11:30:18 +00001848** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001849** must be either NO_LOCK or SHARED_LOCK.
1850**
1851** If the locking level of the file descriptor is already at or below
1852** the requested locking level, this routine is a no-op.
1853*/
drh308c2a52010-05-14 11:30:18 +00001854static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001855 unixFile *pFile = (unixFile*)id;
1856
1857 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001858 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1859 pFile->eFileLock, getpid()));
1860 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001861
1862 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001863 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001864 return SQLITE_OK;
1865 }
1866
1867 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001868 if (eFileLock==SHARED_LOCK) {
1869 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001870 return SQLITE_OK;
1871 }
1872
1873 /* no, really, unlock. */
1874 int rc = flock(pFile->h, LOCK_UN);
1875 if (rc) {
1876 int r, tErrno = errno;
1877 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1878 if( IS_LOCK_ERROR(r) ){
1879 pFile->lastErrno = tErrno;
1880 }
1881#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1882 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1883 r = SQLITE_BUSY;
1884 }
1885#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1886
1887 return r;
1888 } else {
drh308c2a52010-05-14 11:30:18 +00001889 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001890 return SQLITE_OK;
1891 }
1892}
1893
1894/*
1895** Close a file.
1896*/
1897static int flockClose(sqlite3_file *id) {
1898 if( id ){
1899 flockUnlock(id, NO_LOCK);
1900 }
1901 return closeUnixFile(id);
1902}
1903
1904#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1905
1906/******************* End of the flock lock implementation *********************
1907******************************************************************************/
1908
1909/******************************************************************************
1910************************ Begin Named Semaphore Locking ************************
1911**
1912** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00001913**
1914** Semaphore locking is like dot-lock and flock in that it really only
1915** supports EXCLUSIVE locking. Only a single process can read or write
1916** the database file at a time. This reduces potential concurrency, but
1917** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00001918*/
1919#if OS_VXWORKS
1920
drh6b9d6dd2008-12-03 19:34:47 +00001921/*
1922** This routine checks if there is a RESERVED lock held on the specified
1923** file by this or any other process. If such a lock is held, set *pResOut
1924** to a non-zero value otherwise *pResOut is set to zero. The return value
1925** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1926*/
drh734c9862008-11-28 15:37:20 +00001927static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1928 int rc = SQLITE_OK;
1929 int reserved = 0;
1930 unixFile *pFile = (unixFile*)id;
1931
1932 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1933
1934 assert( pFile );
1935
1936 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001937 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001938 reserved = 1;
1939 }
1940
1941 /* Otherwise see if some other process holds it. */
1942 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00001943 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001944 struct stat statBuf;
1945
1946 if( sem_trywait(pSem)==-1 ){
1947 int tErrno = errno;
1948 if( EAGAIN != tErrno ){
1949 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1950 pFile->lastErrno = tErrno;
1951 } else {
1952 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00001953 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00001954 }
1955 }else{
1956 /* we could have it if we want it */
1957 sem_post(pSem);
1958 }
1959 }
drh308c2a52010-05-14 11:30:18 +00001960 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001961
1962 *pResOut = reserved;
1963 return rc;
1964}
1965
drh6b9d6dd2008-12-03 19:34:47 +00001966/*
drh308c2a52010-05-14 11:30:18 +00001967** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001968** of the following:
1969**
1970** (1) SHARED_LOCK
1971** (2) RESERVED_LOCK
1972** (3) PENDING_LOCK
1973** (4) EXCLUSIVE_LOCK
1974**
1975** Sometimes when requesting one lock state, additional lock states
1976** are inserted in between. The locking might fail on one of the later
1977** transitions leaving the lock state different from what it started but
1978** still short of its goal. The following chart shows the allowed
1979** transitions and the inserted intermediate states:
1980**
1981** UNLOCKED -> SHARED
1982** SHARED -> RESERVED
1983** SHARED -> (PENDING) -> EXCLUSIVE
1984** RESERVED -> (PENDING) -> EXCLUSIVE
1985** PENDING -> EXCLUSIVE
1986**
1987** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
1988** lock states in the sqlite3_file structure, but all locks SHARED or
1989** above are really EXCLUSIVE locks and exclude all other processes from
1990** access the file.
1991**
1992** This routine will only increase a lock. Use the sqlite3OsUnlock()
1993** routine to lower a locking level.
1994*/
drh308c2a52010-05-14 11:30:18 +00001995static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001996 unixFile *pFile = (unixFile*)id;
1997 int fd;
drh8af6c222010-05-14 12:43:01 +00001998 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001999 int rc = SQLITE_OK;
2000
2001 /* if we already have a lock, it is exclusive.
2002 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002003 if (pFile->eFileLock > NO_LOCK) {
2004 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002005 rc = SQLITE_OK;
2006 goto sem_end_lock;
2007 }
2008
2009 /* lock semaphore now but bail out when already locked. */
2010 if( sem_trywait(pSem)==-1 ){
2011 rc = SQLITE_BUSY;
2012 goto sem_end_lock;
2013 }
2014
2015 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002016 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002017
2018 sem_end_lock:
2019 return rc;
2020}
2021
drh6b9d6dd2008-12-03 19:34:47 +00002022/*
drh308c2a52010-05-14 11:30:18 +00002023** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002024** must be either NO_LOCK or SHARED_LOCK.
2025**
2026** If the locking level of the file descriptor is already at or below
2027** the requested locking level, this routine is a no-op.
2028*/
drh308c2a52010-05-14 11:30:18 +00002029static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002030 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002031 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002032
2033 assert( pFile );
2034 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002035 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2036 pFile->eFileLock, getpid()));
2037 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002038
2039 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002040 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002041 return SQLITE_OK;
2042 }
2043
2044 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002045 if (eFileLock==SHARED_LOCK) {
2046 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002047 return SQLITE_OK;
2048 }
2049
2050 /* no, really unlock. */
2051 if ( sem_post(pSem)==-1 ) {
2052 int rc, tErrno = errno;
2053 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2054 if( IS_LOCK_ERROR(rc) ){
2055 pFile->lastErrno = tErrno;
2056 }
2057 return rc;
2058 }
drh308c2a52010-05-14 11:30:18 +00002059 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002060 return SQLITE_OK;
2061}
2062
2063/*
2064 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002065 */
drh734c9862008-11-28 15:37:20 +00002066static int semClose(sqlite3_file *id) {
2067 if( id ){
2068 unixFile *pFile = (unixFile*)id;
2069 semUnlock(id, NO_LOCK);
2070 assert( pFile );
2071 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002072 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002073 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002074 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002075 }
2076 return SQLITE_OK;
2077}
2078
2079#endif /* OS_VXWORKS */
2080/*
2081** Named semaphore locking is only available on VxWorks.
2082**
2083*************** End of the named semaphore lock implementation ****************
2084******************************************************************************/
2085
2086
2087/******************************************************************************
2088*************************** Begin AFP Locking *********************************
2089**
2090** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2091** on Apple Macintosh computers - both OS9 and OSX.
2092**
2093** Third-party implementations of AFP are available. But this code here
2094** only works on OSX.
2095*/
2096
drhd2cb50b2009-01-09 21:41:17 +00002097#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002098/*
2099** The afpLockingContext structure contains all afp lock specific state
2100*/
drhbfe66312006-10-03 17:40:40 +00002101typedef struct afpLockingContext afpLockingContext;
2102struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002103 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002104 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002105};
2106
2107struct ByteRangeLockPB2
2108{
2109 unsigned long long offset; /* offset to first byte to lock */
2110 unsigned long long length; /* nbr of bytes to lock */
2111 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2112 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2113 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2114 int fd; /* file desc to assoc this lock with */
2115};
2116
drhfd131da2007-08-07 17:13:03 +00002117#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002118
drh6b9d6dd2008-12-03 19:34:47 +00002119/*
2120** This is a utility for setting or clearing a bit-range lock on an
2121** AFP filesystem.
2122**
2123** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2124*/
2125static int afpSetLock(
2126 const char *path, /* Name of the file to be locked or unlocked */
2127 unixFile *pFile, /* Open file descriptor on path */
2128 unsigned long long offset, /* First byte to be locked */
2129 unsigned long long length, /* Number of bytes to lock */
2130 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002131){
drh6b9d6dd2008-12-03 19:34:47 +00002132 struct ByteRangeLockPB2 pb;
2133 int err;
drhbfe66312006-10-03 17:40:40 +00002134
2135 pb.unLockFlag = setLockFlag ? 0 : 1;
2136 pb.startEndFlag = 0;
2137 pb.offset = offset;
2138 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002139 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002140
drh308c2a52010-05-14 11:30:18 +00002141 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002142 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002143 offset, length));
drhbfe66312006-10-03 17:40:40 +00002144 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2145 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002146 int rc;
2147 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002148 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2149 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002150#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2151 rc = SQLITE_BUSY;
2152#else
drh734c9862008-11-28 15:37:20 +00002153 rc = sqliteErrorFromPosixError(tErrno,
2154 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002155#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002156 if( IS_LOCK_ERROR(rc) ){
2157 pFile->lastErrno = tErrno;
2158 }
2159 return rc;
drhbfe66312006-10-03 17:40:40 +00002160 } else {
aswift5b1a2562008-08-22 00:22:35 +00002161 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002162 }
2163}
2164
drh6b9d6dd2008-12-03 19:34:47 +00002165/*
2166** This routine checks if there is a RESERVED lock held on the specified
2167** file by this or any other process. If such a lock is held, set *pResOut
2168** to a non-zero value otherwise *pResOut is set to zero. The return value
2169** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2170*/
danielk1977e339d652008-06-28 11:23:00 +00002171static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002172 int rc = SQLITE_OK;
2173 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002174 unixFile *pFile = (unixFile*)id;
2175
aswift5b1a2562008-08-22 00:22:35 +00002176 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2177
2178 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002179 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002180 if( context->reserved ){
2181 *pResOut = 1;
2182 return SQLITE_OK;
2183 }
drh8af6c222010-05-14 12:43:01 +00002184 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002185
2186 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002187 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002188 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002189 }
2190
2191 /* Otherwise see if some other process holds it.
2192 */
aswift5b1a2562008-08-22 00:22:35 +00002193 if( !reserved ){
2194 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002195 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002196 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002197 /* if we succeeded in taking the reserved lock, unlock it to restore
2198 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002199 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002200 } else {
2201 /* if we failed to get the lock then someone else must have it */
2202 reserved = 1;
2203 }
2204 if( IS_LOCK_ERROR(lrc) ){
2205 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002206 }
2207 }
drhbfe66312006-10-03 17:40:40 +00002208
drh7ed97b92010-01-20 13:07:21 +00002209 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002210 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002211
2212 *pResOut = reserved;
2213 return rc;
drhbfe66312006-10-03 17:40:40 +00002214}
2215
drh6b9d6dd2008-12-03 19:34:47 +00002216/*
drh308c2a52010-05-14 11:30:18 +00002217** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002218** of the following:
2219**
2220** (1) SHARED_LOCK
2221** (2) RESERVED_LOCK
2222** (3) PENDING_LOCK
2223** (4) EXCLUSIVE_LOCK
2224**
2225** Sometimes when requesting one lock state, additional lock states
2226** are inserted in between. The locking might fail on one of the later
2227** transitions leaving the lock state different from what it started but
2228** still short of its goal. The following chart shows the allowed
2229** transitions and the inserted intermediate states:
2230**
2231** UNLOCKED -> SHARED
2232** SHARED -> RESERVED
2233** SHARED -> (PENDING) -> EXCLUSIVE
2234** RESERVED -> (PENDING) -> EXCLUSIVE
2235** PENDING -> EXCLUSIVE
2236**
2237** This routine will only increase a lock. Use the sqlite3OsUnlock()
2238** routine to lower a locking level.
2239*/
drh308c2a52010-05-14 11:30:18 +00002240static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002241 int rc = SQLITE_OK;
2242 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002243 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002244 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002245
2246 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002247 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2248 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002249 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002250
drhbfe66312006-10-03 17:40:40 +00002251 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002252 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002253 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002254 */
drh308c2a52010-05-14 11:30:18 +00002255 if( pFile->eFileLock>=eFileLock ){
2256 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2257 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002258 return SQLITE_OK;
2259 }
2260
2261 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002262 ** (1) We never move from unlocked to anything higher than shared lock.
2263 ** (2) SQLite never explicitly requests a pendig lock.
2264 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002265 */
drh308c2a52010-05-14 11:30:18 +00002266 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2267 assert( eFileLock!=PENDING_LOCK );
2268 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002269
drh8af6c222010-05-14 12:43:01 +00002270 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002271 */
drh6c7d5c52008-11-21 20:32:33 +00002272 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002273 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002274
2275 /* If some thread using this PID has a lock via a different unixFile*
2276 ** handle that precludes the requested lock, return BUSY.
2277 */
drh8af6c222010-05-14 12:43:01 +00002278 if( (pFile->eFileLock!=pInode->eFileLock &&
2279 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002280 ){
2281 rc = SQLITE_BUSY;
2282 goto afp_end_lock;
2283 }
2284
2285 /* If a SHARED lock is requested, and some thread using this PID already
2286 ** has a SHARED or RESERVED lock, then increment reference counts and
2287 ** return SQLITE_OK.
2288 */
drh308c2a52010-05-14 11:30:18 +00002289 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002290 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002291 assert( eFileLock==SHARED_LOCK );
2292 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002293 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002294 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002295 pInode->nShared++;
2296 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002297 goto afp_end_lock;
2298 }
drhbfe66312006-10-03 17:40:40 +00002299
2300 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002301 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2302 ** be released.
2303 */
drh308c2a52010-05-14 11:30:18 +00002304 if( eFileLock==SHARED_LOCK
2305 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002306 ){
2307 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002308 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002309 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002310 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002311 goto afp_end_lock;
2312 }
2313 }
2314
2315 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002316 ** operating system calls for the specified lock.
2317 */
drh308c2a52010-05-14 11:30:18 +00002318 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002319 int lrc1, lrc2, lrc1Errno;
2320 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002321
drh8af6c222010-05-14 12:43:01 +00002322 assert( pInode->nShared==0 );
2323 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002324
2325 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002326 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002327 /* note that the quality of the randomness doesn't matter that much */
2328 lk = random();
drh8af6c222010-05-14 12:43:01 +00002329 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002330 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002331 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002332 if( IS_LOCK_ERROR(lrc1) ){
2333 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002334 }
aswift5b1a2562008-08-22 00:22:35 +00002335 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002336 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002337
aswift5b1a2562008-08-22 00:22:35 +00002338 if( IS_LOCK_ERROR(lrc1) ) {
2339 pFile->lastErrno = lrc1Errno;
2340 rc = lrc1;
2341 goto afp_end_lock;
2342 } else if( IS_LOCK_ERROR(lrc2) ){
2343 rc = lrc2;
2344 goto afp_end_lock;
2345 } else if( lrc1 != SQLITE_OK ) {
2346 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002347 } else {
drh308c2a52010-05-14 11:30:18 +00002348 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002349 pInode->nLock++;
2350 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002351 }
drh8af6c222010-05-14 12:43:01 +00002352 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002353 /* We are trying for an exclusive lock but another thread in this
2354 ** same process is still holding a shared lock. */
2355 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002356 }else{
2357 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2358 ** assumed that there is a SHARED or greater lock on the file
2359 ** already.
2360 */
2361 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002362 assert( 0!=pFile->eFileLock );
2363 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002364 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002365 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002366 if( !failed ){
2367 context->reserved = 1;
2368 }
drhbfe66312006-10-03 17:40:40 +00002369 }
drh308c2a52010-05-14 11:30:18 +00002370 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002371 /* Acquire an EXCLUSIVE lock */
2372
2373 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002374 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002375 */
drh6b9d6dd2008-12-03 19:34:47 +00002376 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002377 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002378 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002379 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002380 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002381 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002382 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002383 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002384 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2385 ** a critical I/O error
2386 */
2387 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2388 SQLITE_IOERR_LOCK;
2389 goto afp_end_lock;
2390 }
2391 }else{
aswift5b1a2562008-08-22 00:22:35 +00002392 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002393 }
2394 }
aswift5b1a2562008-08-22 00:22:35 +00002395 if( failed ){
2396 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002397 }
2398 }
2399
2400 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002401 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002402 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002403 }else if( eFileLock==EXCLUSIVE_LOCK ){
2404 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002405 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002406 }
2407
2408afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002409 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002410 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2411 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002412 return rc;
2413}
2414
2415/*
drh308c2a52010-05-14 11:30:18 +00002416** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002417** must be either NO_LOCK or SHARED_LOCK.
2418**
2419** If the locking level of the file descriptor is already at or below
2420** the requested locking level, this routine is a no-op.
2421*/
drh308c2a52010-05-14 11:30:18 +00002422static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002423 int rc = SQLITE_OK;
2424 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002425 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002426 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2427 int skipShared = 0;
2428#ifdef SQLITE_TEST
2429 int h = pFile->h;
2430#endif
drhbfe66312006-10-03 17:40:40 +00002431
2432 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002433 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002434 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002435 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002436
drh308c2a52010-05-14 11:30:18 +00002437 assert( eFileLock<=SHARED_LOCK );
2438 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002439 return SQLITE_OK;
2440 }
drh6c7d5c52008-11-21 20:32:33 +00002441 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002442 pInode = pFile->pInode;
2443 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002444 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002445 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002446 SimulateIOErrorBenign(1);
2447 SimulateIOError( h=(-1) )
2448 SimulateIOErrorBenign(0);
2449
2450#ifndef NDEBUG
2451 /* When reducing a lock such that other processes can start
2452 ** reading the database file again, make sure that the
2453 ** transaction counter was updated if any part of the database
2454 ** file changed. If the transaction counter is not updated,
2455 ** other connections to the same file might not realize that
2456 ** the file has changed and hence might not know to flush their
2457 ** cache. The use of a stale cache can lead to database corruption.
2458 */
2459 assert( pFile->inNormalWrite==0
2460 || pFile->dbUpdate==0
2461 || pFile->transCntrChng==1 );
2462 pFile->inNormalWrite = 0;
2463#endif
aswiftaebf4132008-11-21 00:10:35 +00002464
drh308c2a52010-05-14 11:30:18 +00002465 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002466 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002467 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002468 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002469 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002470 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2471 } else {
2472 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002473 }
2474 }
drh308c2a52010-05-14 11:30:18 +00002475 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002476 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002477 }
drh308c2a52010-05-14 11:30:18 +00002478 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002479 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2480 if( !rc ){
2481 context->reserved = 0;
2482 }
aswiftaebf4132008-11-21 00:10:35 +00002483 }
drh8af6c222010-05-14 12:43:01 +00002484 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2485 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002486 }
aswiftaebf4132008-11-21 00:10:35 +00002487 }
drh308c2a52010-05-14 11:30:18 +00002488 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002489
drh7ed97b92010-01-20 13:07:21 +00002490 /* Decrement the shared lock counter. Release the lock using an
2491 ** OS call only when all threads in this same process have released
2492 ** the lock.
2493 */
drh8af6c222010-05-14 12:43:01 +00002494 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2495 pInode->nShared--;
2496 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002497 SimulateIOErrorBenign(1);
2498 SimulateIOError( h=(-1) )
2499 SimulateIOErrorBenign(0);
2500 if( !skipShared ){
2501 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2502 }
2503 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002504 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002505 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002506 }
2507 }
2508 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002509 pInode->nLock--;
2510 assert( pInode->nLock>=0 );
2511 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002512 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002513 }
2514 }
drhbfe66312006-10-03 17:40:40 +00002515 }
drh7ed97b92010-01-20 13:07:21 +00002516
drh6c7d5c52008-11-21 20:32:33 +00002517 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002518 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002519 return rc;
2520}
2521
2522/*
drh339eb0b2008-03-07 15:34:11 +00002523** Close a file & cleanup AFP specific locking context
2524*/
danielk1977e339d652008-06-28 11:23:00 +00002525static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002526 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002527 if( id ){
2528 unixFile *pFile = (unixFile*)id;
2529 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002530 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002531 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002532 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002533 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002534 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002535 ** the last lock is cleared.
2536 */
dan08da86a2009-08-21 17:18:03 +00002537 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002538 }
danb0ac3e32010-06-16 10:55:42 +00002539 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002540 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002541 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002542 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002543 }
drh7ed97b92010-01-20 13:07:21 +00002544 return rc;
drhbfe66312006-10-03 17:40:40 +00002545}
2546
drhd2cb50b2009-01-09 21:41:17 +00002547#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002548/*
2549** The code above is the AFP lock implementation. The code is specific
2550** to MacOSX and does not work on other unix platforms. No alternative
2551** is available. If you don't compile for a mac, then the "unix-afp"
2552** VFS is not available.
2553**
2554********************* End of the AFP lock implementation **********************
2555******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002556
drh7ed97b92010-01-20 13:07:21 +00002557/******************************************************************************
2558*************************** Begin NFS Locking ********************************/
2559
2560#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2561/*
drh308c2a52010-05-14 11:30:18 +00002562 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002563 ** must be either NO_LOCK or SHARED_LOCK.
2564 **
2565 ** If the locking level of the file descriptor is already at or below
2566 ** the requested locking level, this routine is a no-op.
2567 */
drh308c2a52010-05-14 11:30:18 +00002568static int nfsUnlock(sqlite3_file *id, int eFileLock){
2569 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002570}
2571
2572#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2573/*
2574** The code above is the NFS lock implementation. The code is specific
2575** to MacOSX and does not work on other unix platforms. No alternative
2576** is available.
2577**
2578********************* End of the NFS lock implementation **********************
2579******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002580
2581/******************************************************************************
2582**************** Non-locking sqlite3_file methods *****************************
2583**
2584** The next division contains implementations for all methods of the
2585** sqlite3_file object other than the locking methods. The locking
2586** methods were defined in divisions above (one locking method per
2587** division). Those methods that are common to all locking modes
2588** are gather together into this division.
2589*/
drhbfe66312006-10-03 17:40:40 +00002590
2591/*
drh734c9862008-11-28 15:37:20 +00002592** Seek to the offset passed as the second argument, then read cnt
2593** bytes into pBuf. Return the number of bytes actually read.
2594**
2595** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2596** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2597** one system to another. Since SQLite does not define USE_PREAD
2598** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2599** See tickets #2741 and #2681.
2600**
2601** To avoid stomping the errno value on a failed read the lastErrno value
2602** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002603*/
drh734c9862008-11-28 15:37:20 +00002604static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2605 int got;
drh7ed97b92010-01-20 13:07:21 +00002606#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002607 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002608#endif
drh734c9862008-11-28 15:37:20 +00002609 TIMER_START;
2610#if defined(USE_PREAD)
2611 got = pread(id->h, pBuf, cnt, offset);
2612 SimulateIOError( got = -1 );
2613#elif defined(USE_PREAD64)
2614 got = pread64(id->h, pBuf, cnt, offset);
2615 SimulateIOError( got = -1 );
2616#else
2617 newOffset = lseek(id->h, offset, SEEK_SET);
2618 SimulateIOError( newOffset-- );
2619 if( newOffset!=offset ){
2620 if( newOffset == -1 ){
2621 ((unixFile*)id)->lastErrno = errno;
2622 }else{
2623 ((unixFile*)id)->lastErrno = 0;
2624 }
2625 return -1;
2626 }
2627 got = read(id->h, pBuf, cnt);
2628#endif
2629 TIMER_END;
2630 if( got<0 ){
2631 ((unixFile*)id)->lastErrno = errno;
2632 }
drh308c2a52010-05-14 11:30:18 +00002633 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002634 return got;
drhbfe66312006-10-03 17:40:40 +00002635}
2636
2637/*
drh734c9862008-11-28 15:37:20 +00002638** Read data from a file into a buffer. Return SQLITE_OK if all
2639** bytes were read successfully and SQLITE_IOERR if anything goes
2640** wrong.
drh339eb0b2008-03-07 15:34:11 +00002641*/
drh734c9862008-11-28 15:37:20 +00002642static int unixRead(
2643 sqlite3_file *id,
2644 void *pBuf,
2645 int amt,
2646 sqlite3_int64 offset
2647){
dan08da86a2009-08-21 17:18:03 +00002648 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002649 int got;
2650 assert( id );
drh08c6d442009-02-09 17:34:07 +00002651
dan08da86a2009-08-21 17:18:03 +00002652 /* If this is a database file (not a journal, master-journal or temp
2653 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002654#if 0
dane946c392009-08-22 11:39:46 +00002655 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002656 || offset>=PENDING_BYTE+512
2657 || offset+amt<=PENDING_BYTE
2658 );
dan7c246102010-04-12 19:00:29 +00002659#endif
drh08c6d442009-02-09 17:34:07 +00002660
dan08da86a2009-08-21 17:18:03 +00002661 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002662 if( got==amt ){
2663 return SQLITE_OK;
2664 }else if( got<0 ){
2665 /* lastErrno set by seekAndRead */
2666 return SQLITE_IOERR_READ;
2667 }else{
dan08da86a2009-08-21 17:18:03 +00002668 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002669 /* Unread parts of the buffer must be zero-filled */
2670 memset(&((char*)pBuf)[got], 0, amt-got);
2671 return SQLITE_IOERR_SHORT_READ;
2672 }
2673}
2674
2675/*
2676** Seek to the offset in id->offset then read cnt bytes into pBuf.
2677** Return the number of bytes actually read. Update the offset.
2678**
2679** To avoid stomping the errno value on a failed write the lastErrno value
2680** is set before returning.
2681*/
2682static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2683 int got;
drh7ed97b92010-01-20 13:07:21 +00002684#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002685 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002686#endif
drh734c9862008-11-28 15:37:20 +00002687 TIMER_START;
2688#if defined(USE_PREAD)
2689 got = pwrite(id->h, pBuf, cnt, offset);
2690#elif defined(USE_PREAD64)
2691 got = pwrite64(id->h, pBuf, cnt, offset);
2692#else
2693 newOffset = lseek(id->h, offset, SEEK_SET);
2694 if( newOffset!=offset ){
2695 if( newOffset == -1 ){
2696 ((unixFile*)id)->lastErrno = errno;
2697 }else{
2698 ((unixFile*)id)->lastErrno = 0;
2699 }
2700 return -1;
2701 }
2702 got = write(id->h, pBuf, cnt);
2703#endif
2704 TIMER_END;
2705 if( got<0 ){
2706 ((unixFile*)id)->lastErrno = errno;
2707 }
2708
drh308c2a52010-05-14 11:30:18 +00002709 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002710 return got;
2711}
2712
2713
2714/*
2715** Write data from a buffer into a file. Return SQLITE_OK on success
2716** or some other error code on failure.
2717*/
2718static int unixWrite(
2719 sqlite3_file *id,
2720 const void *pBuf,
2721 int amt,
2722 sqlite3_int64 offset
2723){
dan08da86a2009-08-21 17:18:03 +00002724 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002725 int wrote = 0;
2726 assert( id );
2727 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002728
dan08da86a2009-08-21 17:18:03 +00002729 /* If this is a database file (not a journal, master-journal or temp
2730 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002731#if 0
dane946c392009-08-22 11:39:46 +00002732 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002733 || offset>=PENDING_BYTE+512
2734 || offset+amt<=PENDING_BYTE
2735 );
dan7c246102010-04-12 19:00:29 +00002736#endif
drh08c6d442009-02-09 17:34:07 +00002737
drh8f941bc2009-01-14 23:03:40 +00002738#ifndef NDEBUG
2739 /* If we are doing a normal write to a database file (as opposed to
2740 ** doing a hot-journal rollback or a write to some file other than a
2741 ** normal database file) then record the fact that the database
2742 ** has changed. If the transaction counter is modified, record that
2743 ** fact too.
2744 */
dan08da86a2009-08-21 17:18:03 +00002745 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002746 pFile->dbUpdate = 1; /* The database has been modified */
2747 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002748 int rc;
drh8f941bc2009-01-14 23:03:40 +00002749 char oldCntr[4];
2750 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002751 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002752 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002753 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002754 pFile->transCntrChng = 1; /* The transaction counter has changed */
2755 }
2756 }
2757 }
2758#endif
2759
dan08da86a2009-08-21 17:18:03 +00002760 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002761 amt -= wrote;
2762 offset += wrote;
2763 pBuf = &((char*)pBuf)[wrote];
2764 }
2765 SimulateIOError(( wrote=(-1), amt=1 ));
2766 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002767
drh734c9862008-11-28 15:37:20 +00002768 if( amt>0 ){
2769 if( wrote<0 ){
2770 /* lastErrno set by seekAndWrite */
2771 return SQLITE_IOERR_WRITE;
2772 }else{
dan08da86a2009-08-21 17:18:03 +00002773 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002774 return SQLITE_FULL;
2775 }
2776 }
dan6e09d692010-07-27 18:34:15 +00002777
drh734c9862008-11-28 15:37:20 +00002778 return SQLITE_OK;
2779}
2780
2781#ifdef SQLITE_TEST
2782/*
2783** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002784** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002785*/
2786int sqlite3_sync_count = 0;
2787int sqlite3_fullsync_count = 0;
2788#endif
2789
2790/*
drh89240432009-03-25 01:06:01 +00002791** We do not trust systems to provide a working fdatasync(). Some do.
2792** Others do no. To be safe, we will stick with the (slower) fsync().
2793** If you know that your system does support fdatasync() correctly,
2794** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002795*/
drh89240432009-03-25 01:06:01 +00002796#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002797# define fdatasync fsync
2798#endif
2799
2800/*
2801** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2802** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2803** only available on Mac OS X. But that could change.
2804*/
2805#ifdef F_FULLFSYNC
2806# define HAVE_FULLFSYNC 1
2807#else
2808# define HAVE_FULLFSYNC 0
2809#endif
2810
2811
2812/*
2813** The fsync() system call does not work as advertised on many
2814** unix systems. The following procedure is an attempt to make
2815** it work better.
2816**
2817** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2818** for testing when we want to run through the test suite quickly.
2819** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2820** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2821** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002822**
2823** SQLite sets the dataOnly flag if the size of the file is unchanged.
2824** The idea behind dataOnly is that it should only write the file content
2825** to disk, not the inode. We only set dataOnly if the file size is
2826** unchanged since the file size is part of the inode. However,
2827** Ted Ts'o tells us that fdatasync() will also write the inode if the
2828** file size has changed. The only real difference between fdatasync()
2829** and fsync(), Ted tells us, is that fdatasync() will not flush the
2830** inode if the mtime or owner or other inode attributes have changed.
2831** We only care about the file size, not the other file attributes, so
2832** as far as SQLite is concerned, an fdatasync() is always adequate.
2833** So, we always use fdatasync() if it is available, regardless of
2834** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002835*/
2836static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002837 int rc;
drh734c9862008-11-28 15:37:20 +00002838
2839 /* The following "ifdef/elif/else/" block has the same structure as
2840 ** the one below. It is replicated here solely to avoid cluttering
2841 ** up the real code with the UNUSED_PARAMETER() macros.
2842 */
2843#ifdef SQLITE_NO_SYNC
2844 UNUSED_PARAMETER(fd);
2845 UNUSED_PARAMETER(fullSync);
2846 UNUSED_PARAMETER(dataOnly);
2847#elif HAVE_FULLFSYNC
2848 UNUSED_PARAMETER(dataOnly);
2849#else
2850 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002851 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002852#endif
2853
2854 /* Record the number of times that we do a normal fsync() and
2855 ** FULLSYNC. This is used during testing to verify that this procedure
2856 ** gets called with the correct arguments.
2857 */
2858#ifdef SQLITE_TEST
2859 if( fullSync ) sqlite3_fullsync_count++;
2860 sqlite3_sync_count++;
2861#endif
2862
2863 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2864 ** no-op
2865 */
2866#ifdef SQLITE_NO_SYNC
2867 rc = SQLITE_OK;
2868#elif HAVE_FULLFSYNC
2869 if( fullSync ){
2870 rc = fcntl(fd, F_FULLFSYNC, 0);
2871 }else{
2872 rc = 1;
2873 }
2874 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002875 ** It shouldn't be possible for fullfsync to fail on the local
2876 ** file system (on OSX), so failure indicates that FULLFSYNC
2877 ** isn't supported for this file system. So, attempt an fsync
2878 ** and (for now) ignore the overhead of a superfluous fcntl call.
2879 ** It'd be better to detect fullfsync support once and avoid
2880 ** the fcntl call every time sync is called.
2881 */
drh734c9862008-11-28 15:37:20 +00002882 if( rc ) rc = fsync(fd);
2883
drh7ed97b92010-01-20 13:07:21 +00002884#elif defined(__APPLE__)
2885 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2886 ** so currently we default to the macro that redefines fdatasync to fsync
2887 */
2888 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002889#else
drh0b647ff2009-03-21 14:41:04 +00002890 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002891#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002892 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002893 rc = fsync(fd);
2894 }
drh0b647ff2009-03-21 14:41:04 +00002895#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002896#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2897
2898 if( OS_VXWORKS && rc!= -1 ){
2899 rc = 0;
2900 }
chw97185482008-11-17 08:05:31 +00002901 return rc;
drhbfe66312006-10-03 17:40:40 +00002902}
2903
drh734c9862008-11-28 15:37:20 +00002904/*
2905** Make sure all writes to a particular file are committed to disk.
2906**
2907** If dataOnly==0 then both the file itself and its metadata (file
2908** size, access time, etc) are synced. If dataOnly!=0 then only the
2909** file data is synced.
2910**
2911** Under Unix, also make sure that the directory entry for the file
2912** has been created by fsync-ing the directory that contains the file.
2913** If we do not do this and we encounter a power failure, the directory
2914** entry for the journal might not exist after we reboot. The next
2915** SQLite to access the file will not know that the journal exists (because
2916** the directory entry for the journal was never created) and the transaction
2917** will not roll back - possibly leading to database corruption.
2918*/
2919static int unixSync(sqlite3_file *id, int flags){
2920 int rc;
2921 unixFile *pFile = (unixFile*)id;
2922
2923 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2924 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2925
2926 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2927 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2928 || (flags&0x0F)==SQLITE_SYNC_FULL
2929 );
2930
2931 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2932 ** line is to test that doing so does not cause any problems.
2933 */
2934 SimulateDiskfullError( return SQLITE_FULL );
2935
2936 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002937 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00002938 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2939 SimulateIOError( rc=1 );
2940 if( rc ){
2941 pFile->lastErrno = errno;
2942 return SQLITE_IOERR_FSYNC;
2943 }
2944 if( pFile->dirfd>=0 ){
2945 int err;
drh308c2a52010-05-14 11:30:18 +00002946 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2947 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00002948#ifndef SQLITE_DISABLE_DIRSYNC
2949 /* The directory sync is only attempted if full_fsync is
2950 ** turned off or unavailable. If a full_fsync occurred above,
2951 ** then the directory sync is superfluous.
2952 */
2953 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2954 /*
2955 ** We have received multiple reports of fsync() returning
2956 ** errors when applied to directories on certain file systems.
2957 ** A failed directory sync is not a big deal. So it seems
2958 ** better to ignore the error. Ticket #1657
2959 */
2960 /* pFile->lastErrno = errno; */
2961 /* return SQLITE_IOERR; */
2962 }
2963#endif
2964 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2965 if( err==0 ){ /* directory when we are done */
2966 pFile->dirfd = -1;
2967 }else{
2968 pFile->lastErrno = errno;
2969 rc = SQLITE_IOERR_DIR_CLOSE;
2970 }
2971 }
2972 return rc;
2973}
2974
2975/*
2976** Truncate an open file to a specified size
2977*/
2978static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00002979 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002980 int rc;
dan6e09d692010-07-27 18:34:15 +00002981 assert( pFile );
drh734c9862008-11-28 15:37:20 +00002982 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00002983
2984 /* If the user has configured a chunk-size for this file, truncate the
2985 ** file so that it consists of an integer number of chunks (i.e. the
2986 ** actual file size after the operation may be larger than the requested
2987 ** size).
2988 */
2989 if( pFile->szChunk ){
2990 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2991 }
2992
2993 rc = ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00002994 if( rc ){
dan6e09d692010-07-27 18:34:15 +00002995 pFile->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00002996 return SQLITE_IOERR_TRUNCATE;
2997 }else{
drh3313b142009-11-06 04:13:18 +00002998#ifndef NDEBUG
2999 /* If we are doing a normal write to a database file (as opposed to
3000 ** doing a hot-journal rollback or a write to some file other than a
3001 ** normal database file) and we truncate the file to zero length,
3002 ** that effectively updates the change counter. This might happen
3003 ** when restoring a database using the backup API from a zero-length
3004 ** source.
3005 */
dan6e09d692010-07-27 18:34:15 +00003006 if( pFile->inNormalWrite && nByte==0 ){
3007 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003008 }
3009#endif
3010
drh734c9862008-11-28 15:37:20 +00003011 return SQLITE_OK;
3012 }
3013}
3014
3015/*
3016** Determine the current size of a file in bytes
3017*/
3018static int unixFileSize(sqlite3_file *id, i64 *pSize){
3019 int rc;
3020 struct stat buf;
3021 assert( id );
3022 rc = fstat(((unixFile*)id)->h, &buf);
3023 SimulateIOError( rc=1 );
3024 if( rc!=0 ){
3025 ((unixFile*)id)->lastErrno = errno;
3026 return SQLITE_IOERR_FSTAT;
3027 }
3028 *pSize = buf.st_size;
3029
drh8af6c222010-05-14 12:43:01 +00003030 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003031 ** writes a single byte into that file in order to work around a bug
3032 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3033 ** layers, we need to report this file size as zero even though it is
3034 ** really 1. Ticket #3260.
3035 */
3036 if( *pSize==1 ) *pSize = 0;
3037
3038
3039 return SQLITE_OK;
3040}
3041
drhd2cb50b2009-01-09 21:41:17 +00003042#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003043/*
3044** Handler for proxy-locking file-control verbs. Defined below in the
3045** proxying locking division.
3046*/
3047static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003048#endif
drh715ff302008-12-03 22:32:44 +00003049
dan502019c2010-07-28 14:26:17 +00003050/*
3051** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3052** file-control operation.
3053**
3054** If the user has configured a chunk-size for this file, it could be
3055** that the file needs to be extended at this point. Otherwise, the
3056** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3057*/
3058static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3059 if( pFile->szChunk ){
3060 i64 nSize; /* Required file size */
3061 struct stat buf; /* Used to hold return values of fstat() */
3062
3063 if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
3064
3065 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3066 if( nSize>(i64)buf.st_size ){
3067#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3068 if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
3069 return SQLITE_IOERR_WRITE;
3070 }
3071#else
3072 /* If the OS does not have posix_fallocate(), fake it. First use
3073 ** ftruncate() to set the file size, then write a single byte to
3074 ** the last byte in each block within the extended region. This
3075 ** is the same technique used by glibc to implement posix_fallocate()
3076 ** on systems that do not have a real fallocate() system call.
3077 */
3078 int nBlk = buf.st_blksize; /* File-system block size */
3079 i64 iWrite; /* Next offset to write to */
3080 int nWrite; /* Return value from seekAndWrite() */
3081
3082 if( ftruncate(pFile->h, nSize) ){
3083 pFile->lastErrno = errno;
3084 return SQLITE_IOERR_TRUNCATE;
3085 }
3086 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3087 do {
3088 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3089 iWrite += nBlk;
3090 } while( nWrite==1 && iWrite<nSize );
3091 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3092#endif
3093 }
3094 }
3095
3096 return SQLITE_OK;
3097}
danielk1977ad94b582007-08-20 06:44:22 +00003098
danielk1977e3026632004-06-22 11:29:02 +00003099/*
drh9e33c2c2007-08-31 18:34:59 +00003100** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003101*/
drhcc6bb3e2007-08-31 16:11:35 +00003102static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003103 switch( op ){
3104 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003105 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003106 return SQLITE_OK;
3107 }
drh7708e972008-11-29 00:56:52 +00003108 case SQLITE_LAST_ERRNO: {
3109 *(int*)pArg = ((unixFile*)id)->lastErrno;
3110 return SQLITE_OK;
3111 }
dan6e09d692010-07-27 18:34:15 +00003112 case SQLITE_FCNTL_CHUNK_SIZE: {
3113 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003114 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003115 }
drh9ff27ec2010-05-19 19:26:05 +00003116 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003117 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003118 }
drh8f941bc2009-01-14 23:03:40 +00003119#ifndef NDEBUG
3120 /* The pager calls this method to signal that it has done
3121 ** a rollback and that the database is therefore unchanged and
3122 ** it hence it is OK for the transaction change counter to be
3123 ** unchanged.
3124 */
3125 case SQLITE_FCNTL_DB_UNCHANGED: {
3126 ((unixFile*)id)->dbUpdate = 0;
3127 return SQLITE_OK;
3128 }
3129#endif
drhd2cb50b2009-01-09 21:41:17 +00003130#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003131 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003132 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003133 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003134 }
drhd2cb50b2009-01-09 21:41:17 +00003135#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003136 }
drhcc6bb3e2007-08-31 16:11:35 +00003137 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003138}
3139
3140/*
danielk1977a3d4c882007-03-23 10:08:38 +00003141** Return the sector size in bytes of the underlying block device for
3142** the specified file. This is almost always 512 bytes, but may be
3143** larger for some devices.
3144**
3145** SQLite code assumes this function cannot fail. It also assumes that
3146** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003147** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003148** same for both.
3149*/
danielk1977397d65f2008-11-19 11:35:39 +00003150static int unixSectorSize(sqlite3_file *NotUsed){
3151 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003152 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003153}
3154
danielk197790949c22007-08-17 16:50:38 +00003155/*
danielk1977397d65f2008-11-19 11:35:39 +00003156** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003157*/
danielk1977397d65f2008-11-19 11:35:39 +00003158static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3159 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003160 return 0;
3161}
3162
drhd9e5c4f2010-05-12 18:01:39 +00003163#ifndef SQLITE_OMIT_WAL
3164
3165
3166/*
drhd91c68f2010-05-14 14:52:25 +00003167** Object used to represent an shared memory buffer.
3168**
3169** When multiple threads all reference the same wal-index, each thread
3170** has its own unixShm object, but they all point to a single instance
3171** of this unixShmNode object. In other words, each wal-index is opened
3172** only once per process.
3173**
3174** Each unixShmNode object is connected to a single unixInodeInfo object.
3175** We could coalesce this object into unixInodeInfo, but that would mean
3176** every open file that does not use shared memory (in other words, most
3177** open files) would have to carry around this extra information. So
3178** the unixInodeInfo object contains a pointer to this unixShmNode object
3179** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003180**
3181** unixMutexHeld() must be true when creating or destroying
3182** this object or while reading or writing the following fields:
3183**
3184** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003185**
3186** The following fields are read-only after the object is created:
3187**
3188** fid
3189** zFilename
3190**
drhd91c68f2010-05-14 14:52:25 +00003191** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003192** unixMutexHeld() is true when reading or writing any other field
3193** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003194*/
drhd91c68f2010-05-14 14:52:25 +00003195struct unixShmNode {
3196 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003197 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003198 char *zFilename; /* Name of the mmapped file */
3199 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003200 int szRegion; /* Size of shared-memory regions */
3201 int nRegion; /* Size of array apRegion */
3202 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003203 int nRef; /* Number of unixShm objects pointing to this */
3204 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003205#ifdef SQLITE_DEBUG
3206 u8 exclMask; /* Mask of exclusive locks held */
3207 u8 sharedMask; /* Mask of shared locks held */
3208 u8 nextShmId; /* Next available unixShm.id value */
3209#endif
3210};
3211
3212/*
drhd9e5c4f2010-05-12 18:01:39 +00003213** Structure used internally by this VFS to record the state of an
3214** open shared memory connection.
3215**
drhd91c68f2010-05-14 14:52:25 +00003216** The following fields are initialized when this object is created and
3217** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003218**
drhd91c68f2010-05-14 14:52:25 +00003219** unixShm.pFile
3220** unixShm.id
3221**
3222** All other fields are read/write. The unixShm.pFile->mutex must be held
3223** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003224*/
3225struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003226 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3227 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003228 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003229 u16 sharedMask; /* Mask of shared locks held */
3230 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003231#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003232 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003233#endif
3234};
3235
3236/*
drhd9e5c4f2010-05-12 18:01:39 +00003237** Constants used for locking
3238*/
drhbd9676c2010-06-23 17:58:38 +00003239#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003240#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003241
drhd9e5c4f2010-05-12 18:01:39 +00003242/*
drh73b64e42010-05-30 19:55:15 +00003243** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003244**
3245** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3246** otherwise.
3247*/
3248static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003249 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3250 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003251 int ofst, /* First byte of the locking range */
3252 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003253){
3254 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003255 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003256
drhd91c68f2010-05-14 14:52:25 +00003257 /* Access to the unixShmNode object is serialized by the caller */
3258 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003259
drh73b64e42010-05-30 19:55:15 +00003260 /* Shared locks never span more than one byte */
3261 assert( n==1 || lockType!=F_RDLCK );
3262
3263 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003264 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003265
drhd9e5c4f2010-05-12 18:01:39 +00003266 /* Initialize the locking parameters */
3267 memset(&f, 0, sizeof(f));
3268 f.l_type = lockType;
3269 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003270 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003271 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003272
drh73b64e42010-05-30 19:55:15 +00003273 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003274 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3275
3276 /* Update the global lock state and do debug tracing */
3277#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003278 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003279 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003280 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003281 if( rc==SQLITE_OK ){
3282 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003283 OSTRACE(("unlock %d ok", ofst));
3284 pShmNode->exclMask &= ~mask;
3285 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003286 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003287 OSTRACE(("read-lock %d ok", ofst));
3288 pShmNode->exclMask &= ~mask;
3289 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003290 }else{
3291 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003292 OSTRACE(("write-lock %d ok", ofst));
3293 pShmNode->exclMask |= mask;
3294 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003295 }
3296 }else{
3297 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003298 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003299 }else if( lockType==F_RDLCK ){
3300 OSTRACE(("read-lock failed"));
3301 }else{
3302 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003303 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003304 }
3305 }
drh20e1f082010-05-31 16:10:12 +00003306 OSTRACE((" - afterwards %03x,%03x\n",
3307 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003308 }
drhd9e5c4f2010-05-12 18:01:39 +00003309#endif
3310
3311 return rc;
3312}
3313
drhd9e5c4f2010-05-12 18:01:39 +00003314
3315/*
drhd91c68f2010-05-14 14:52:25 +00003316** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003317**
3318** This is not a VFS shared-memory method; it is a utility function called
3319** by VFS shared-memory methods.
3320*/
drhd91c68f2010-05-14 14:52:25 +00003321static void unixShmPurge(unixFile *pFd){
3322 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003323 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003324 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003325 int i;
drhd91c68f2010-05-14 14:52:25 +00003326 assert( p->pInode==pFd->pInode );
3327 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003328 for(i=0; i<p->nRegion; i++){
3329 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003330 }
dan18801912010-06-14 14:07:50 +00003331 sqlite3_free(p->apRegion);
drhd91c68f2010-05-14 14:52:25 +00003332 if( p->h>=0 ) close(p->h);
3333 p->pInode->pShmNode = 0;
3334 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003335 }
3336}
3337
3338/*
danda9fe0c2010-07-13 18:44:03 +00003339** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003340** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003341**
drh7234c6d2010-06-19 15:10:09 +00003342** The file used to implement shared-memory is in the same directory
3343** as the open database file and has the same name as the open database
3344** file with the "-shm" suffix added. For example, if the database file
3345** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003346** for shared memory will be called "/home/user1/config.db-shm".
3347**
3348** Another approach to is to use files in /dev/shm or /dev/tmp or an
3349** some other tmpfs mount. But if a file in a different directory
3350** from the database file is used, then differing access permissions
3351** or a chroot() might cause two different processes on the same
3352** database to end up using different files for shared memory -
3353** meaning that their memory would not really be shared - resulting
3354** in database corruption. Nevertheless, this tmpfs file usage
3355** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3356** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3357** option results in an incompatible build of SQLite; builds of SQLite
3358** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3359** same database file at the same time, database corruption will likely
3360** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3361** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003362**
3363** When opening a new shared-memory file, if no other instances of that
3364** file are currently open, in this process or in other processes, then
3365** the file must be truncated to zero length or have its header cleared.
3366*/
danda9fe0c2010-07-13 18:44:03 +00003367static int unixOpenSharedMemory(unixFile *pDbFd){
3368 struct unixShm *p = 0; /* The connection to be opened */
3369 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3370 int rc; /* Result code */
3371 unixInodeInfo *pInode; /* The inode of fd */
3372 char *zShmFilename; /* Name of the file used for SHM */
3373 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003374
danda9fe0c2010-07-13 18:44:03 +00003375 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003376 p = sqlite3_malloc( sizeof(*p) );
3377 if( p==0 ) return SQLITE_NOMEM;
3378 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003379 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003380
danda9fe0c2010-07-13 18:44:03 +00003381 /* Check to see if a unixShmNode object already exists. Reuse an existing
3382 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003383 */
3384 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003385 pInode = pDbFd->pInode;
3386 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003387 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003388 struct stat sStat; /* fstat() info for database file */
3389
3390 /* Call fstat() to figure out the permissions on the database file. If
3391 ** a new *-shm file is created, an attempt will be made to create it
3392 ** with the same permissions. The actual permissions the file is created
3393 ** with are subject to the current umask setting.
3394 */
3395 if( fstat(pDbFd->h, &sStat) ){
3396 rc = SQLITE_IOERR_FSTAT;
3397 goto shm_open_err;
3398 }
3399
drha4ced192010-07-15 18:32:40 +00003400#ifdef SQLITE_SHM_DIRECTORY
3401 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3402#else
drh7234c6d2010-06-19 15:10:09 +00003403 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003404#endif
drh7234c6d2010-06-19 15:10:09 +00003405 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003406 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003407 rc = SQLITE_NOMEM;
3408 goto shm_open_err;
3409 }
drhd91c68f2010-05-14 14:52:25 +00003410 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003411 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003412#ifdef SQLITE_SHM_DIRECTORY
3413 sqlite3_snprintf(nShmFilename, zShmFilename,
3414 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3415 (u32)sStat.st_ino, (u32)sStat.st_dev);
3416#else
drh7234c6d2010-06-19 15:10:09 +00003417 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003418#endif
drhd91c68f2010-05-14 14:52:25 +00003419 pShmNode->h = -1;
3420 pDbFd->pInode->pShmNode = pShmNode;
3421 pShmNode->pInode = pDbFd->pInode;
3422 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3423 if( pShmNode->mutex==0 ){
3424 rc = SQLITE_NOMEM;
3425 goto shm_open_err;
3426 }
drhd9e5c4f2010-05-12 18:01:39 +00003427
danddb0ac42010-07-14 14:48:58 +00003428 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003429 if( pShmNode->h<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003430 rc = SQLITE_CANTOPEN_BKPT;
3431 goto shm_open_err;
3432 }
3433
drhd9e5c4f2010-05-12 18:01:39 +00003434 /* Check to see if another process is holding the dead-man switch.
3435 ** If not, truncate the file to zero length.
3436 */
drhd91c68f2010-05-14 14:52:25 +00003437 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003438 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhd91c68f2010-05-14 14:52:25 +00003439 if( ftruncate(pShmNode->h, 0) ){
drhaab4c022010-06-02 14:45:51 +00003440 rc = SQLITE_IOERR_SHMOPEN;
drhd9e5c4f2010-05-12 18:01:39 +00003441 }
3442 }
3443 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003444 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003445 }
3446 if( rc ) goto shm_open_err;
3447 }
3448
drhd91c68f2010-05-14 14:52:25 +00003449 /* Make the new connection a child of the unixShmNode */
3450 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003451#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003452 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003453#endif
drhd91c68f2010-05-14 14:52:25 +00003454 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003455 pDbFd->pShm = p;
3456 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003457
3458 /* The reference count on pShmNode has already been incremented under
3459 ** the cover of the unixEnterMutex() mutex and the pointer from the
3460 ** new (struct unixShm) object to the pShmNode has been set. All that is
3461 ** left to do is to link the new object into the linked list starting
3462 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3463 ** mutex.
3464 */
3465 sqlite3_mutex_enter(pShmNode->mutex);
3466 p->pNext = pShmNode->pFirst;
3467 pShmNode->pFirst = p;
3468 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003469 return SQLITE_OK;
3470
3471 /* Jump here on any error */
3472shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003473 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003474 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003475 unixLeaveMutex();
3476 return rc;
3477}
3478
3479/*
danda9fe0c2010-07-13 18:44:03 +00003480** This function is called to obtain a pointer to region iRegion of the
3481** shared-memory associated with the database file fd. Shared-memory regions
3482** are numbered starting from zero. Each shared-memory region is szRegion
3483** bytes in size.
3484**
3485** If an error occurs, an error code is returned and *pp is set to NULL.
3486**
3487** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3488** region has not been allocated (by any client, including one running in a
3489** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3490** bExtend is non-zero and the requested shared-memory region has not yet
3491** been allocated, it is allocated by this function.
3492**
3493** If the shared-memory region has already been allocated or is allocated by
3494** this call as described above, then it is mapped into this processes
3495** address space (if it is not already), *pp is set to point to the mapped
3496** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003497*/
danda9fe0c2010-07-13 18:44:03 +00003498static int unixShmMap(
3499 sqlite3_file *fd, /* Handle open on database file */
3500 int iRegion, /* Region to retrieve */
3501 int szRegion, /* Size of regions */
3502 int bExtend, /* True to extend file if necessary */
3503 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003504){
danda9fe0c2010-07-13 18:44:03 +00003505 unixFile *pDbFd = (unixFile*)fd;
3506 unixShm *p;
3507 unixShmNode *pShmNode;
3508 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003509
danda9fe0c2010-07-13 18:44:03 +00003510 /* If the shared-memory file has not yet been opened, open it now. */
3511 if( pDbFd->pShm==0 ){
3512 rc = unixOpenSharedMemory(pDbFd);
3513 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003514 }
drhd9e5c4f2010-05-12 18:01:39 +00003515
danda9fe0c2010-07-13 18:44:03 +00003516 p = pDbFd->pShm;
3517 pShmNode = p->pShmNode;
3518 sqlite3_mutex_enter(pShmNode->mutex);
3519 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3520
3521 if( pShmNode->nRegion<=iRegion ){
3522 char **apNew; /* New apRegion[] array */
3523 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3524 struct stat sStat; /* Used by fstat() */
3525
3526 pShmNode->szRegion = szRegion;
3527
3528 /* The requested region is not mapped into this processes address space.
3529 ** Check to see if it has been allocated (i.e. if the wal-index file is
3530 ** large enough to contain the requested region).
3531 */
3532 if( fstat(pShmNode->h, &sStat) ){
3533 rc = SQLITE_IOERR_SHMSIZE;
3534 goto shmpage_out;
3535 }
3536
3537 if( sStat.st_size<nByte ){
3538 /* The requested memory region does not exist. If bExtend is set to
3539 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3540 **
3541 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3542 ** the requested memory region.
3543 */
3544 if( !bExtend ) goto shmpage_out;
3545 if( ftruncate(pShmNode->h, nByte) ){
3546 rc = SQLITE_IOERR_SHMSIZE;
3547 goto shmpage_out;
3548 }
3549 }
3550
3551 /* Map the requested memory region into this processes address space. */
3552 apNew = (char **)sqlite3_realloc(
3553 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3554 );
3555 if( !apNew ){
3556 rc = SQLITE_IOERR_NOMEM;
3557 goto shmpage_out;
3558 }
3559 pShmNode->apRegion = apNew;
3560 while(pShmNode->nRegion<=iRegion){
3561 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3562 MAP_SHARED, pShmNode->h, iRegion*szRegion
3563 );
3564 if( pMem==MAP_FAILED ){
3565 rc = SQLITE_IOERR;
3566 goto shmpage_out;
3567 }
3568 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3569 pShmNode->nRegion++;
3570 }
3571 }
3572
3573shmpage_out:
3574 if( pShmNode->nRegion>iRegion ){
3575 *pp = pShmNode->apRegion[iRegion];
3576 }else{
3577 *pp = 0;
3578 }
3579 sqlite3_mutex_leave(pShmNode->mutex);
3580 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003581}
3582
3583/*
drhd9e5c4f2010-05-12 18:01:39 +00003584** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003585**
3586** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3587** different here than in posix. In xShmLock(), one can go from unlocked
3588** to shared and back or from unlocked to exclusive and back. But one may
3589** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003590*/
3591static int unixShmLock(
3592 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003593 int ofst, /* First lock to acquire or release */
3594 int n, /* Number of locks to acquire or release */
3595 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003596){
drh73b64e42010-05-30 19:55:15 +00003597 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3598 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3599 unixShm *pX; /* For looping over all siblings */
3600 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3601 int rc = SQLITE_OK; /* Result code */
3602 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003603
drhd91c68f2010-05-14 14:52:25 +00003604 assert( pShmNode==pDbFd->pInode->pShmNode );
3605 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003606 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003607 assert( n>=1 );
3608 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3609 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3610 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3611 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3612 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003613
drhc99597c2010-05-31 01:41:15 +00003614 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003615 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003616 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003617 if( flags & SQLITE_SHM_UNLOCK ){
3618 u16 allMask = 0; /* Mask of locks held by siblings */
3619
3620 /* See if any siblings hold this same lock */
3621 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3622 if( pX==p ) continue;
3623 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3624 allMask |= pX->sharedMask;
3625 }
3626
3627 /* Unlock the system-level locks */
3628 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003629 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003630 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003631 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003632 }
drh73b64e42010-05-30 19:55:15 +00003633
3634 /* Undo the local locks */
3635 if( rc==SQLITE_OK ){
3636 p->exclMask &= ~mask;
3637 p->sharedMask &= ~mask;
3638 }
3639 }else if( flags & SQLITE_SHM_SHARED ){
3640 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3641
3642 /* Find out which shared locks are already held by sibling connections.
3643 ** If any sibling already holds an exclusive lock, go ahead and return
3644 ** SQLITE_BUSY.
3645 */
3646 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003647 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003648 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003649 break;
3650 }
3651 allShared |= pX->sharedMask;
3652 }
3653
3654 /* Get shared locks at the system level, if necessary */
3655 if( rc==SQLITE_OK ){
3656 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003657 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003658 }else{
drh73b64e42010-05-30 19:55:15 +00003659 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003660 }
drhd9e5c4f2010-05-12 18:01:39 +00003661 }
drh73b64e42010-05-30 19:55:15 +00003662
3663 /* Get the local shared locks */
3664 if( rc==SQLITE_OK ){
3665 p->sharedMask |= mask;
3666 }
3667 }else{
3668 /* Make sure no sibling connections hold locks that will block this
3669 ** lock. If any do, return SQLITE_BUSY right away.
3670 */
3671 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003672 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3673 rc = SQLITE_BUSY;
3674 break;
3675 }
3676 }
3677
3678 /* Get the exclusive locks at the system level. Then if successful
3679 ** also mark the local connection as being locked.
3680 */
3681 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003682 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003683 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003684 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003685 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003686 }
drhd9e5c4f2010-05-12 18:01:39 +00003687 }
3688 }
drhd91c68f2010-05-14 14:52:25 +00003689 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003690 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3691 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003692 return rc;
3693}
3694
drh286a2882010-05-20 23:51:06 +00003695/*
3696** Implement a memory barrier or memory fence on shared memory.
3697**
3698** All loads and stores begun before the barrier must complete before
3699** any load or store begun after the barrier.
3700*/
3701static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003702 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003703){
drhff828942010-06-26 21:34:06 +00003704 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003705 unixEnterMutex();
3706 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003707}
3708
dan18801912010-06-14 14:07:50 +00003709/*
danda9fe0c2010-07-13 18:44:03 +00003710** Close a connection to shared-memory. Delete the underlying
3711** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003712**
3713** If there is no shared memory associated with the connection then this
3714** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003715*/
danda9fe0c2010-07-13 18:44:03 +00003716static int unixShmUnmap(
3717 sqlite3_file *fd, /* The underlying database file */
3718 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003719){
danda9fe0c2010-07-13 18:44:03 +00003720 unixShm *p; /* The connection to be closed */
3721 unixShmNode *pShmNode; /* The underlying shared-memory file */
3722 unixShm **pp; /* For looping over sibling connections */
3723 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003724
danda9fe0c2010-07-13 18:44:03 +00003725 pDbFd = (unixFile*)fd;
3726 p = pDbFd->pShm;
3727 if( p==0 ) return SQLITE_OK;
3728 pShmNode = p->pShmNode;
3729
3730 assert( pShmNode==pDbFd->pInode->pShmNode );
3731 assert( pShmNode->pInode==pDbFd->pInode );
3732
3733 /* Remove connection p from the set of connections associated
3734 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003735 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003736 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3737 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003738
danda9fe0c2010-07-13 18:44:03 +00003739 /* Free the connection p */
3740 sqlite3_free(p);
3741 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003742 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003743
3744 /* If pShmNode->nRef has reached 0, then close the underlying
3745 ** shared-memory file, too */
3746 unixEnterMutex();
3747 assert( pShmNode->nRef>0 );
3748 pShmNode->nRef--;
3749 if( pShmNode->nRef==0 ){
3750 if( deleteFlag ) unlink(pShmNode->zFilename);
3751 unixShmPurge(pDbFd);
3752 }
3753 unixLeaveMutex();
3754
3755 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003756}
drh286a2882010-05-20 23:51:06 +00003757
danda9fe0c2010-07-13 18:44:03 +00003758
drhd9e5c4f2010-05-12 18:01:39 +00003759#else
drh6b017cc2010-06-14 18:01:46 +00003760# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003761# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003762# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003763# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003764#endif /* #ifndef SQLITE_OMIT_WAL */
3765
drh734c9862008-11-28 15:37:20 +00003766/*
3767** Here ends the implementation of all sqlite3_file methods.
3768**
3769********************** End sqlite3_file Methods *******************************
3770******************************************************************************/
3771
3772/*
drh6b9d6dd2008-12-03 19:34:47 +00003773** This division contains definitions of sqlite3_io_methods objects that
3774** implement various file locking strategies. It also contains definitions
3775** of "finder" functions. A finder-function is used to locate the appropriate
3776** sqlite3_io_methods object for a particular database file. The pAppData
3777** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3778** the correct finder-function for that VFS.
3779**
3780** Most finder functions return a pointer to a fixed sqlite3_io_methods
3781** object. The only interesting finder-function is autolockIoFinder, which
3782** looks at the filesystem type and tries to guess the best locking
3783** strategy from that.
3784**
drh1875f7a2008-12-08 18:19:17 +00003785** For finder-funtion F, two objects are created:
3786**
3787** (1) The real finder-function named "FImpt()".
3788**
dane946c392009-08-22 11:39:46 +00003789** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003790**
3791**
3792** A pointer to the F pointer is used as the pAppData value for VFS
3793** objects. We have to do this instead of letting pAppData point
3794** directly at the finder-function since C90 rules prevent a void*
3795** from be cast into a function pointer.
3796**
drh6b9d6dd2008-12-03 19:34:47 +00003797**
drh7708e972008-11-29 00:56:52 +00003798** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003799**
drh7708e972008-11-29 00:56:52 +00003800** * A constant sqlite3_io_methods object call METHOD that has locking
3801** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3802**
3803** * An I/O method finder function called FINDER that returns a pointer
3804** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003805*/
drhd9e5c4f2010-05-12 18:01:39 +00003806#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003807static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003808 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003809 CLOSE, /* xClose */ \
3810 unixRead, /* xRead */ \
3811 unixWrite, /* xWrite */ \
3812 unixTruncate, /* xTruncate */ \
3813 unixSync, /* xSync */ \
3814 unixFileSize, /* xFileSize */ \
3815 LOCK, /* xLock */ \
3816 UNLOCK, /* xUnlock */ \
3817 CKLOCK, /* xCheckReservedLock */ \
3818 unixFileControl, /* xFileControl */ \
3819 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003820 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003821 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00003822 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003823 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00003824 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00003825}; \
drh0c2694b2009-09-03 16:23:44 +00003826static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3827 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003828 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003829} \
drh0c2694b2009-09-03 16:23:44 +00003830static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003831 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003832
3833/*
3834** Here are all of the sqlite3_io_methods objects for each of the
3835** locking strategies. Functions that return pointers to these methods
3836** are also created.
3837*/
3838IOMETHODS(
3839 posixIoFinder, /* Finder function name */
3840 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003841 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00003842 unixClose, /* xClose method */
3843 unixLock, /* xLock method */
3844 unixUnlock, /* xUnlock method */
3845 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003846)
drh7708e972008-11-29 00:56:52 +00003847IOMETHODS(
3848 nolockIoFinder, /* Finder function name */
3849 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003850 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003851 nolockClose, /* xClose method */
3852 nolockLock, /* xLock method */
3853 nolockUnlock, /* xUnlock method */
3854 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003855)
drh7708e972008-11-29 00:56:52 +00003856IOMETHODS(
3857 dotlockIoFinder, /* Finder function name */
3858 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003859 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003860 dotlockClose, /* xClose method */
3861 dotlockLock, /* xLock method */
3862 dotlockUnlock, /* xUnlock method */
3863 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003864)
drh7708e972008-11-29 00:56:52 +00003865
chw78a13182009-04-07 05:35:03 +00003866#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003867IOMETHODS(
3868 flockIoFinder, /* Finder function name */
3869 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003870 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003871 flockClose, /* xClose method */
3872 flockLock, /* xLock method */
3873 flockUnlock, /* xUnlock method */
3874 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003875)
drh7708e972008-11-29 00:56:52 +00003876#endif
3877
drh6c7d5c52008-11-21 20:32:33 +00003878#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003879IOMETHODS(
3880 semIoFinder, /* Finder function name */
3881 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003882 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003883 semClose, /* xClose method */
3884 semLock, /* xLock method */
3885 semUnlock, /* xUnlock method */
3886 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003887)
aswiftaebf4132008-11-21 00:10:35 +00003888#endif
drh7708e972008-11-29 00:56:52 +00003889
drhd2cb50b2009-01-09 21:41:17 +00003890#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003891IOMETHODS(
3892 afpIoFinder, /* Finder function name */
3893 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003894 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003895 afpClose, /* xClose method */
3896 afpLock, /* xLock method */
3897 afpUnlock, /* xUnlock method */
3898 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003899)
drh715ff302008-12-03 22:32:44 +00003900#endif
3901
3902/*
3903** The proxy locking method is a "super-method" in the sense that it
3904** opens secondary file descriptors for the conch and lock files and
3905** it uses proxy, dot-file, AFP, and flock() locking methods on those
3906** secondary files. For this reason, the division that implements
3907** proxy locking is located much further down in the file. But we need
3908** to go ahead and define the sqlite3_io_methods and finder function
3909** for proxy locking here. So we forward declare the I/O methods.
3910*/
drhd2cb50b2009-01-09 21:41:17 +00003911#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003912static int proxyClose(sqlite3_file*);
3913static int proxyLock(sqlite3_file*, int);
3914static int proxyUnlock(sqlite3_file*, int);
3915static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003916IOMETHODS(
3917 proxyIoFinder, /* Finder function name */
3918 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003919 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003920 proxyClose, /* xClose method */
3921 proxyLock, /* xLock method */
3922 proxyUnlock, /* xUnlock method */
3923 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003924)
aswiftaebf4132008-11-21 00:10:35 +00003925#endif
drh7708e972008-11-29 00:56:52 +00003926
drh7ed97b92010-01-20 13:07:21 +00003927/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3928#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3929IOMETHODS(
3930 nfsIoFinder, /* Finder function name */
3931 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003932 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00003933 unixClose, /* xClose method */
3934 unixLock, /* xLock method */
3935 nfsUnlock, /* xUnlock method */
3936 unixCheckReservedLock /* xCheckReservedLock method */
3937)
3938#endif
drh7708e972008-11-29 00:56:52 +00003939
drhd2cb50b2009-01-09 21:41:17 +00003940#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003941/*
drh6b9d6dd2008-12-03 19:34:47 +00003942** This "finder" function attempts to determine the best locking strategy
3943** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003944** object that implements that strategy.
3945**
3946** This is for MacOSX only.
3947*/
drh1875f7a2008-12-08 18:19:17 +00003948static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003949 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003950 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003951){
3952 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003953 const char *zFilesystem; /* Filesystem type name */
3954 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003955 } aMap[] = {
3956 { "hfs", &posixIoMethods },
3957 { "ufs", &posixIoMethods },
3958 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003959 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003960 { "webdav", &nolockIoMethods },
3961 { 0, 0 }
3962 };
3963 int i;
3964 struct statfs fsInfo;
3965 struct flock lockInfo;
3966
3967 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003968 /* If filePath==NULL that means we are dealing with a transient file
3969 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003970 return &nolockIoMethods;
3971 }
3972 if( statfs(filePath, &fsInfo) != -1 ){
3973 if( fsInfo.f_flags & MNT_RDONLY ){
3974 return &nolockIoMethods;
3975 }
3976 for(i=0; aMap[i].zFilesystem; i++){
3977 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3978 return aMap[i].pMethods;
3979 }
3980 }
3981 }
3982
3983 /* Default case. Handles, amongst others, "nfs".
3984 ** Test byte-range lock using fcntl(). If the call succeeds,
3985 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003986 */
drh7708e972008-11-29 00:56:52 +00003987 lockInfo.l_len = 1;
3988 lockInfo.l_start = 0;
3989 lockInfo.l_whence = SEEK_SET;
3990 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003991 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003992 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3993 return &nfsIoMethods;
3994 } else {
3995 return &posixIoMethods;
3996 }
drh7708e972008-11-29 00:56:52 +00003997 }else{
3998 return &dotlockIoMethods;
3999 }
4000}
drh0c2694b2009-09-03 16:23:44 +00004001static const sqlite3_io_methods
4002 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004003
drhd2cb50b2009-01-09 21:41:17 +00004004#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004005
chw78a13182009-04-07 05:35:03 +00004006#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4007/*
4008** This "finder" function attempts to determine the best locking strategy
4009** for the database file "filePath". It then returns the sqlite3_io_methods
4010** object that implements that strategy.
4011**
4012** This is for VXWorks only.
4013*/
4014static const sqlite3_io_methods *autolockIoFinderImpl(
4015 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004016 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004017){
4018 struct flock lockInfo;
4019
4020 if( !filePath ){
4021 /* If filePath==NULL that means we are dealing with a transient file
4022 ** that does not need to be locked. */
4023 return &nolockIoMethods;
4024 }
4025
4026 /* Test if fcntl() is supported and use POSIX style locks.
4027 ** Otherwise fall back to the named semaphore method.
4028 */
4029 lockInfo.l_len = 1;
4030 lockInfo.l_start = 0;
4031 lockInfo.l_whence = SEEK_SET;
4032 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004033 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004034 return &posixIoMethods;
4035 }else{
4036 return &semIoMethods;
4037 }
4038}
drh0c2694b2009-09-03 16:23:44 +00004039static const sqlite3_io_methods
4040 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004041
4042#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4043
drh7708e972008-11-29 00:56:52 +00004044/*
4045** An abstract type for a pointer to a IO method finder function:
4046*/
drh0c2694b2009-09-03 16:23:44 +00004047typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004048
aswiftaebf4132008-11-21 00:10:35 +00004049
drh734c9862008-11-28 15:37:20 +00004050/****************************************************************************
4051**************************** sqlite3_vfs methods ****************************
4052**
4053** This division contains the implementation of methods on the
4054** sqlite3_vfs object.
4055*/
4056
danielk1977a3d4c882007-03-23 10:08:38 +00004057/*
danielk1977e339d652008-06-28 11:23:00 +00004058** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004059*/
4060static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004061 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004062 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004063 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004064 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004065 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004066 int noLock, /* Omit locking if true */
4067 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004068){
drh7708e972008-11-29 00:56:52 +00004069 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004070 unixFile *pNew = (unixFile *)pId;
4071 int rc = SQLITE_OK;
4072
drh8af6c222010-05-14 12:43:01 +00004073 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004074
dane946c392009-08-22 11:39:46 +00004075 /* Parameter isDelete is only used on vxworks. Express this explicitly
4076 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004077 */
drh7708e972008-11-29 00:56:52 +00004078 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004079
drh308c2a52010-05-14 11:30:18 +00004080 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004081 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004082 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004083 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004084 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
4085 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004086
drh6c7d5c52008-11-21 20:32:33 +00004087#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004088 pNew->pId = vxworksFindFileId(zFilename);
4089 if( pNew->pId==0 ){
4090 noLock = 1;
4091 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004092 }
4093#endif
4094
drhda0e7682008-07-30 15:27:54 +00004095 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004096 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004097 }else{
drh0c2694b2009-09-03 16:23:44 +00004098 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004099#if SQLITE_ENABLE_LOCKING_STYLE
4100 /* Cache zFilename in the locking context (AFP and dotlock override) for
4101 ** proxyLock activation is possible (remote proxy is based on db name)
4102 ** zFilename remains valid until file is closed, to support */
4103 pNew->lockingContext = (void*)zFilename;
4104#endif
drhda0e7682008-07-30 15:27:54 +00004105 }
danielk1977e339d652008-06-28 11:23:00 +00004106
drh7ed97b92010-01-20 13:07:21 +00004107 if( pLockingStyle == &posixIoMethods
4108#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4109 || pLockingStyle == &nfsIoMethods
4110#endif
4111 ){
drh7708e972008-11-29 00:56:52 +00004112 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004113 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004114 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004115 /* If an error occured in findInodeInfo(), close the file descriptor
4116 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004117 ** in two scenarios:
4118 **
4119 ** (a) A call to fstat() failed.
4120 ** (b) A malloc failed.
4121 **
4122 ** Scenario (b) may only occur if the process is holding no other
4123 ** file descriptors open on the same file. If there were other file
4124 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004125 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004126 ** handle h - as it is guaranteed that no posix locks will be released
4127 ** by doing so.
4128 **
4129 ** If scenario (a) caused the error then things are not so safe. The
4130 ** implicit assumption here is that if fstat() fails, things are in
4131 ** such bad shape that dropping a lock or two doesn't matter much.
4132 */
4133 close(h);
4134 h = -1;
4135 }
drh7708e972008-11-29 00:56:52 +00004136 unixLeaveMutex();
4137 }
danielk1977e339d652008-06-28 11:23:00 +00004138
drhd2cb50b2009-01-09 21:41:17 +00004139#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004140 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004141 /* AFP locking uses the file path so it needs to be included in
4142 ** the afpLockingContext.
4143 */
4144 afpLockingContext *pCtx;
4145 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4146 if( pCtx==0 ){
4147 rc = SQLITE_NOMEM;
4148 }else{
4149 /* NB: zFilename exists and remains valid until the file is closed
4150 ** according to requirement F11141. So we do not need to make a
4151 ** copy of the filename. */
4152 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004153 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004154 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004155 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004156 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004157 if( rc!=SQLITE_OK ){
4158 sqlite3_free(pNew->lockingContext);
4159 close(h);
4160 h = -1;
4161 }
drh7708e972008-11-29 00:56:52 +00004162 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004163 }
drh7708e972008-11-29 00:56:52 +00004164 }
4165#endif
danielk1977e339d652008-06-28 11:23:00 +00004166
drh7708e972008-11-29 00:56:52 +00004167 else if( pLockingStyle == &dotlockIoMethods ){
4168 /* Dotfile locking uses the file path so it needs to be included in
4169 ** the dotlockLockingContext
4170 */
4171 char *zLockFile;
4172 int nFilename;
drhea678832008-12-10 19:26:22 +00004173 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004174 zLockFile = (char *)sqlite3_malloc(nFilename);
4175 if( zLockFile==0 ){
4176 rc = SQLITE_NOMEM;
4177 }else{
4178 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004179 }
drh7708e972008-11-29 00:56:52 +00004180 pNew->lockingContext = zLockFile;
4181 }
danielk1977e339d652008-06-28 11:23:00 +00004182
drh6c7d5c52008-11-21 20:32:33 +00004183#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004184 else if( pLockingStyle == &semIoMethods ){
4185 /* Named semaphore locking uses the file path so it needs to be
4186 ** included in the semLockingContext
4187 */
4188 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004189 rc = findInodeInfo(pNew, &pNew->pInode);
4190 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4191 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004192 int n;
drh2238dcc2009-08-27 17:56:20 +00004193 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004194 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004195 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004196 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004197 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4198 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004199 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004200 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004201 }
chw97185482008-11-17 08:05:31 +00004202 }
drh7708e972008-11-29 00:56:52 +00004203 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004204 }
drh7708e972008-11-29 00:56:52 +00004205#endif
aswift5b1a2562008-08-22 00:22:35 +00004206
4207 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004208#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004209 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004210 if( h>=0 ) close(h);
4211 h = -1;
chw97185482008-11-17 08:05:31 +00004212 unlink(zFilename);
4213 isDelete = 0;
4214 }
4215 pNew->isDelete = isDelete;
4216#endif
danielk1977e339d652008-06-28 11:23:00 +00004217 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004218 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004219 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004220 }else{
drh7708e972008-11-29 00:56:52 +00004221 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004222 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004223 }
danielk1977e339d652008-06-28 11:23:00 +00004224 return rc;
drh054889e2005-11-30 03:20:31 +00004225}
drh9c06c952005-11-26 00:25:00 +00004226
danielk1977ad94b582007-08-20 06:44:22 +00004227/*
4228** Open a file descriptor to the directory containing file zFilename.
4229** If successful, *pFd is set to the opened file descriptor and
4230** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4231** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4232** value.
4233**
4234** If SQLITE_OK is returned, the caller is responsible for closing
4235** the file descriptor *pFd using close().
4236*/
danielk1977fee2d252007-08-18 10:59:19 +00004237static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004238 int ii;
drh777b17a2007-09-20 10:02:54 +00004239 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004240 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004241
drh153c62c2007-08-24 03:51:33 +00004242 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004243 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004244 if( ii>0 ){
4245 zDirname[ii] = '\0';
4246 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004247 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004248#ifdef FD_CLOEXEC
4249 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4250#endif
drh308c2a52010-05-14 11:30:18 +00004251 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004252 }
4253 }
danielk1977fee2d252007-08-18 10:59:19 +00004254 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004255 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004256}
4257
danielk1977b4b47412007-08-17 15:53:36 +00004258/*
drh8b3cf822010-06-01 21:02:51 +00004259** Return the name of a directory in which to put temporary files.
4260** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004261*/
drh7234c6d2010-06-19 15:10:09 +00004262static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004263 static const char *azDirs[] = {
4264 0,
aswiftaebf4132008-11-21 00:10:35 +00004265 0,
danielk197717b90b52008-06-06 11:11:25 +00004266 "/var/tmp",
4267 "/usr/tmp",
4268 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004269 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004270 };
drh8b3cf822010-06-01 21:02:51 +00004271 unsigned int i;
4272 struct stat buf;
4273 const char *zDir = 0;
4274
4275 azDirs[0] = sqlite3_temp_directory;
4276 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004277 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004278 if( zDir==0 ) continue;
4279 if( stat(zDir, &buf) ) continue;
4280 if( !S_ISDIR(buf.st_mode) ) continue;
drh7234c6d2010-06-19 15:10:09 +00004281 if( access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004282 break;
4283 }
4284 return zDir;
4285}
4286
4287/*
4288** Create a temporary file name in zBuf. zBuf must be allocated
4289** by the calling process and must be big enough to hold at least
4290** pVfs->mxPathname bytes.
4291*/
4292static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004293 static const unsigned char zChars[] =
4294 "abcdefghijklmnopqrstuvwxyz"
4295 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4296 "0123456789";
drh41022642008-11-21 00:24:42 +00004297 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004298 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004299
4300 /* It's odd to simulate an io-error here, but really this is just
4301 ** using the io-error infrastructure to test that SQLite handles this
4302 ** function failing.
4303 */
4304 SimulateIOError( return SQLITE_IOERR );
4305
drh7234c6d2010-06-19 15:10:09 +00004306 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004307 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004308
4309 /* Check that the output buffer is large enough for the temporary file
4310 ** name. If it is not, return SQLITE_ERROR.
4311 */
danielk197700e13612008-11-17 19:18:54 +00004312 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004313 return SQLITE_ERROR;
4314 }
4315
4316 do{
4317 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004318 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004319 sqlite3_randomness(15, &zBuf[j]);
4320 for(i=0; i<15; i++, j++){
4321 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4322 }
4323 zBuf[j] = 0;
4324 }while( access(zBuf,0)==0 );
4325 return SQLITE_OK;
4326}
4327
drhd2cb50b2009-01-09 21:41:17 +00004328#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004329/*
4330** Routine to transform a unixFile into a proxy-locking unixFile.
4331** Implementation in the proxy-lock division, but used by unixOpen()
4332** if SQLITE_PREFER_PROXY_LOCKING is defined.
4333*/
4334static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004335#endif
drhc66d5b62008-12-03 22:48:32 +00004336
dan08da86a2009-08-21 17:18:03 +00004337/*
4338** Search for an unused file descriptor that was opened on the database
4339** file (not a journal or master-journal file) identified by pathname
4340** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4341** argument to this function.
4342**
4343** Such a file descriptor may exist if a database connection was closed
4344** but the associated file descriptor could not be closed because some
4345** other file descriptor open on the same file is holding a file-lock.
4346** Refer to comments in the unixClose() function and the lengthy comment
4347** describing "Posix Advisory Locking" at the start of this file for
4348** further details. Also, ticket #4018.
4349**
4350** If a suitable file descriptor is found, then it is returned. If no
4351** such file descriptor is located, -1 is returned.
4352*/
dane946c392009-08-22 11:39:46 +00004353static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4354 UnixUnusedFd *pUnused = 0;
4355
4356 /* Do not search for an unused file descriptor on vxworks. Not because
4357 ** vxworks would not benefit from the change (it might, we're not sure),
4358 ** but because no way to test it is currently available. It is better
4359 ** not to risk breaking vxworks support for the sake of such an obscure
4360 ** feature. */
4361#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004362 struct stat sStat; /* Results of stat() call */
4363
4364 /* A stat() call may fail for various reasons. If this happens, it is
4365 ** almost certain that an open() call on the same path will also fail.
4366 ** For this reason, if an error occurs in the stat() call here, it is
4367 ** ignored and -1 is returned. The caller will try to open a new file
4368 ** descriptor on the same path, fail, and return an error to SQLite.
4369 **
4370 ** Even if a subsequent open() call does succeed, the consequences of
4371 ** not searching for a resusable file descriptor are not dire. */
4372 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004373 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004374
4375 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004376 pInode = inodeList;
4377 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4378 || pInode->fileId.ino!=sStat.st_ino) ){
4379 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004380 }
drh8af6c222010-05-14 12:43:01 +00004381 if( pInode ){
dane946c392009-08-22 11:39:46 +00004382 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004383 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004384 pUnused = *pp;
4385 if( pUnused ){
4386 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004387 }
4388 }
4389 unixLeaveMutex();
4390 }
dane946c392009-08-22 11:39:46 +00004391#endif /* if !OS_VXWORKS */
4392 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004393}
danielk197717b90b52008-06-06 11:11:25 +00004394
4395/*
danddb0ac42010-07-14 14:48:58 +00004396** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004397** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004398** and a value suitable for passing as the third argument to open(2) is
4399** written to *pMode. If an IO error occurs, an SQLite error code is
4400** returned and the value of *pMode is not modified.
4401**
4402** If the file being opened is a temporary file, it is always created with
4403** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004404** is a database or master journal file, it is created with the permissions
4405** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004406**
drh8ab58662010-07-15 18:38:39 +00004407** Finally, if the file being opened is a WAL or regular journal file, then
4408** this function queries the file-system for the permissions on the
4409** corresponding database file and sets *pMode to this value. Whenever
4410** possible, WAL and journal files are created using the same permissions
4411** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004412*/
4413static int findCreateFileMode(
4414 const char *zPath, /* Path of file (possibly) being created */
4415 int flags, /* Flags passed as 4th argument to xOpen() */
4416 mode_t *pMode /* OUT: Permissions to open file with */
4417){
4418 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004419 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004420 char zDb[MAX_PATHNAME+1]; /* Database file path */
4421 int nDb; /* Number of valid bytes in zDb */
4422 struct stat sStat; /* Output of stat() on database file */
4423
drh8ab58662010-07-15 18:38:39 +00004424 nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
danddb0ac42010-07-14 14:48:58 +00004425 memcpy(zDb, zPath, nDb);
4426 zDb[nDb] = '\0';
4427 if( 0==stat(zDb, &sStat) ){
4428 *pMode = sStat.st_mode & 0777;
4429 }else{
4430 rc = SQLITE_IOERR_FSTAT;
4431 }
4432 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4433 *pMode = 0600;
4434 }else{
4435 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4436 }
4437 return rc;
4438}
4439
4440/*
danielk1977ad94b582007-08-20 06:44:22 +00004441** Open the file zPath.
4442**
danielk1977b4b47412007-08-17 15:53:36 +00004443** Previously, the SQLite OS layer used three functions in place of this
4444** one:
4445**
4446** sqlite3OsOpenReadWrite();
4447** sqlite3OsOpenReadOnly();
4448** sqlite3OsOpenExclusive();
4449**
4450** These calls correspond to the following combinations of flags:
4451**
4452** ReadWrite() -> (READWRITE | CREATE)
4453** ReadOnly() -> (READONLY)
4454** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4455**
4456** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4457** true, the file was configured to be automatically deleted when the
4458** file handle closed. To achieve the same effect using this new
4459** interface, add the DELETEONCLOSE flag to those specified above for
4460** OpenExclusive().
4461*/
4462static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004463 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4464 const char *zPath, /* Pathname of file to be opened */
4465 sqlite3_file *pFile, /* The file descriptor to be filled in */
4466 int flags, /* Input flags to control the opening */
4467 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004468){
dan08da86a2009-08-21 17:18:03 +00004469 unixFile *p = (unixFile *)pFile;
4470 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004471 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004472 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004473 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004474 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004475 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004476
4477 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4478 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4479 int isCreate = (flags & SQLITE_OPEN_CREATE);
4480 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4481 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004482#if SQLITE_ENABLE_LOCKING_STYLE
4483 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4484#endif
danielk1977b4b47412007-08-17 15:53:36 +00004485
danielk1977fee2d252007-08-18 10:59:19 +00004486 /* If creating a master or main-file journal, this function will open
4487 ** a file-descriptor on the directory too. The first time unixSync()
4488 ** is called the directory file descriptor will be fsync()ed and close()d.
4489 */
danddb0ac42010-07-14 14:48:58 +00004490 int isOpenDirectory = (isCreate && (
4491 eType==SQLITE_OPEN_MASTER_JOURNAL
4492 || eType==SQLITE_OPEN_MAIN_JOURNAL
4493 || eType==SQLITE_OPEN_WAL
4494 ));
danielk1977fee2d252007-08-18 10:59:19 +00004495
danielk197717b90b52008-06-06 11:11:25 +00004496 /* If argument zPath is a NULL pointer, this function is required to open
4497 ** a temporary file. Use this buffer to store the file name in.
4498 */
4499 char zTmpname[MAX_PATHNAME+1];
4500 const char *zName = zPath;
4501
danielk1977fee2d252007-08-18 10:59:19 +00004502 /* Check the following statements are true:
4503 **
4504 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4505 ** (b) if CREATE is set, then READWRITE must also be set, and
4506 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004507 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004508 */
danielk1977b4b47412007-08-17 15:53:36 +00004509 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004510 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004511 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004512 assert(isDelete==0 || isCreate);
4513
danddb0ac42010-07-14 14:48:58 +00004514 /* The main DB, main journal, WAL file and master journal are never
4515 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004516 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4517 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4518 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004519 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004520
danielk1977fee2d252007-08-18 10:59:19 +00004521 /* Assert that the upper layer has set one of the "file-type" flags. */
4522 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4523 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4524 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004525 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004526 );
4527
dan08da86a2009-08-21 17:18:03 +00004528 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004529
dan08da86a2009-08-21 17:18:03 +00004530 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004531 UnixUnusedFd *pUnused;
4532 pUnused = findReusableFd(zName, flags);
4533 if( pUnused ){
4534 fd = pUnused->fd;
4535 }else{
dan6aa657f2009-08-24 18:57:58 +00004536 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004537 if( !pUnused ){
4538 return SQLITE_NOMEM;
4539 }
4540 }
4541 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004542 }else if( !zName ){
4543 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004544 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004545 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004546 if( rc!=SQLITE_OK ){
4547 return rc;
4548 }
4549 zName = zTmpname;
4550 }
4551
dan08da86a2009-08-21 17:18:03 +00004552 /* Determine the value of the flags parameter passed to POSIX function
4553 ** open(). These must be calculated even if open() is not called, as
4554 ** they may be stored as part of the file handle and used by the
4555 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004556 if( isReadonly ) openFlags |= O_RDONLY;
4557 if( isReadWrite ) openFlags |= O_RDWR;
4558 if( isCreate ) openFlags |= O_CREAT;
4559 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4560 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004561
danielk1977b4b47412007-08-17 15:53:36 +00004562 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004563 mode_t openMode; /* Permissions to create file with */
4564 rc = findCreateFileMode(zName, flags, &openMode);
4565 if( rc!=SQLITE_OK ){
4566 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004567 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004568 return rc;
4569 }
dane946c392009-08-22 11:39:46 +00004570 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004571 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004572 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4573 /* Failed to open the file for read/write access. Try read-only. */
4574 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004575 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004576 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004577 openFlags |= O_RDONLY;
4578 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004579 }
4580 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004581 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004582 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004583 }
danielk1977b4b47412007-08-17 15:53:36 +00004584 }
dan08da86a2009-08-21 17:18:03 +00004585 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004586 if( pOutFlags ){
4587 *pOutFlags = flags;
4588 }
4589
dane946c392009-08-22 11:39:46 +00004590 if( p->pUnused ){
4591 p->pUnused->fd = fd;
4592 p->pUnused->flags = flags;
4593 }
4594
danielk1977b4b47412007-08-17 15:53:36 +00004595 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004596#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004597 zPath = zName;
4598#else
danielk197717b90b52008-06-06 11:11:25 +00004599 unlink(zName);
chw97185482008-11-17 08:05:31 +00004600#endif
danielk1977b4b47412007-08-17 15:53:36 +00004601 }
drh41022642008-11-21 00:24:42 +00004602#if SQLITE_ENABLE_LOCKING_STYLE
4603 else{
dan08da86a2009-08-21 17:18:03 +00004604 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004605 }
4606#endif
4607
danielk1977fee2d252007-08-18 10:59:19 +00004608 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004609 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004610 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004611 /* It is safe to close fd at this point, because it is guaranteed not
4612 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004613 ** it would not be safe to close as this would release any locks held
4614 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004615 assert( eType!=SQLITE_OPEN_MAIN_DB );
4616 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004617 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004618 }
4619 }
danielk1977e339d652008-06-28 11:23:00 +00004620
4621#ifdef FD_CLOEXEC
4622 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4623#endif
4624
drhda0e7682008-07-30 15:27:54 +00004625 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004626
drh7ed97b92010-01-20 13:07:21 +00004627
4628#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4629 struct statfs fsInfo;
4630 if( fstatfs(fd, &fsInfo) == -1 ){
4631 ((unixFile*)pFile)->lastErrno = errno;
4632 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4633 close(fd); /* silently leak if fail, in error */
4634 return SQLITE_IOERR_ACCESS;
4635 }
4636 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4637 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4638 }
4639#endif
4640
4641#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004642#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004643 isAutoProxy = 1;
4644#endif
4645 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004646 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4647 int useProxy = 0;
4648
dan08da86a2009-08-21 17:18:03 +00004649 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4650 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004651 if( envforce!=NULL ){
4652 useProxy = atoi(envforce)>0;
4653 }else{
4654 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004655 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004656 /* In theory, the close(fd) call is sub-optimal. If the file opened
4657 ** with fd is a database file, and there are other connections open
4658 ** on that file that are currently holding advisory locks on it,
4659 ** then the call to close() will cancel those locks. In practice,
4660 ** we're assuming that statfs() doesn't fail very often. At least
4661 ** not while other file descriptors opened by the same process on
4662 ** the same file are working. */
4663 p->lastErrno = errno;
4664 if( dirfd>=0 ){
4665 close(dirfd); /* silently leak if fail, in error */
4666 }
aswiftaebf4132008-11-21 00:10:35 +00004667 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004668 rc = SQLITE_IOERR_ACCESS;
4669 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004670 }
4671 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4672 }
4673 if( useProxy ){
4674 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4675 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004676 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004677 if( rc!=SQLITE_OK ){
4678 /* Use unixClose to clean up the resources added in fillInUnixFile
4679 ** and clear all the structure's references. Specifically,
4680 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4681 */
4682 unixClose(pFile);
4683 return rc;
4684 }
aswiftaebf4132008-11-21 00:10:35 +00004685 }
dane946c392009-08-22 11:39:46 +00004686 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004687 }
4688 }
4689#endif
4690
dane946c392009-08-22 11:39:46 +00004691 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4692open_finished:
4693 if( rc!=SQLITE_OK ){
4694 sqlite3_free(p->pUnused);
4695 }
4696 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004697}
4698
dane946c392009-08-22 11:39:46 +00004699
danielk1977b4b47412007-08-17 15:53:36 +00004700/*
danielk1977fee2d252007-08-18 10:59:19 +00004701** Delete the file at zPath. If the dirSync argument is true, fsync()
4702** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004703*/
drh6b9d6dd2008-12-03 19:34:47 +00004704static int unixDelete(
4705 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4706 const char *zPath, /* Name of file to be deleted */
4707 int dirSync /* If true, fsync() directory after deleting file */
4708){
danielk1977fee2d252007-08-18 10:59:19 +00004709 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004710 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004711 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004712 if( unlink(zPath)==(-1) && errno!=ENOENT ){
4713 return SQLITE_IOERR_DELETE;
4714 }
danielk1977d39fa702008-10-16 13:27:40 +00004715#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004716 if( dirSync ){
4717 int fd;
4718 rc = openDirectory(zPath, &fd);
4719 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004720#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004721 if( fsync(fd)==-1 )
4722#else
4723 if( fsync(fd) )
4724#endif
4725 {
danielk1977fee2d252007-08-18 10:59:19 +00004726 rc = SQLITE_IOERR_DIR_FSYNC;
4727 }
aswiftaebf4132008-11-21 00:10:35 +00004728 if( close(fd)&&!rc ){
4729 rc = SQLITE_IOERR_DIR_CLOSE;
4730 }
danielk1977fee2d252007-08-18 10:59:19 +00004731 }
4732 }
danielk1977d138dd82008-10-15 16:02:48 +00004733#endif
danielk1977fee2d252007-08-18 10:59:19 +00004734 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004735}
4736
danielk197790949c22007-08-17 16:50:38 +00004737/*
4738** Test the existance of or access permissions of file zPath. The
4739** test performed depends on the value of flags:
4740**
4741** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4742** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4743** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4744**
4745** Otherwise return 0.
4746*/
danielk1977861f7452008-06-05 11:39:11 +00004747static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004748 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4749 const char *zPath, /* Path of the file to examine */
4750 int flags, /* What do we want to learn about the zPath file? */
4751 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004752){
rse25c0d1a2007-09-20 08:38:14 +00004753 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004754 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004755 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004756 switch( flags ){
4757 case SQLITE_ACCESS_EXISTS:
4758 amode = F_OK;
4759 break;
4760 case SQLITE_ACCESS_READWRITE:
4761 amode = W_OK|R_OK;
4762 break;
drh50d3f902007-08-27 21:10:36 +00004763 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004764 amode = R_OK;
4765 break;
4766
4767 default:
4768 assert(!"Invalid flags argument");
4769 }
danielk1977861f7452008-06-05 11:39:11 +00004770 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004771 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4772 struct stat buf;
4773 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4774 *pResOut = 0;
4775 }
4776 }
danielk1977861f7452008-06-05 11:39:11 +00004777 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004778}
4779
danielk1977b4b47412007-08-17 15:53:36 +00004780
4781/*
4782** Turn a relative pathname into a full pathname. The relative path
4783** is stored as a nul-terminated string in the buffer pointed to by
4784** zPath.
4785**
4786** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4787** (in this case, MAX_PATHNAME bytes). The full-path is written to
4788** this buffer before returning.
4789*/
danielk1977adfb9b02007-09-17 07:02:56 +00004790static int unixFullPathname(
4791 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4792 const char *zPath, /* Possibly relative input path */
4793 int nOut, /* Size of output buffer in bytes */
4794 char *zOut /* Output buffer */
4795){
danielk1977843e65f2007-09-01 16:16:15 +00004796
4797 /* It's odd to simulate an io-error here, but really this is just
4798 ** using the io-error infrastructure to test that SQLite handles this
4799 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004800 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004801 */
4802 SimulateIOError( return SQLITE_ERROR );
4803
drh153c62c2007-08-24 03:51:33 +00004804 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004805 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004806
drh3c7f2dc2007-12-06 13:26:20 +00004807 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004808 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004809 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004810 }else{
4811 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004812 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004813 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004814 }
drhea678832008-12-10 19:26:22 +00004815 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004816 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004817 }
4818 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004819}
4820
drh0ccebe72005-06-07 22:22:50 +00004821
drh761df872006-12-21 01:29:22 +00004822#ifndef SQLITE_OMIT_LOAD_EXTENSION
4823/*
4824** Interfaces for opening a shared library, finding entry points
4825** within the shared library, and closing the shared library.
4826*/
4827#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004828static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4829 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004830 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4831}
danielk197795c8a542007-09-01 06:51:27 +00004832
4833/*
4834** SQLite calls this function immediately after a call to unixDlSym() or
4835** unixDlOpen() fails (returns a null pointer). If a more detailed error
4836** message is available, it is written to zBufOut. If no error message
4837** is available, zBufOut is left unmodified and SQLite uses a default
4838** error message.
4839*/
danielk1977397d65f2008-11-19 11:35:39 +00004840static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004841 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004842 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004843 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004844 zErr = dlerror();
4845 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004846 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004847 }
drh6c7d5c52008-11-21 20:32:33 +00004848 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004849}
drh1875f7a2008-12-08 18:19:17 +00004850static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4851 /*
4852 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4853 ** cast into a pointer to a function. And yet the library dlsym() routine
4854 ** returns a void* which is really a pointer to a function. So how do we
4855 ** use dlsym() with -pedantic-errors?
4856 **
4857 ** Variable x below is defined to be a pointer to a function taking
4858 ** parameters void* and const char* and returning a pointer to a function.
4859 ** We initialize x by assigning it a pointer to the dlsym() function.
4860 ** (That assignment requires a cast.) Then we call the function that
4861 ** x points to.
4862 **
4863 ** This work-around is unlikely to work correctly on any system where
4864 ** you really cannot cast a function pointer into void*. But then, on the
4865 ** other hand, dlsym() will not work on such a system either, so we have
4866 ** not really lost anything.
4867 */
4868 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004869 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004870 x = (void(*(*)(void*,const char*))(void))dlsym;
4871 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004872}
danielk1977397d65f2008-11-19 11:35:39 +00004873static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4874 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004875 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004876}
danielk1977b4b47412007-08-17 15:53:36 +00004877#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4878 #define unixDlOpen 0
4879 #define unixDlError 0
4880 #define unixDlSym 0
4881 #define unixDlClose 0
4882#endif
4883
4884/*
danielk197790949c22007-08-17 16:50:38 +00004885** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004886*/
danielk1977397d65f2008-11-19 11:35:39 +00004887static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4888 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004889 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004890
drhbbd42a62004-05-22 17:41:58 +00004891 /* We have to initialize zBuf to prevent valgrind from reporting
4892 ** errors. The reports issued by valgrind are incorrect - we would
4893 ** prefer that the randomness be increased by making use of the
4894 ** uninitialized space in zBuf - but valgrind errors tend to worry
4895 ** some users. Rather than argue, it seems easier just to initialize
4896 ** the whole array and silence valgrind, even if that means less randomness
4897 ** in the random seed.
4898 **
4899 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004900 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004901 ** tests repeatable.
4902 */
danielk1977b4b47412007-08-17 15:53:36 +00004903 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004904#if !defined(SQLITE_TEST)
4905 {
drh842b8642005-01-21 17:53:17 +00004906 int pid, fd;
4907 fd = open("/dev/urandom", O_RDONLY);
4908 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004909 time_t t;
4910 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004911 memcpy(zBuf, &t, sizeof(t));
4912 pid = getpid();
4913 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004914 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004915 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004916 }else{
drh72cbd072008-10-14 17:58:38 +00004917 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004918 close(fd);
4919 }
drhbbd42a62004-05-22 17:41:58 +00004920 }
4921#endif
drh72cbd072008-10-14 17:58:38 +00004922 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004923}
4924
danielk1977b4b47412007-08-17 15:53:36 +00004925
drhbbd42a62004-05-22 17:41:58 +00004926/*
4927** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004928** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004929** The return value is the number of microseconds of sleep actually
4930** requested from the underlying operating system, a number which
4931** might be greater than or equal to the argument, but not less
4932** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004933*/
danielk1977397d65f2008-11-19 11:35:39 +00004934static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004935#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004936 struct timespec sp;
4937
4938 sp.tv_sec = microseconds / 1000000;
4939 sp.tv_nsec = (microseconds % 1000000) * 1000;
4940 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004941 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004942 return microseconds;
4943#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004944 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004945 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004946 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004947#else
danielk1977b4b47412007-08-17 15:53:36 +00004948 int seconds = (microseconds+999999)/1000000;
4949 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004950 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004951 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004952#endif
drh88f474a2006-01-02 20:00:12 +00004953}
4954
4955/*
drh6b9d6dd2008-12-03 19:34:47 +00004956** The following variable, if set to a non-zero value, is interpreted as
4957** the number of seconds since 1970 and is used to set the result of
4958** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004959*/
4960#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004961int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004962#endif
4963
4964/*
drhb7e8ea22010-05-03 14:32:30 +00004965** Find the current time (in Universal Coordinated Time). Write into *piNow
4966** the current time and date as a Julian Day number times 86_400_000. In
4967** other words, write into *piNow the number of milliseconds since the Julian
4968** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4969** proleptic Gregorian calendar.
4970**
4971** On success, return 0. Return 1 if the time and date cannot be found.
4972*/
4973static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
4974 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
4975#if defined(NO_GETTOD)
4976 time_t t;
4977 time(&t);
4978 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
4979#elif OS_VXWORKS
4980 struct timespec sNow;
4981 clock_gettime(CLOCK_REALTIME, &sNow);
4982 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
4983#else
4984 struct timeval sNow;
4985 gettimeofday(&sNow, 0);
4986 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
4987#endif
4988
4989#ifdef SQLITE_TEST
4990 if( sqlite3_current_time ){
4991 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
4992 }
4993#endif
4994 UNUSED_PARAMETER(NotUsed);
4995 return 0;
4996}
4997
4998/*
drhbbd42a62004-05-22 17:41:58 +00004999** Find the current time (in Universal Coordinated Time). Write the
5000** current time and date as a Julian Day number into *prNow and
5001** return 0. Return 1 if the time and date cannot be found.
5002*/
danielk1977397d65f2008-11-19 11:35:39 +00005003static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005004 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005005 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005006 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005007 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005008 return 0;
5009}
danielk1977b4b47412007-08-17 15:53:36 +00005010
drh6b9d6dd2008-12-03 19:34:47 +00005011/*
5012** We added the xGetLastError() method with the intention of providing
5013** better low-level error messages when operating-system problems come up
5014** during SQLite operation. But so far, none of that has been implemented
5015** in the core. So this routine is never called. For now, it is merely
5016** a place-holder.
5017*/
danielk1977397d65f2008-11-19 11:35:39 +00005018static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5019 UNUSED_PARAMETER(NotUsed);
5020 UNUSED_PARAMETER(NotUsed2);
5021 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005022 return 0;
5023}
5024
drhf2424c52010-04-26 00:04:55 +00005025
5026/*
drh734c9862008-11-28 15:37:20 +00005027************************ End of sqlite3_vfs methods ***************************
5028******************************************************************************/
5029
drh715ff302008-12-03 22:32:44 +00005030/******************************************************************************
5031************************** Begin Proxy Locking ********************************
5032**
5033** Proxy locking is a "uber-locking-method" in this sense: It uses the
5034** other locking methods on secondary lock files. Proxy locking is a
5035** meta-layer over top of the primitive locking implemented above. For
5036** this reason, the division that implements of proxy locking is deferred
5037** until late in the file (here) after all of the other I/O methods have
5038** been defined - so that the primitive locking methods are available
5039** as services to help with the implementation of proxy locking.
5040**
5041****
5042**
5043** The default locking schemes in SQLite use byte-range locks on the
5044** database file to coordinate safe, concurrent access by multiple readers
5045** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5046** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5047** as POSIX read & write locks over fixed set of locations (via fsctl),
5048** on AFP and SMB only exclusive byte-range locks are available via fsctl
5049** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5050** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5051** address in the shared range is taken for a SHARED lock, the entire
5052** shared range is taken for an EXCLUSIVE lock):
5053**
5054** PENDING_BYTE 0x40000000
5055** RESERVED_BYTE 0x40000001
5056** SHARED_RANGE 0x40000002 -> 0x40000200
5057**
5058** This works well on the local file system, but shows a nearly 100x
5059** slowdown in read performance on AFP because the AFP client disables
5060** the read cache when byte-range locks are present. Enabling the read
5061** cache exposes a cache coherency problem that is present on all OS X
5062** supported network file systems. NFS and AFP both observe the
5063** close-to-open semantics for ensuring cache coherency
5064** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5065** address the requirements for concurrent database access by multiple
5066** readers and writers
5067** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5068**
5069** To address the performance and cache coherency issues, proxy file locking
5070** changes the way database access is controlled by limiting access to a
5071** single host at a time and moving file locks off of the database file
5072** and onto a proxy file on the local file system.
5073**
5074**
5075** Using proxy locks
5076** -----------------
5077**
5078** C APIs
5079**
5080** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5081** <proxy_path> | ":auto:");
5082** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5083**
5084**
5085** SQL pragmas
5086**
5087** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5088** PRAGMA [database.]lock_proxy_file
5089**
5090** Specifying ":auto:" means that if there is a conch file with a matching
5091** host ID in it, the proxy path in the conch file will be used, otherwise
5092** a proxy path based on the user's temp dir
5093** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5094** actual proxy file name is generated from the name and path of the
5095** database file. For example:
5096**
5097** For database path "/Users/me/foo.db"
5098** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5099**
5100** Once a lock proxy is configured for a database connection, it can not
5101** be removed, however it may be switched to a different proxy path via
5102** the above APIs (assuming the conch file is not being held by another
5103** connection or process).
5104**
5105**
5106** How proxy locking works
5107** -----------------------
5108**
5109** Proxy file locking relies primarily on two new supporting files:
5110**
5111** * conch file to limit access to the database file to a single host
5112** at a time
5113**
5114** * proxy file to act as a proxy for the advisory locks normally
5115** taken on the database
5116**
5117** The conch file - to use a proxy file, sqlite must first "hold the conch"
5118** by taking an sqlite-style shared lock on the conch file, reading the
5119** contents and comparing the host's unique host ID (see below) and lock
5120** proxy path against the values stored in the conch. The conch file is
5121** stored in the same directory as the database file and the file name
5122** is patterned after the database file name as ".<databasename>-conch".
5123** If the conch file does not exist, or it's contents do not match the
5124** host ID and/or proxy path, then the lock is escalated to an exclusive
5125** lock and the conch file contents is updated with the host ID and proxy
5126** path and the lock is downgraded to a shared lock again. If the conch
5127** is held by another process (with a shared lock), the exclusive lock
5128** will fail and SQLITE_BUSY is returned.
5129**
5130** The proxy file - a single-byte file used for all advisory file locks
5131** normally taken on the database file. This allows for safe sharing
5132** of the database file for multiple readers and writers on the same
5133** host (the conch ensures that they all use the same local lock file).
5134**
drh715ff302008-12-03 22:32:44 +00005135** Requesting the lock proxy does not immediately take the conch, it is
5136** only taken when the first request to lock database file is made.
5137** This matches the semantics of the traditional locking behavior, where
5138** opening a connection to a database file does not take a lock on it.
5139** The shared lock and an open file descriptor are maintained until
5140** the connection to the database is closed.
5141**
5142** The proxy file and the lock file are never deleted so they only need
5143** to be created the first time they are used.
5144**
5145** Configuration options
5146** ---------------------
5147**
5148** SQLITE_PREFER_PROXY_LOCKING
5149**
5150** Database files accessed on non-local file systems are
5151** automatically configured for proxy locking, lock files are
5152** named automatically using the same logic as
5153** PRAGMA lock_proxy_file=":auto:"
5154**
5155** SQLITE_PROXY_DEBUG
5156**
5157** Enables the logging of error messages during host id file
5158** retrieval and creation
5159**
drh715ff302008-12-03 22:32:44 +00005160** LOCKPROXYDIR
5161**
5162** Overrides the default directory used for lock proxy files that
5163** are named automatically via the ":auto:" setting
5164**
5165** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5166**
5167** Permissions to use when creating a directory for storing the
5168** lock proxy files, only used when LOCKPROXYDIR is not set.
5169**
5170**
5171** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5172** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5173** force proxy locking to be used for every database file opened, and 0
5174** will force automatic proxy locking to be disabled for all database
5175** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5176** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5177*/
5178
5179/*
5180** Proxy locking is only available on MacOSX
5181*/
drhd2cb50b2009-01-09 21:41:17 +00005182#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005183
drh715ff302008-12-03 22:32:44 +00005184/*
5185** The proxyLockingContext has the path and file structures for the remote
5186** and local proxy files in it
5187*/
5188typedef struct proxyLockingContext proxyLockingContext;
5189struct proxyLockingContext {
5190 unixFile *conchFile; /* Open conch file */
5191 char *conchFilePath; /* Name of the conch file */
5192 unixFile *lockProxy; /* Open proxy lock file */
5193 char *lockProxyPath; /* Name of the proxy lock file */
5194 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005195 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005196 void *oldLockingContext; /* Original lockingcontext to restore on close */
5197 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5198};
5199
drh7ed97b92010-01-20 13:07:21 +00005200/*
5201** The proxy lock file path for the database at dbPath is written into lPath,
5202** which must point to valid, writable memory large enough for a maxLen length
5203** file path.
drh715ff302008-12-03 22:32:44 +00005204*/
drh715ff302008-12-03 22:32:44 +00005205static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5206 int len;
5207 int dbLen;
5208 int i;
5209
5210#ifdef LOCKPROXYDIR
5211 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5212#else
5213# ifdef _CS_DARWIN_USER_TEMP_DIR
5214 {
drh7ed97b92010-01-20 13:07:21 +00005215 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005216 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5217 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005218 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005219 }
drh7ed97b92010-01-20 13:07:21 +00005220 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005221 }
5222# else
5223 len = strlcpy(lPath, "/tmp/", maxLen);
5224# endif
5225#endif
5226
5227 if( lPath[len-1]!='/' ){
5228 len = strlcat(lPath, "/", maxLen);
5229 }
5230
5231 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005232 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005233 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005234 char c = dbPath[i];
5235 lPath[i+len] = (c=='/')?'_':c;
5236 }
5237 lPath[i+len]='\0';
5238 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005239 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005240 return SQLITE_OK;
5241}
5242
drh7ed97b92010-01-20 13:07:21 +00005243/*
5244 ** Creates the lock file and any missing directories in lockPath
5245 */
5246static int proxyCreateLockPath(const char *lockPath){
5247 int i, len;
5248 char buf[MAXPATHLEN];
5249 int start = 0;
5250
5251 assert(lockPath!=NULL);
5252 /* try to create all the intermediate directories */
5253 len = (int)strlen(lockPath);
5254 buf[0] = lockPath[0];
5255 for( i=1; i<len; i++ ){
5256 if( lockPath[i] == '/' && (i - start > 0) ){
5257 /* only mkdir if leaf dir != "." or "/" or ".." */
5258 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5259 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5260 buf[i]='\0';
5261 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5262 int err=errno;
5263 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005264 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005265 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005266 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005267 return err;
5268 }
5269 }
5270 }
5271 start=i+1;
5272 }
5273 buf[i] = lockPath[i];
5274 }
drh308c2a52010-05-14 11:30:18 +00005275 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005276 return 0;
5277}
5278
drh715ff302008-12-03 22:32:44 +00005279/*
5280** Create a new VFS file descriptor (stored in memory obtained from
5281** sqlite3_malloc) and open the file named "path" in the file descriptor.
5282**
5283** The caller is responsible not only for closing the file descriptor
5284** but also for freeing the memory associated with the file descriptor.
5285*/
drh7ed97b92010-01-20 13:07:21 +00005286static int proxyCreateUnixFile(
5287 const char *path, /* path for the new unixFile */
5288 unixFile **ppFile, /* unixFile created and returned by ref */
5289 int islockfile /* if non zero missing dirs will be created */
5290) {
5291 int fd = -1;
5292 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005293 unixFile *pNew;
5294 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005295 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005296 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005297 int terrno = 0;
5298 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005299
drh7ed97b92010-01-20 13:07:21 +00005300 /* 1. first try to open/create the file
5301 ** 2. if that fails, and this is a lock file (not-conch), try creating
5302 ** the parent directories and then try again.
5303 ** 3. if that fails, try to open the file read-only
5304 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5305 */
5306 pUnused = findReusableFd(path, openFlags);
5307 if( pUnused ){
5308 fd = pUnused->fd;
5309 }else{
5310 pUnused = sqlite3_malloc(sizeof(*pUnused));
5311 if( !pUnused ){
5312 return SQLITE_NOMEM;
5313 }
5314 }
5315 if( fd<0 ){
5316 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5317 terrno = errno;
5318 if( fd<0 && errno==ENOENT && islockfile ){
5319 if( proxyCreateLockPath(path) == SQLITE_OK ){
5320 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5321 }
5322 }
5323 }
5324 if( fd<0 ){
5325 openFlags = O_RDONLY;
5326 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5327 terrno = errno;
5328 }
5329 if( fd<0 ){
5330 if( islockfile ){
5331 return SQLITE_BUSY;
5332 }
5333 switch (terrno) {
5334 case EACCES:
5335 return SQLITE_PERM;
5336 case EIO:
5337 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5338 default:
drh9978c972010-02-23 17:36:32 +00005339 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005340 }
5341 }
5342
5343 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5344 if( pNew==NULL ){
5345 rc = SQLITE_NOMEM;
5346 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005347 }
5348 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005349 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005350 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005351 pUnused->fd = fd;
5352 pUnused->flags = openFlags;
5353 pNew->pUnused = pUnused;
5354
5355 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5356 if( rc==SQLITE_OK ){
5357 *ppFile = pNew;
5358 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005359 }
drh7ed97b92010-01-20 13:07:21 +00005360end_create_proxy:
5361 close(fd); /* silently leak fd if error, we're already in error */
5362 sqlite3_free(pNew);
5363 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005364 return rc;
5365}
5366
drh7ed97b92010-01-20 13:07:21 +00005367#ifdef SQLITE_TEST
5368/* simulate multiple hosts by creating unique hostid file paths */
5369int sqlite3_hostid_num = 0;
5370#endif
5371
5372#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5373
drh0ab216a2010-07-02 17:10:40 +00005374/* Not always defined in the headers as it ought to be */
5375extern int gethostuuid(uuid_t id, const struct timespec *wait);
5376
drh7ed97b92010-01-20 13:07:21 +00005377/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5378** bytes of writable memory.
5379*/
5380static int proxyGetHostID(unsigned char *pHostID, int *pError){
5381 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5382
5383 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5384 memset(pHostID, 0, PROXY_HOSTIDLEN);
5385 if( gethostuuid(pHostID, &timeout) ){
5386 int err = errno;
5387 if( pError ){
5388 *pError = err;
5389 }
5390 return SQLITE_IOERR;
5391 }
5392#ifdef SQLITE_TEST
5393 /* simulate multiple hosts by creating unique hostid file paths */
5394 if( sqlite3_hostid_num != 0){
5395 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5396 }
5397#endif
5398
5399 return SQLITE_OK;
5400}
5401
5402/* The conch file contains the header, host id and lock file path
5403 */
5404#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5405#define PROXY_HEADERLEN 1 /* conch file header length */
5406#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5407#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5408
5409/*
5410** Takes an open conch file, copies the contents to a new path and then moves
5411** it back. The newly created file's file descriptor is assigned to the
5412** conch file structure and finally the original conch file descriptor is
5413** closed. Returns zero if successful.
5414*/
5415static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5416 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5417 unixFile *conchFile = pCtx->conchFile;
5418 char tPath[MAXPATHLEN];
5419 char buf[PROXY_MAXCONCHLEN];
5420 char *cPath = pCtx->conchFilePath;
5421 size_t readLen = 0;
5422 size_t pathLen = 0;
5423 char errmsg[64] = "";
5424 int fd = -1;
5425 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005426 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005427
5428 /* create a new path by replace the trailing '-conch' with '-break' */
5429 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5430 if( pathLen>MAXPATHLEN || pathLen<6 ||
5431 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5432 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5433 goto end_breaklock;
5434 }
5435 /* read the conch content */
5436 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5437 if( readLen<PROXY_PATHINDEX ){
5438 sprintf(errmsg, "read error (len %d)", (int)readLen);
5439 goto end_breaklock;
5440 }
5441 /* write it out to the temporary break file */
5442 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5443 if( fd<0 ){
5444 sprintf(errmsg, "create failed (%d)", errno);
5445 goto end_breaklock;
5446 }
drh0ab216a2010-07-02 17:10:40 +00005447 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
drh7ed97b92010-01-20 13:07:21 +00005448 sprintf(errmsg, "write failed (%d)", errno);
5449 goto end_breaklock;
5450 }
5451 if( rename(tPath, cPath) ){
5452 sprintf(errmsg, "rename failed (%d)", errno);
5453 goto end_breaklock;
5454 }
5455 rc = 0;
5456 fprintf(stderr, "broke stale lock on %s\n", cPath);
5457 close(conchFile->h);
5458 conchFile->h = fd;
5459 conchFile->openFlags = O_RDWR | O_CREAT;
5460
5461end_breaklock:
5462 if( rc ){
5463 if( fd>=0 ){
5464 unlink(tPath);
5465 close(fd);
5466 }
5467 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5468 }
5469 return rc;
5470}
5471
5472/* Take the requested lock on the conch file and break a stale lock if the
5473** host id matches.
5474*/
5475static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5476 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5477 unixFile *conchFile = pCtx->conchFile;
5478 int rc = SQLITE_OK;
5479 int nTries = 0;
5480 struct timespec conchModTime;
5481
5482 do {
5483 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5484 nTries ++;
5485 if( rc==SQLITE_BUSY ){
5486 /* If the lock failed (busy):
5487 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5488 * 2nd try: fail if the mod time changed or host id is different, wait
5489 * 10 sec and try again
5490 * 3rd try: break the lock unless the mod time has changed.
5491 */
5492 struct stat buf;
5493 if( fstat(conchFile->h, &buf) ){
5494 pFile->lastErrno = errno;
5495 return SQLITE_IOERR_LOCK;
5496 }
5497
5498 if( nTries==1 ){
5499 conchModTime = buf.st_mtimespec;
5500 usleep(500000); /* wait 0.5 sec and try the lock again*/
5501 continue;
5502 }
5503
5504 assert( nTries>1 );
5505 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5506 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5507 return SQLITE_BUSY;
5508 }
5509
5510 if( nTries==2 ){
5511 char tBuf[PROXY_MAXCONCHLEN];
5512 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5513 if( len<0 ){
5514 pFile->lastErrno = errno;
5515 return SQLITE_IOERR_LOCK;
5516 }
5517 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5518 /* don't break the lock if the host id doesn't match */
5519 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5520 return SQLITE_BUSY;
5521 }
5522 }else{
5523 /* don't break the lock on short read or a version mismatch */
5524 return SQLITE_BUSY;
5525 }
5526 usleep(10000000); /* wait 10 sec and try the lock again */
5527 continue;
5528 }
5529
5530 assert( nTries==3 );
5531 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5532 rc = SQLITE_OK;
5533 if( lockType==EXCLUSIVE_LOCK ){
5534 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5535 }
5536 if( !rc ){
5537 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5538 }
5539 }
5540 }
5541 } while( rc==SQLITE_BUSY && nTries<3 );
5542
5543 return rc;
5544}
5545
5546/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005547** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5548** lockPath means that the lockPath in the conch file will be used if the
5549** host IDs match, or a new lock path will be generated automatically
5550** and written to the conch file.
5551*/
5552static int proxyTakeConch(unixFile *pFile){
5553 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5554
drh7ed97b92010-01-20 13:07:21 +00005555 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005556 return SQLITE_OK;
5557 }else{
5558 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005559 uuid_t myHostID;
5560 int pError = 0;
5561 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005562 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005563 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005564 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005565 int createConch = 0;
5566 int hostIdMatch = 0;
5567 int readLen = 0;
5568 int tryOldLockPath = 0;
5569 int forceNewLockPath = 0;
5570
drh308c2a52010-05-14 11:30:18 +00005571 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5572 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005573
drh7ed97b92010-01-20 13:07:21 +00005574 rc = proxyGetHostID(myHostID, &pError);
5575 if( (rc&0xff)==SQLITE_IOERR ){
5576 pFile->lastErrno = pError;
5577 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005578 }
drh7ed97b92010-01-20 13:07:21 +00005579 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005580 if( rc!=SQLITE_OK ){
5581 goto end_takeconch;
5582 }
drh7ed97b92010-01-20 13:07:21 +00005583 /* read the existing conch file */
5584 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5585 if( readLen<0 ){
5586 /* I/O error: lastErrno set by seekAndRead */
5587 pFile->lastErrno = conchFile->lastErrno;
5588 rc = SQLITE_IOERR_READ;
5589 goto end_takeconch;
5590 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5591 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5592 /* a short read or version format mismatch means we need to create a new
5593 ** conch file.
5594 */
5595 createConch = 1;
5596 }
5597 /* if the host id matches and the lock path already exists in the conch
5598 ** we'll try to use the path there, if we can't open that path, we'll
5599 ** retry with a new auto-generated path
5600 */
5601 do { /* in case we need to try again for an :auto: named lock file */
5602
5603 if( !createConch && !forceNewLockPath ){
5604 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5605 PROXY_HOSTIDLEN);
5606 /* if the conch has data compare the contents */
5607 if( !pCtx->lockProxyPath ){
5608 /* for auto-named local lock file, just check the host ID and we'll
5609 ** use the local lock file path that's already in there
5610 */
5611 if( hostIdMatch ){
5612 size_t pathLen = (readLen - PROXY_PATHINDEX);
5613
5614 if( pathLen>=MAXPATHLEN ){
5615 pathLen=MAXPATHLEN-1;
5616 }
5617 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5618 lockPath[pathLen] = 0;
5619 tempLockPath = lockPath;
5620 tryOldLockPath = 1;
5621 /* create a copy of the lock path if the conch is taken */
5622 goto end_takeconch;
5623 }
5624 }else if( hostIdMatch
5625 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5626 readLen-PROXY_PATHINDEX)
5627 ){
5628 /* conch host and lock path match */
5629 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005630 }
drh7ed97b92010-01-20 13:07:21 +00005631 }
5632
5633 /* if the conch isn't writable and doesn't match, we can't take it */
5634 if( (conchFile->openFlags&O_RDWR) == 0 ){
5635 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005636 goto end_takeconch;
5637 }
drh7ed97b92010-01-20 13:07:21 +00005638
5639 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005640 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005641 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5642 tempLockPath = lockPath;
5643 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005644 }
drh7ed97b92010-01-20 13:07:21 +00005645
5646 /* update conch with host and path (this will fail if other process
5647 ** has a shared lock already), if the host id matches, use the big
5648 ** stick.
drh715ff302008-12-03 22:32:44 +00005649 */
drh7ed97b92010-01-20 13:07:21 +00005650 futimes(conchFile->h, NULL);
5651 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005652 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005653 /* We are trying for an exclusive lock but another thread in this
5654 ** same process is still holding a shared lock. */
5655 rc = SQLITE_BUSY;
5656 } else {
5657 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005658 }
drh715ff302008-12-03 22:32:44 +00005659 }else{
drh7ed97b92010-01-20 13:07:21 +00005660 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005661 }
drh7ed97b92010-01-20 13:07:21 +00005662 if( rc==SQLITE_OK ){
5663 char writeBuffer[PROXY_MAXCONCHLEN];
5664 int writeSize = 0;
5665
5666 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5667 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5668 if( pCtx->lockProxyPath!=NULL ){
5669 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5670 }else{
5671 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5672 }
5673 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5674 ftruncate(conchFile->h, writeSize);
5675 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5676 fsync(conchFile->h);
5677 /* If we created a new conch file (not just updated the contents of a
5678 ** valid conch file), try to match the permissions of the database
5679 */
5680 if( rc==SQLITE_OK && createConch ){
5681 struct stat buf;
5682 int err = fstat(pFile->h, &buf);
5683 if( err==0 ){
5684 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5685 S_IROTH|S_IWOTH);
5686 /* try to match the database file R/W permissions, ignore failure */
5687#ifndef SQLITE_PROXY_DEBUG
5688 fchmod(conchFile->h, cmode);
5689#else
5690 if( fchmod(conchFile->h, cmode)!=0 ){
5691 int code = errno;
5692 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5693 cmode, code, strerror(code));
5694 } else {
5695 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5696 }
5697 }else{
5698 int code = errno;
5699 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5700 err, code, strerror(code));
5701#endif
5702 }
drh715ff302008-12-03 22:32:44 +00005703 }
5704 }
drh7ed97b92010-01-20 13:07:21 +00005705 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5706
5707 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005708 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005709 if( rc==SQLITE_OK && pFile->openFlags ){
5710 if( pFile->h>=0 ){
5711#ifdef STRICT_CLOSE_ERROR
5712 if( close(pFile->h) ){
5713 pFile->lastErrno = errno;
5714 return SQLITE_IOERR_CLOSE;
5715 }
5716#else
5717 close(pFile->h); /* silently leak fd if fail */
5718#endif
5719 }
5720 pFile->h = -1;
5721 int fd = open(pCtx->dbPath, pFile->openFlags,
5722 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005723 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005724 if( fd>=0 ){
5725 pFile->h = fd;
5726 }else{
drh9978c972010-02-23 17:36:32 +00005727 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005728 during locking */
5729 }
5730 }
5731 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5732 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5733 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5734 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5735 /* we couldn't create the proxy lock file with the old lock file path
5736 ** so try again via auto-naming
5737 */
5738 forceNewLockPath = 1;
5739 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005740 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005741 }
5742 }
5743 if( rc==SQLITE_OK ){
5744 /* Need to make a copy of path if we extracted the value
5745 ** from the conch file or the path was allocated on the stack
5746 */
5747 if( tempLockPath ){
5748 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5749 if( !pCtx->lockProxyPath ){
5750 rc = SQLITE_NOMEM;
5751 }
5752 }
5753 }
5754 if( rc==SQLITE_OK ){
5755 pCtx->conchHeld = 1;
5756
5757 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5758 afpLockingContext *afpCtx;
5759 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5760 afpCtx->dbPath = pCtx->lockProxyPath;
5761 }
5762 } else {
5763 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5764 }
drh308c2a52010-05-14 11:30:18 +00005765 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5766 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005767 return rc;
drh308c2a52010-05-14 11:30:18 +00005768 } while (1); /* in case we need to retry the :auto: lock file -
5769 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005770 }
5771}
5772
5773/*
5774** If pFile holds a lock on a conch file, then release that lock.
5775*/
5776static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005777 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005778 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5779 unixFile *conchFile; /* Name of the conch file */
5780
5781 pCtx = (proxyLockingContext *)pFile->lockingContext;
5782 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005783 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005784 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005785 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005786 if( pCtx->conchHeld>0 ){
5787 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5788 }
drh715ff302008-12-03 22:32:44 +00005789 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005790 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5791 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005792 return rc;
5793}
5794
5795/*
5796** Given the name of a database file, compute the name of its conch file.
5797** Store the conch filename in memory obtained from sqlite3_malloc().
5798** Make *pConchPath point to the new name. Return SQLITE_OK on success
5799** or SQLITE_NOMEM if unable to obtain memory.
5800**
5801** The caller is responsible for ensuring that the allocated memory
5802** space is eventually freed.
5803**
5804** *pConchPath is set to NULL if a memory allocation error occurs.
5805*/
5806static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5807 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005808 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005809 char *conchPath; /* buffer in which to construct conch name */
5810
5811 /* Allocate space for the conch filename and initialize the name to
5812 ** the name of the original database file. */
5813 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5814 if( conchPath==0 ){
5815 return SQLITE_NOMEM;
5816 }
5817 memcpy(conchPath, dbPath, len+1);
5818
5819 /* now insert a "." before the last / character */
5820 for( i=(len-1); i>=0; i-- ){
5821 if( conchPath[i]=='/' ){
5822 i++;
5823 break;
5824 }
5825 }
5826 conchPath[i]='.';
5827 while ( i<len ){
5828 conchPath[i+1]=dbPath[i];
5829 i++;
5830 }
5831
5832 /* append the "-conch" suffix to the file */
5833 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005834 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005835
5836 return SQLITE_OK;
5837}
5838
5839
5840/* Takes a fully configured proxy locking-style unix file and switches
5841** the local lock file path
5842*/
5843static int switchLockProxyPath(unixFile *pFile, const char *path) {
5844 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5845 char *oldPath = pCtx->lockProxyPath;
5846 int rc = SQLITE_OK;
5847
drh308c2a52010-05-14 11:30:18 +00005848 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005849 return SQLITE_BUSY;
5850 }
5851
5852 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5853 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5854 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5855 return SQLITE_OK;
5856 }else{
5857 unixFile *lockProxy = pCtx->lockProxy;
5858 pCtx->lockProxy=NULL;
5859 pCtx->conchHeld = 0;
5860 if( lockProxy!=NULL ){
5861 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5862 if( rc ) return rc;
5863 sqlite3_free(lockProxy);
5864 }
5865 sqlite3_free(oldPath);
5866 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5867 }
5868
5869 return rc;
5870}
5871
5872/*
5873** pFile is a file that has been opened by a prior xOpen call. dbPath
5874** is a string buffer at least MAXPATHLEN+1 characters in size.
5875**
5876** This routine find the filename associated with pFile and writes it
5877** int dbPath.
5878*/
5879static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005880#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005881 if( pFile->pMethod == &afpIoMethods ){
5882 /* afp style keeps a reference to the db path in the filePath field
5883 ** of the struct */
drhea678832008-12-10 19:26:22 +00005884 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005885 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5886 } else
drh715ff302008-12-03 22:32:44 +00005887#endif
5888 if( pFile->pMethod == &dotlockIoMethods ){
5889 /* dot lock style uses the locking context to store the dot lock
5890 ** file path */
5891 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5892 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5893 }else{
5894 /* all other styles use the locking context to store the db file path */
5895 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005896 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005897 }
5898 return SQLITE_OK;
5899}
5900
5901/*
5902** Takes an already filled in unix file and alters it so all file locking
5903** will be performed on the local proxy lock file. The following fields
5904** are preserved in the locking context so that they can be restored and
5905** the unix structure properly cleaned up at close time:
5906** ->lockingContext
5907** ->pMethod
5908*/
5909static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5910 proxyLockingContext *pCtx;
5911 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5912 char *lockPath=NULL;
5913 int rc = SQLITE_OK;
5914
drh308c2a52010-05-14 11:30:18 +00005915 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005916 return SQLITE_BUSY;
5917 }
5918 proxyGetDbPathForUnixFile(pFile, dbPath);
5919 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5920 lockPath=NULL;
5921 }else{
5922 lockPath=(char *)path;
5923 }
5924
drh308c2a52010-05-14 11:30:18 +00005925 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5926 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005927
5928 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5929 if( pCtx==0 ){
5930 return SQLITE_NOMEM;
5931 }
5932 memset(pCtx, 0, sizeof(*pCtx));
5933
5934 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5935 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005936 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5937 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5938 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5939 ** (c) the file system is read-only, then enable no-locking access.
5940 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5941 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5942 */
5943 struct statfs fsInfo;
5944 struct stat conchInfo;
5945 int goLockless = 0;
5946
5947 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5948 int err = errno;
5949 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5950 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5951 }
5952 }
5953 if( goLockless ){
5954 pCtx->conchHeld = -1; /* read only FS/ lockless */
5955 rc = SQLITE_OK;
5956 }
5957 }
drh715ff302008-12-03 22:32:44 +00005958 }
5959 if( rc==SQLITE_OK && lockPath ){
5960 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5961 }
5962
5963 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005964 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5965 if( pCtx->dbPath==NULL ){
5966 rc = SQLITE_NOMEM;
5967 }
5968 }
5969 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005970 /* all memory is allocated, proxys are created and assigned,
5971 ** switch the locking context and pMethod then return.
5972 */
drh715ff302008-12-03 22:32:44 +00005973 pCtx->oldLockingContext = pFile->lockingContext;
5974 pFile->lockingContext = pCtx;
5975 pCtx->pOldMethod = pFile->pMethod;
5976 pFile->pMethod = &proxyIoMethods;
5977 }else{
5978 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00005979 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00005980 sqlite3_free(pCtx->conchFile);
5981 }
drh7ed97b92010-01-20 13:07:21 +00005982 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00005983 sqlite3_free(pCtx->conchFilePath);
5984 sqlite3_free(pCtx);
5985 }
drh308c2a52010-05-14 11:30:18 +00005986 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
5987 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005988 return rc;
5989}
5990
5991
5992/*
5993** This routine handles sqlite3_file_control() calls that are specific
5994** to proxy locking.
5995*/
5996static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5997 switch( op ){
5998 case SQLITE_GET_LOCKPROXYFILE: {
5999 unixFile *pFile = (unixFile*)id;
6000 if( pFile->pMethod == &proxyIoMethods ){
6001 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6002 proxyTakeConch(pFile);
6003 if( pCtx->lockProxyPath ){
6004 *(const char **)pArg = pCtx->lockProxyPath;
6005 }else{
6006 *(const char **)pArg = ":auto: (not held)";
6007 }
6008 } else {
6009 *(const char **)pArg = NULL;
6010 }
6011 return SQLITE_OK;
6012 }
6013 case SQLITE_SET_LOCKPROXYFILE: {
6014 unixFile *pFile = (unixFile*)id;
6015 int rc = SQLITE_OK;
6016 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6017 if( pArg==NULL || (const char *)pArg==0 ){
6018 if( isProxyStyle ){
6019 /* turn off proxy locking - not supported */
6020 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6021 }else{
6022 /* turn off proxy locking - already off - NOOP */
6023 rc = SQLITE_OK;
6024 }
6025 }else{
6026 const char *proxyPath = (const char *)pArg;
6027 if( isProxyStyle ){
6028 proxyLockingContext *pCtx =
6029 (proxyLockingContext*)pFile->lockingContext;
6030 if( !strcmp(pArg, ":auto:")
6031 || (pCtx->lockProxyPath &&
6032 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6033 ){
6034 rc = SQLITE_OK;
6035 }else{
6036 rc = switchLockProxyPath(pFile, proxyPath);
6037 }
6038 }else{
6039 /* turn on proxy file locking */
6040 rc = proxyTransformUnixFile(pFile, proxyPath);
6041 }
6042 }
6043 return rc;
6044 }
6045 default: {
6046 assert( 0 ); /* The call assures that only valid opcodes are sent */
6047 }
6048 }
6049 /*NOTREACHED*/
6050 return SQLITE_ERROR;
6051}
6052
6053/*
6054** Within this division (the proxying locking implementation) the procedures
6055** above this point are all utilities. The lock-related methods of the
6056** proxy-locking sqlite3_io_method object follow.
6057*/
6058
6059
6060/*
6061** This routine checks if there is a RESERVED lock held on the specified
6062** file by this or any other process. If such a lock is held, set *pResOut
6063** to a non-zero value otherwise *pResOut is set to zero. The return value
6064** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6065*/
6066static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6067 unixFile *pFile = (unixFile*)id;
6068 int rc = proxyTakeConch(pFile);
6069 if( rc==SQLITE_OK ){
6070 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006071 if( pCtx->conchHeld>0 ){
6072 unixFile *proxy = pCtx->lockProxy;
6073 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6074 }else{ /* conchHeld < 0 is lockless */
6075 pResOut=0;
6076 }
drh715ff302008-12-03 22:32:44 +00006077 }
6078 return rc;
6079}
6080
6081/*
drh308c2a52010-05-14 11:30:18 +00006082** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006083** of the following:
6084**
6085** (1) SHARED_LOCK
6086** (2) RESERVED_LOCK
6087** (3) PENDING_LOCK
6088** (4) EXCLUSIVE_LOCK
6089**
6090** Sometimes when requesting one lock state, additional lock states
6091** are inserted in between. The locking might fail on one of the later
6092** transitions leaving the lock state different from what it started but
6093** still short of its goal. The following chart shows the allowed
6094** transitions and the inserted intermediate states:
6095**
6096** UNLOCKED -> SHARED
6097** SHARED -> RESERVED
6098** SHARED -> (PENDING) -> EXCLUSIVE
6099** RESERVED -> (PENDING) -> EXCLUSIVE
6100** PENDING -> EXCLUSIVE
6101**
6102** This routine will only increase a lock. Use the sqlite3OsUnlock()
6103** routine to lower a locking level.
6104*/
drh308c2a52010-05-14 11:30:18 +00006105static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006106 unixFile *pFile = (unixFile*)id;
6107 int rc = proxyTakeConch(pFile);
6108 if( rc==SQLITE_OK ){
6109 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006110 if( pCtx->conchHeld>0 ){
6111 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006112 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6113 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006114 }else{
6115 /* conchHeld < 0 is lockless */
6116 }
drh715ff302008-12-03 22:32:44 +00006117 }
6118 return rc;
6119}
6120
6121
6122/*
drh308c2a52010-05-14 11:30:18 +00006123** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006124** must be either NO_LOCK or SHARED_LOCK.
6125**
6126** If the locking level of the file descriptor is already at or below
6127** the requested locking level, this routine is a no-op.
6128*/
drh308c2a52010-05-14 11:30:18 +00006129static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006130 unixFile *pFile = (unixFile*)id;
6131 int rc = proxyTakeConch(pFile);
6132 if( rc==SQLITE_OK ){
6133 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006134 if( pCtx->conchHeld>0 ){
6135 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006136 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6137 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006138 }else{
6139 /* conchHeld < 0 is lockless */
6140 }
drh715ff302008-12-03 22:32:44 +00006141 }
6142 return rc;
6143}
6144
6145/*
6146** Close a file that uses proxy locks.
6147*/
6148static int proxyClose(sqlite3_file *id) {
6149 if( id ){
6150 unixFile *pFile = (unixFile*)id;
6151 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6152 unixFile *lockProxy = pCtx->lockProxy;
6153 unixFile *conchFile = pCtx->conchFile;
6154 int rc = SQLITE_OK;
6155
6156 if( lockProxy ){
6157 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6158 if( rc ) return rc;
6159 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6160 if( rc ) return rc;
6161 sqlite3_free(lockProxy);
6162 pCtx->lockProxy = 0;
6163 }
6164 if( conchFile ){
6165 if( pCtx->conchHeld ){
6166 rc = proxyReleaseConch(pFile);
6167 if( rc ) return rc;
6168 }
6169 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6170 if( rc ) return rc;
6171 sqlite3_free(conchFile);
6172 }
6173 sqlite3_free(pCtx->lockProxyPath);
6174 sqlite3_free(pCtx->conchFilePath);
6175 sqlite3_free(pCtx->dbPath);
6176 /* restore the original locking context and pMethod then close it */
6177 pFile->lockingContext = pCtx->oldLockingContext;
6178 pFile->pMethod = pCtx->pOldMethod;
6179 sqlite3_free(pCtx);
6180 return pFile->pMethod->xClose(id);
6181 }
6182 return SQLITE_OK;
6183}
6184
6185
6186
drhd2cb50b2009-01-09 21:41:17 +00006187#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006188/*
6189** The proxy locking style is intended for use with AFP filesystems.
6190** And since AFP is only supported on MacOSX, the proxy locking is also
6191** restricted to MacOSX.
6192**
6193**
6194******************* End of the proxy lock implementation **********************
6195******************************************************************************/
6196
drh734c9862008-11-28 15:37:20 +00006197/*
danielk1977e339d652008-06-28 11:23:00 +00006198** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006199**
6200** This routine registers all VFS implementations for unix-like operating
6201** systems. This routine, and the sqlite3_os_end() routine that follows,
6202** should be the only routines in this file that are visible from other
6203** files.
drh6b9d6dd2008-12-03 19:34:47 +00006204**
6205** This routine is called once during SQLite initialization and by a
6206** single thread. The memory allocation and mutex subsystems have not
6207** necessarily been initialized when this routine is called, and so they
6208** should not be used.
drh153c62c2007-08-24 03:51:33 +00006209*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006210int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006211 /*
6212 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006213 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6214 ** to the "finder" function. (pAppData is a pointer to a pointer because
6215 ** silly C90 rules prohibit a void* from being cast to a function pointer
6216 ** and so we have to go through the intermediate pointer to avoid problems
6217 ** when compiling with -pedantic-errors on GCC.)
6218 **
6219 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006220 ** finder-function. The finder-function returns a pointer to the
6221 ** sqlite_io_methods object that implements the desired locking
6222 ** behaviors. See the division above that contains the IOMETHODS
6223 ** macro for addition information on finder-functions.
6224 **
6225 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6226 ** object. But the "autolockIoFinder" available on MacOSX does a little
6227 ** more than that; it looks at the filesystem type that hosts the
6228 ** database file and tries to choose an locking method appropriate for
6229 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006230 */
drh7708e972008-11-29 00:56:52 +00006231 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006232 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006233 sizeof(unixFile), /* szOsFile */ \
6234 MAX_PATHNAME, /* mxPathname */ \
6235 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006236 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006237 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006238 unixOpen, /* xOpen */ \
6239 unixDelete, /* xDelete */ \
6240 unixAccess, /* xAccess */ \
6241 unixFullPathname, /* xFullPathname */ \
6242 unixDlOpen, /* xDlOpen */ \
6243 unixDlError, /* xDlError */ \
6244 unixDlSym, /* xDlSym */ \
6245 unixDlClose, /* xDlClose */ \
6246 unixRandomness, /* xRandomness */ \
6247 unixSleep, /* xSleep */ \
6248 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006249 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006250 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006251 }
6252
drh6b9d6dd2008-12-03 19:34:47 +00006253 /*
6254 ** All default VFSes for unix are contained in the following array.
6255 **
6256 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6257 ** by the SQLite core when the VFS is registered. So the following
6258 ** array cannot be const.
6259 */
danielk1977e339d652008-06-28 11:23:00 +00006260 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006261#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006262 UNIXVFS("unix", autolockIoFinder ),
6263#else
6264 UNIXVFS("unix", posixIoFinder ),
6265#endif
6266 UNIXVFS("unix-none", nolockIoFinder ),
6267 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006268#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006269 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006270#endif
6271#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006272 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006273#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006274 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006275#endif
chw78a13182009-04-07 05:35:03 +00006276#endif
drhd2cb50b2009-01-09 21:41:17 +00006277#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006278 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006279 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006280 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006281#endif
drh153c62c2007-08-24 03:51:33 +00006282 };
drh6b9d6dd2008-12-03 19:34:47 +00006283 unsigned int i; /* Loop counter */
6284
6285 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006286 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006287 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006288 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006289 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006290}
danielk1977e339d652008-06-28 11:23:00 +00006291
6292/*
drh6b9d6dd2008-12-03 19:34:47 +00006293** Shutdown the operating system interface.
6294**
6295** Some operating systems might need to do some cleanup in this routine,
6296** to release dynamically allocated objects. But not on unix.
6297** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006298*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006299int sqlite3_os_end(void){
6300 return SQLITE_OK;
6301}
drhdce8bdb2007-08-16 13:01:44 +00006302
danielk197729bafea2008-06-26 10:41:19 +00006303#endif /* SQLITE_OS_UNIX */