blob: 8ff3023e86dc3d2476b214917f5be97c9d856fb2 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
209 int lastErrno; /* The unix errno from last I/O error */
210 void *lockingContext; /* Locking style specific state */
211 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
212 int fileFlags; /* Miscellanous flags */
213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drh0c2694b2009-09-03 16:23:44 +0000247** The following macros define bits in unixFile.fileFlags
248*/
249#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
250
251/*
drh198bf392006-01-06 21:52:49 +0000252** Include code that is common to all os_*.c files
253*/
254#include "os_common.h"
255
256/*
drh0ccebe72005-06-07 22:22:50 +0000257** Define various macros that are missing from some systems.
258*/
drhbbd42a62004-05-22 17:41:58 +0000259#ifndef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifdef SQLITE_DISABLE_LFS
263# undef O_LARGEFILE
264# define O_LARGEFILE 0
265#endif
266#ifndef O_NOFOLLOW
267# define O_NOFOLLOW 0
268#endif
269#ifndef O_BINARY
270# define O_BINARY 0
271#endif
272
273/*
274** The DJGPP compiler environment looks mostly like Unix, but it
275** lacks the fcntl() system call. So redefine fcntl() to be something
276** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000277** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000278*/
279#ifdef __DJGPP__
280# define fcntl(A,B,C) 0
281#endif
282
283/*
drh2b4b5962005-06-15 17:47:55 +0000284** The threadid macro resolves to the thread-id or to 0. Used for
285** testing and debugging only.
286*/
drhd677b3d2007-08-20 22:48:41 +0000287#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000288#define threadid pthread_self()
289#else
290#define threadid 0
291#endif
292
danielk197713adf8a2004-06-03 16:08:41 +0000293
drh107886a2008-11-21 22:21:50 +0000294/*
dan9359c7b2009-08-21 08:29:10 +0000295** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000296** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000297** vxworksFileId objects used by this file, all of which may be
298** shared by multiple threads.
299**
300** Function unixMutexHeld() is used to assert() that the global mutex
301** is held when required. This function is only used as part of assert()
302** statements. e.g.
303**
304** unixEnterMutex()
305** assert( unixMutexHeld() );
306** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000307*/
308static void unixEnterMutex(void){
309 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
310}
311static void unixLeaveMutex(void){
312 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
313}
dan9359c7b2009-08-21 08:29:10 +0000314#ifdef SQLITE_DEBUG
315static int unixMutexHeld(void) {
316 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
317}
318#endif
drh107886a2008-11-21 22:21:50 +0000319
drh734c9862008-11-28 15:37:20 +0000320
321#ifdef SQLITE_DEBUG
322/*
323** Helper function for printing out trace information from debugging
324** binaries. This returns the string represetation of the supplied
325** integer lock-type.
326*/
drh308c2a52010-05-14 11:30:18 +0000327static const char *azFileLock(int eFileLock){
328 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000329 case NO_LOCK: return "NONE";
330 case SHARED_LOCK: return "SHARED";
331 case RESERVED_LOCK: return "RESERVED";
332 case PENDING_LOCK: return "PENDING";
333 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000334 }
335 return "ERROR";
336}
337#endif
338
339#ifdef SQLITE_LOCK_TRACE
340/*
341** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000342**
drh734c9862008-11-28 15:37:20 +0000343** This routine is used for troubleshooting locks on multithreaded
344** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
345** command-line option on the compiler. This code is normally
346** turned off.
347*/
348static int lockTrace(int fd, int op, struct flock *p){
349 char *zOpName, *zType;
350 int s;
351 int savedErrno;
352 if( op==F_GETLK ){
353 zOpName = "GETLK";
354 }else if( op==F_SETLK ){
355 zOpName = "SETLK";
356 }else{
357 s = fcntl(fd, op, p);
358 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
359 return s;
360 }
361 if( p->l_type==F_RDLCK ){
362 zType = "RDLCK";
363 }else if( p->l_type==F_WRLCK ){
364 zType = "WRLCK";
365 }else if( p->l_type==F_UNLCK ){
366 zType = "UNLCK";
367 }else{
368 assert( 0 );
369 }
370 assert( p->l_whence==SEEK_SET );
371 s = fcntl(fd, op, p);
372 savedErrno = errno;
373 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
374 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
375 (int)p->l_pid, s);
376 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
377 struct flock l2;
378 l2 = *p;
379 fcntl(fd, F_GETLK, &l2);
380 if( l2.l_type==F_RDLCK ){
381 zType = "RDLCK";
382 }else if( l2.l_type==F_WRLCK ){
383 zType = "WRLCK";
384 }else if( l2.l_type==F_UNLCK ){
385 zType = "UNLCK";
386 }else{
387 assert( 0 );
388 }
389 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
390 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
391 }
392 errno = savedErrno;
393 return s;
394}
395#define fcntl lockTrace
396#endif /* SQLITE_LOCK_TRACE */
397
398
399
400/*
401** This routine translates a standard POSIX errno code into something
402** useful to the clients of the sqlite3 functions. Specifically, it is
403** intended to translate a variety of "try again" errors into SQLITE_BUSY
404** and a variety of "please close the file descriptor NOW" errors into
405** SQLITE_IOERR
406**
407** Errors during initialization of locks, or file system support for locks,
408** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
409*/
410static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
411 switch (posixError) {
412 case 0:
413 return SQLITE_OK;
414
415 case EAGAIN:
416 case ETIMEDOUT:
417 case EBUSY:
418 case EINTR:
419 case ENOLCK:
420 /* random NFS retry error, unless during file system support
421 * introspection, in which it actually means what it says */
422 return SQLITE_BUSY;
423
424 case EACCES:
425 /* EACCES is like EAGAIN during locking operations, but not any other time*/
426 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
427 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
428 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
429 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
430 return SQLITE_BUSY;
431 }
432 /* else fall through */
433 case EPERM:
434 return SQLITE_PERM;
435
436 case EDEADLK:
437 return SQLITE_IOERR_BLOCKED;
438
439#if EOPNOTSUPP!=ENOTSUP
440 case EOPNOTSUPP:
441 /* something went terribly awry, unless during file system support
442 * introspection, in which it actually means what it says */
443#endif
444#ifdef ENOTSUP
445 case ENOTSUP:
446 /* invalid fd, unless during file system support introspection, in which
447 * it actually means what it says */
448#endif
449 case EIO:
450 case EBADF:
451 case EINVAL:
452 case ENOTCONN:
453 case ENODEV:
454 case ENXIO:
455 case ENOENT:
456 case ESTALE:
457 case ENOSYS:
458 /* these should force the client to close the file and reconnect */
459
460 default:
461 return sqliteIOErr;
462 }
463}
464
465
466
467/******************************************************************************
468****************** Begin Unique File ID Utility Used By VxWorks ***************
469**
470** On most versions of unix, we can get a unique ID for a file by concatenating
471** the device number and the inode number. But this does not work on VxWorks.
472** On VxWorks, a unique file id must be based on the canonical filename.
473**
474** A pointer to an instance of the following structure can be used as a
475** unique file ID in VxWorks. Each instance of this structure contains
476** a copy of the canonical filename. There is also a reference count.
477** The structure is reclaimed when the number of pointers to it drops to
478** zero.
479**
480** There are never very many files open at one time and lookups are not
481** a performance-critical path, so it is sufficient to put these
482** structures on a linked list.
483*/
484struct vxworksFileId {
485 struct vxworksFileId *pNext; /* Next in a list of them all */
486 int nRef; /* Number of references to this one */
487 int nName; /* Length of the zCanonicalName[] string */
488 char *zCanonicalName; /* Canonical filename */
489};
490
491#if OS_VXWORKS
492/*
drh9b35ea62008-11-29 02:20:26 +0000493** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000494** variable:
495*/
496static struct vxworksFileId *vxworksFileList = 0;
497
498/*
499** Simplify a filename into its canonical form
500** by making the following changes:
501**
502** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000503** * convert /./ into just /
504** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000505**
506** Changes are made in-place. Return the new name length.
507**
508** The original filename is in z[0..n-1]. Return the number of
509** characters in the simplified name.
510*/
511static int vxworksSimplifyName(char *z, int n){
512 int i, j;
513 while( n>1 && z[n-1]=='/' ){ n--; }
514 for(i=j=0; i<n; i++){
515 if( z[i]=='/' ){
516 if( z[i+1]=='/' ) continue;
517 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
518 i += 1;
519 continue;
520 }
521 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
522 while( j>0 && z[j-1]!='/' ){ j--; }
523 if( j>0 ){ j--; }
524 i += 2;
525 continue;
526 }
527 }
528 z[j++] = z[i];
529 }
530 z[j] = 0;
531 return j;
532}
533
534/*
535** Find a unique file ID for the given absolute pathname. Return
536** a pointer to the vxworksFileId object. This pointer is the unique
537** file ID.
538**
539** The nRef field of the vxworksFileId object is incremented before
540** the object is returned. A new vxworksFileId object is created
541** and added to the global list if necessary.
542**
543** If a memory allocation error occurs, return NULL.
544*/
545static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
546 struct vxworksFileId *pNew; /* search key and new file ID */
547 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
548 int n; /* Length of zAbsoluteName string */
549
550 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000551 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000552 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
553 if( pNew==0 ) return 0;
554 pNew->zCanonicalName = (char*)&pNew[1];
555 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
556 n = vxworksSimplifyName(pNew->zCanonicalName, n);
557
558 /* Search for an existing entry that matching the canonical name.
559 ** If found, increment the reference count and return a pointer to
560 ** the existing file ID.
561 */
562 unixEnterMutex();
563 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
564 if( pCandidate->nName==n
565 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
566 ){
567 sqlite3_free(pNew);
568 pCandidate->nRef++;
569 unixLeaveMutex();
570 return pCandidate;
571 }
572 }
573
574 /* No match was found. We will make a new file ID */
575 pNew->nRef = 1;
576 pNew->nName = n;
577 pNew->pNext = vxworksFileList;
578 vxworksFileList = pNew;
579 unixLeaveMutex();
580 return pNew;
581}
582
583/*
584** Decrement the reference count on a vxworksFileId object. Free
585** the object when the reference count reaches zero.
586*/
587static void vxworksReleaseFileId(struct vxworksFileId *pId){
588 unixEnterMutex();
589 assert( pId->nRef>0 );
590 pId->nRef--;
591 if( pId->nRef==0 ){
592 struct vxworksFileId **pp;
593 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
594 assert( *pp==pId );
595 *pp = pId->pNext;
596 sqlite3_free(pId);
597 }
598 unixLeaveMutex();
599}
600#endif /* OS_VXWORKS */
601/*************** End of Unique File ID Utility Used By VxWorks ****************
602******************************************************************************/
603
604
605/******************************************************************************
606*************************** Posix Advisory Locking ****************************
607**
drh9b35ea62008-11-29 02:20:26 +0000608** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000609** section 6.5.2.2 lines 483 through 490 specify that when a process
610** sets or clears a lock, that operation overrides any prior locks set
611** by the same process. It does not explicitly say so, but this implies
612** that it overrides locks set by the same process using a different
613** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000614**
615** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000616** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
617**
618** Suppose ./file1 and ./file2 are really the same file (because
619** one is a hard or symbolic link to the other) then if you set
620** an exclusive lock on fd1, then try to get an exclusive lock
621** on fd2, it works. I would have expected the second lock to
622** fail since there was already a lock on the file due to fd1.
623** But not so. Since both locks came from the same process, the
624** second overrides the first, even though they were on different
625** file descriptors opened on different file names.
626**
drh734c9862008-11-28 15:37:20 +0000627** This means that we cannot use POSIX locks to synchronize file access
628** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000629** to synchronize access for threads in separate processes, but not
630** threads within the same process.
631**
632** To work around the problem, SQLite has to manage file locks internally
633** on its own. Whenever a new database is opened, we have to find the
634** specific inode of the database file (the inode is determined by the
635** st_dev and st_ino fields of the stat structure that fstat() fills in)
636** and check for locks already existing on that inode. When locks are
637** created or removed, we have to look at our own internal record of the
638** locks to see if another thread has previously set a lock on that same
639** inode.
640**
drh9b35ea62008-11-29 02:20:26 +0000641** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
642** For VxWorks, we have to use the alternative unique ID system based on
643** canonical filename and implemented in the previous division.)
644**
danielk1977ad94b582007-08-20 06:44:22 +0000645** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000646** descriptor. It is now a structure that holds the integer file
647** descriptor and a pointer to a structure that describes the internal
648** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000649** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000650** point to the same locking structure. The locking structure keeps
651** a reference count (so we will know when to delete it) and a "cnt"
652** field that tells us its internal lock status. cnt==0 means the
653** file is unlocked. cnt==-1 means the file has an exclusive lock.
654** cnt>0 means there are cnt shared locks on the file.
655**
656** Any attempt to lock or unlock a file first checks the locking
657** structure. The fcntl() system call is only invoked to set a
658** POSIX lock if the internal lock structure transitions between
659** a locked and an unlocked state.
660**
drh734c9862008-11-28 15:37:20 +0000661** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000662**
663** If you close a file descriptor that points to a file that has locks,
664** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000665** released. To work around this problem, each unixInodeInfo object
666** maintains a count of the number of pending locks on tha inode.
667** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000668** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000669** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000670** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000671** be closed and that list is walked (and cleared) when the last lock
672** clears.
673**
drh9b35ea62008-11-29 02:20:26 +0000674** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000675**
drh9b35ea62008-11-29 02:20:26 +0000676** Many older versions of linux use the LinuxThreads library which is
677** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000678** A cannot be modified or overridden by a different thread B.
679** Only thread A can modify the lock. Locking behavior is correct
680** if the appliation uses the newer Native Posix Thread Library (NPTL)
681** on linux - with NPTL a lock created by thread A can override locks
682** in thread B. But there is no way to know at compile-time which
683** threading library is being used. So there is no way to know at
684** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000685** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000686** current process.
drh5fdae772004-06-29 03:29:00 +0000687**
drh8af6c222010-05-14 12:43:01 +0000688** SQLite used to support LinuxThreads. But support for LinuxThreads
689** was dropped beginning with version 3.7.0. SQLite will still work with
690** LinuxThreads provided that (1) there is no more than one connection
691** per database file in the same process and (2) database connections
692** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000693*/
694
695/*
696** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000697** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000698*/
699struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000700 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000701#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000702 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000703#else
drh107886a2008-11-21 22:21:50 +0000704 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000705#endif
706};
707
708/*
drhbbd42a62004-05-22 17:41:58 +0000709** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000710** inode. Or, on LinuxThreads, there is one of these structures for
711** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000712**
danielk1977ad94b582007-08-20 06:44:22 +0000713** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000714** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000715** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000716*/
drh8af6c222010-05-14 12:43:01 +0000717struct unixInodeInfo {
718 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000719 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000720 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000721 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000722 unixShmNode *pShmNode; /* Shared memory associated with this inode */
723 int nLock; /* Number of outstanding file locks */
724 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
725 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
726 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000727#if defined(SQLITE_ENABLE_LOCKING_STYLE)
728 unsigned long long sharedByte; /* for AFP simulated shared lock */
729#endif
drh6c7d5c52008-11-21 20:32:33 +0000730#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000731 sem_t *pSem; /* Named POSIX semaphore */
732 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000733#endif
drhbbd42a62004-05-22 17:41:58 +0000734};
735
drhda0e7682008-07-30 15:27:54 +0000736/*
drh8af6c222010-05-14 12:43:01 +0000737** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000738*/
drhd91c68f2010-05-14 14:52:25 +0000739static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000740
drh5fdae772004-06-29 03:29:00 +0000741/*
dane18d4952011-02-21 11:46:24 +0000742**
743** This function - unixLogError_x(), is only ever called via the macro
744** unixLogError().
745**
746** It is invoked after an error occurs in an OS function and errno has been
747** set. It logs a message using sqlite3_log() containing the current value of
748** errno and, if possible, the human-readable equivalent from strerror() or
749** strerror_r().
750**
751** The first argument passed to the macro should be the error code that
752** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
753** The two subsequent arguments should be the name of the OS function that
754** failed (e.g. "unlink", "open") and the the associated file-system path,
755** if any.
756*/
757#define unixLogError(a,b,c) unixLogError_x(a,b,c,__LINE__)
758static int unixLogError_x(
759 int errcode, /* SQLite error code */
760 const char *zFunc, /* Name of OS function that failed */
761 const char *zPath, /* File path associated with error */
762 int iLine /* Source line number where error occurred */
763){
764 char *zErr; /* Message from strerror() or equivalent */
765
766 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
767 ** the strerror() function to obtain the human-readable error message
768 ** equivalent to errno. Otherwise, use strerror_r().
769 */
770#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
771 char aErr[80];
772 memset(aErr, 0, sizeof(aErr));
773 zErr = aErr;
774
775 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
776 ** assume that the system provides the the GNU version of strerror_r() that
777 ** returns a pointer to a buffer containing the error message. That pointer
778 ** may point to aErr[], or it may point to some static storage somewhere.
779 ** Otherwise, assume that the system provides the POSIX version of
780 ** strerror_r(), which always writes an error message into aErr[].
781 **
782 ** If the code incorrectly assumes that it is the POSIX version that is
783 ** available, the error message will often be an empty string. Not a
784 ** huge problem. Incorrectly concluding that the GNU version is available
785 ** could lead to a segfault though.
786 */
787#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
788 zErr =
789# endif
790 strerror_r(errno, aErr, sizeof(aErr)-1);
791
792#elif SQLITE_THREADSAFE
793 /* This is a threadsafe build, but strerror_r() is not available. */
794 zErr = "";
795#else
796 /* Non-threadsafe build, use strerror(). */
797 zErr = strerror(errno);
798#endif
799
800 assert( errcode!=SQLITE_OK );
801 sqlite3_log(errcode,
802 "os_unix.c: %s() at line %d - \"%s\" errno=%d path=%s",
803 zFunc, iLine, zErr, errno, (zPath ? zPath : "n/a")
804 );
805
806 return errcode;
807}
808
809
810/*
danb0ac3e32010-06-16 10:55:42 +0000811** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
812** If all such file descriptors are closed without error, the list is
813** cleared and SQLITE_OK returned.
814**
815** Otherwise, if an error occurs, then successfully closed file descriptor
816** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
817** not deleted and SQLITE_IOERR_CLOSE returned.
818*/
819static int closePendingFds(unixFile *pFile){
820 int rc = SQLITE_OK;
821 unixInodeInfo *pInode = pFile->pInode;
822 UnixUnusedFd *pError = 0;
823 UnixUnusedFd *p;
824 UnixUnusedFd *pNext;
825 for(p=pInode->pUnused; p; p=pNext){
826 pNext = p->pNext;
827 if( close(p->fd) ){
828 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +0000829 rc = unixLogError(SQLITE_IOERR_CLOSE, "close", pFile->zPath);
danb0ac3e32010-06-16 10:55:42 +0000830 p->pNext = pError;
831 pError = p;
832 }else{
833 sqlite3_free(p);
834 }
835 }
836 pInode->pUnused = pError;
837 return rc;
838}
839
840/*
drh8af6c222010-05-14 12:43:01 +0000841** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000842**
843** The mutex entered using the unixEnterMutex() function must be held
844** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000845*/
danb0ac3e32010-06-16 10:55:42 +0000846static void releaseInodeInfo(unixFile *pFile){
847 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000848 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000849 if( pInode ){
850 pInode->nRef--;
851 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000852 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000853 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000854 if( pInode->pPrev ){
855 assert( pInode->pPrev->pNext==pInode );
856 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000857 }else{
drh8af6c222010-05-14 12:43:01 +0000858 assert( inodeList==pInode );
859 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000860 }
drh8af6c222010-05-14 12:43:01 +0000861 if( pInode->pNext ){
862 assert( pInode->pNext->pPrev==pInode );
863 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000864 }
drh8af6c222010-05-14 12:43:01 +0000865 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000866 }
drhbbd42a62004-05-22 17:41:58 +0000867 }
868}
869
870/*
drh8af6c222010-05-14 12:43:01 +0000871** Given a file descriptor, locate the unixInodeInfo object that
872** describes that file descriptor. Create a new one if necessary. The
873** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000874**
dan9359c7b2009-08-21 08:29:10 +0000875** The mutex entered using the unixEnterMutex() function must be held
876** when this function is called.
877**
drh6c7d5c52008-11-21 20:32:33 +0000878** Return an appropriate error code.
879*/
drh8af6c222010-05-14 12:43:01 +0000880static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000881 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000882 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000883){
884 int rc; /* System call return code */
885 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000886 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
887 struct stat statbuf; /* Low-level file information */
888 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000889
dan9359c7b2009-08-21 08:29:10 +0000890 assert( unixMutexHeld() );
891
drh6c7d5c52008-11-21 20:32:33 +0000892 /* Get low-level information about the file that we can used to
893 ** create a unique name for the file.
894 */
895 fd = pFile->h;
896 rc = fstat(fd, &statbuf);
897 if( rc!=0 ){
898 pFile->lastErrno = errno;
899#ifdef EOVERFLOW
900 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
901#endif
902 return SQLITE_IOERR;
903 }
904
drheb0d74f2009-02-03 15:27:02 +0000905#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000906 /* On OS X on an msdos filesystem, the inode number is reported
907 ** incorrectly for zero-size files. See ticket #3260. To work
908 ** around this problem (we consider it a bug in OS X, not SQLite)
909 ** we always increase the file size to 1 by writing a single byte
910 ** prior to accessing the inode number. The one byte written is
911 ** an ASCII 'S' character which also happens to be the first byte
912 ** in the header of every SQLite database. In this way, if there
913 ** is a race condition such that another thread has already populated
914 ** the first page of the database, no damage is done.
915 */
drh7ed97b92010-01-20 13:07:21 +0000916 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +0000917 rc = write(fd, "S", 1);
918 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000919 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000920 return SQLITE_IOERR;
921 }
drh6c7d5c52008-11-21 20:32:33 +0000922 rc = fstat(fd, &statbuf);
923 if( rc!=0 ){
924 pFile->lastErrno = errno;
925 return SQLITE_IOERR;
926 }
927 }
drheb0d74f2009-02-03 15:27:02 +0000928#endif
drh6c7d5c52008-11-21 20:32:33 +0000929
drh8af6c222010-05-14 12:43:01 +0000930 memset(&fileId, 0, sizeof(fileId));
931 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000932#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000933 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000934#else
drh8af6c222010-05-14 12:43:01 +0000935 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000936#endif
drh8af6c222010-05-14 12:43:01 +0000937 pInode = inodeList;
938 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
939 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000940 }
drh8af6c222010-05-14 12:43:01 +0000941 if( pInode==0 ){
942 pInode = sqlite3_malloc( sizeof(*pInode) );
943 if( pInode==0 ){
944 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000945 }
drh8af6c222010-05-14 12:43:01 +0000946 memset(pInode, 0, sizeof(*pInode));
947 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
948 pInode->nRef = 1;
949 pInode->pNext = inodeList;
950 pInode->pPrev = 0;
951 if( inodeList ) inodeList->pPrev = pInode;
952 inodeList = pInode;
953 }else{
954 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000955 }
drh8af6c222010-05-14 12:43:01 +0000956 *ppInode = pInode;
957 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000958}
drh6c7d5c52008-11-21 20:32:33 +0000959
aswift5b1a2562008-08-22 00:22:35 +0000960
961/*
danielk197713adf8a2004-06-03 16:08:41 +0000962** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000963** file by this or any other process. If such a lock is held, set *pResOut
964** to a non-zero value otherwise *pResOut is set to zero. The return value
965** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000966*/
danielk1977861f7452008-06-05 11:39:11 +0000967static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000968 int rc = SQLITE_OK;
969 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000970 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000971
danielk1977861f7452008-06-05 11:39:11 +0000972 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
973
drh054889e2005-11-30 03:20:31 +0000974 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000975 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000976
977 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000978 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000979 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000980 }
981
drh2ac3ee92004-06-07 16:27:46 +0000982 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000983 */
danielk197709480a92009-02-09 05:32:32 +0000984#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000985 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000986 struct flock lock;
987 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000988 lock.l_start = RESERVED_BYTE;
989 lock.l_len = 1;
990 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +0000991 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
992 int tErrno = errno;
993 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
994 pFile->lastErrno = tErrno;
995 } else if( lock.l_type!=F_UNLCK ){
996 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000997 }
998 }
danielk197709480a92009-02-09 05:32:32 +0000999#endif
danielk197713adf8a2004-06-03 16:08:41 +00001000
drh6c7d5c52008-11-21 20:32:33 +00001001 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001002 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001003
aswift5b1a2562008-08-22 00:22:35 +00001004 *pResOut = reserved;
1005 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001006}
1007
1008/*
drh308c2a52010-05-14 11:30:18 +00001009** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001010** of the following:
1011**
drh2ac3ee92004-06-07 16:27:46 +00001012** (1) SHARED_LOCK
1013** (2) RESERVED_LOCK
1014** (3) PENDING_LOCK
1015** (4) EXCLUSIVE_LOCK
1016**
drhb3e04342004-06-08 00:47:47 +00001017** Sometimes when requesting one lock state, additional lock states
1018** are inserted in between. The locking might fail on one of the later
1019** transitions leaving the lock state different from what it started but
1020** still short of its goal. The following chart shows the allowed
1021** transitions and the inserted intermediate states:
1022**
1023** UNLOCKED -> SHARED
1024** SHARED -> RESERVED
1025** SHARED -> (PENDING) -> EXCLUSIVE
1026** RESERVED -> (PENDING) -> EXCLUSIVE
1027** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001028**
drha6abd042004-06-09 17:37:22 +00001029** This routine will only increase a lock. Use the sqlite3OsUnlock()
1030** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001031*/
drh308c2a52010-05-14 11:30:18 +00001032static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001033 /* The following describes the implementation of the various locks and
1034 ** lock transitions in terms of the POSIX advisory shared and exclusive
1035 ** lock primitives (called read-locks and write-locks below, to avoid
1036 ** confusion with SQLite lock names). The algorithms are complicated
1037 ** slightly in order to be compatible with windows systems simultaneously
1038 ** accessing the same database file, in case that is ever required.
1039 **
1040 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1041 ** byte', each single bytes at well known offsets, and the 'shared byte
1042 ** range', a range of 510 bytes at a well known offset.
1043 **
1044 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1045 ** byte'. If this is successful, a random byte from the 'shared byte
1046 ** range' is read-locked and the lock on the 'pending byte' released.
1047 **
danielk197790ba3bd2004-06-25 08:32:25 +00001048 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1049 ** A RESERVED lock is implemented by grabbing a write-lock on the
1050 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001051 **
1052 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001053 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1054 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1055 ** obtained, but existing SHARED locks are allowed to persist. A process
1056 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1057 ** This property is used by the algorithm for rolling back a journal file
1058 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001059 **
danielk197790ba3bd2004-06-25 08:32:25 +00001060 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1061 ** implemented by obtaining a write-lock on the entire 'shared byte
1062 ** range'. Since all other locks require a read-lock on one of the bytes
1063 ** within this range, this ensures that no other locks are held on the
1064 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001065 **
1066 ** The reason a single byte cannot be used instead of the 'shared byte
1067 ** range' is that some versions of windows do not support read-locks. By
1068 ** locking a random byte from a range, concurrent SHARED locks may exist
1069 ** even if the locking primitive used is always a write-lock.
1070 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001071 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001072 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001073 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001074 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001075 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001076 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001077
drh054889e2005-11-30 03:20:31 +00001078 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001079 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1080 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001081 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001082
1083 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001084 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001085 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001086 */
drh308c2a52010-05-14 11:30:18 +00001087 if( pFile->eFileLock>=eFileLock ){
1088 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1089 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001090 return SQLITE_OK;
1091 }
1092
drh0c2694b2009-09-03 16:23:44 +00001093 /* Make sure the locking sequence is correct.
1094 ** (1) We never move from unlocked to anything higher than shared lock.
1095 ** (2) SQLite never explicitly requests a pendig lock.
1096 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001097 */
drh308c2a52010-05-14 11:30:18 +00001098 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1099 assert( eFileLock!=PENDING_LOCK );
1100 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001101
drh8af6c222010-05-14 12:43:01 +00001102 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001103 */
drh6c7d5c52008-11-21 20:32:33 +00001104 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001105 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001106
danielk1977ad94b582007-08-20 06:44:22 +00001107 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001108 ** handle that precludes the requested lock, return BUSY.
1109 */
drh8af6c222010-05-14 12:43:01 +00001110 if( (pFile->eFileLock!=pInode->eFileLock &&
1111 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001112 ){
1113 rc = SQLITE_BUSY;
1114 goto end_lock;
1115 }
1116
1117 /* If a SHARED lock is requested, and some thread using this PID already
1118 ** has a SHARED or RESERVED lock, then increment reference counts and
1119 ** return SQLITE_OK.
1120 */
drh308c2a52010-05-14 11:30:18 +00001121 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001122 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001123 assert( eFileLock==SHARED_LOCK );
1124 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001125 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001126 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001127 pInode->nShared++;
1128 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001129 goto end_lock;
1130 }
1131
danielk19779a1d0ab2004-06-01 14:09:28 +00001132
drh3cde3bb2004-06-12 02:17:14 +00001133 /* A PENDING lock is needed before acquiring a SHARED lock and before
1134 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1135 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001136 */
drh0c2694b2009-09-03 16:23:44 +00001137 lock.l_len = 1L;
1138 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001139 if( eFileLock==SHARED_LOCK
1140 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001141 ){
drh308c2a52010-05-14 11:30:18 +00001142 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001143 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001144 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001145 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001146 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001147 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1148 if( IS_LOCK_ERROR(rc) ){
1149 pFile->lastErrno = tErrno;
1150 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001151 goto end_lock;
1152 }
drh3cde3bb2004-06-12 02:17:14 +00001153 }
1154
1155
1156 /* If control gets to this point, then actually go ahead and make
1157 ** operating system calls for the specified lock.
1158 */
drh308c2a52010-05-14 11:30:18 +00001159 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001160 assert( pInode->nShared==0 );
1161 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001162
drh2ac3ee92004-06-07 16:27:46 +00001163 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001164 lock.l_start = SHARED_FIRST;
1165 lock.l_len = SHARED_SIZE;
1166 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1167 tErrno = errno;
1168 }
drh2ac3ee92004-06-07 16:27:46 +00001169 /* Drop the temporary PENDING lock */
1170 lock.l_start = PENDING_BYTE;
1171 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001172 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001173 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001174 if( s != -1 ){
1175 /* This could happen with a network mount */
1176 tErrno = errno;
1177 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1178 if( IS_LOCK_ERROR(rc) ){
1179 pFile->lastErrno = tErrno;
1180 }
1181 goto end_lock;
1182 }
drh2b4b5962005-06-15 17:47:55 +00001183 }
drhe2396a12007-03-29 20:19:58 +00001184 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001185 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1186 if( IS_LOCK_ERROR(rc) ){
1187 pFile->lastErrno = tErrno;
1188 }
drhbbd42a62004-05-22 17:41:58 +00001189 }else{
drh308c2a52010-05-14 11:30:18 +00001190 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001191 pInode->nLock++;
1192 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001193 }
drh8af6c222010-05-14 12:43:01 +00001194 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001195 /* We are trying for an exclusive lock but another thread in this
1196 ** same process is still holding a shared lock. */
1197 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001198 }else{
drh3cde3bb2004-06-12 02:17:14 +00001199 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001200 ** assumed that there is a SHARED or greater lock on the file
1201 ** already.
1202 */
drh308c2a52010-05-14 11:30:18 +00001203 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001204 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001205 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001206 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001207 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001208 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001209 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001210 lock.l_start = SHARED_FIRST;
1211 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001212 break;
1213 default:
1214 assert(0);
1215 }
drh7ed97b92010-01-20 13:07:21 +00001216 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001217 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001218 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001219 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1220 if( IS_LOCK_ERROR(rc) ){
1221 pFile->lastErrno = tErrno;
1222 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 }
drhbbd42a62004-05-22 17:41:58 +00001224 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001225
drh8f941bc2009-01-14 23:03:40 +00001226
1227#ifndef NDEBUG
1228 /* Set up the transaction-counter change checking flags when
1229 ** transitioning from a SHARED to a RESERVED lock. The change
1230 ** from SHARED to RESERVED marks the beginning of a normal
1231 ** write operation (not a hot journal rollback).
1232 */
1233 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001234 && pFile->eFileLock<=SHARED_LOCK
1235 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001236 ){
1237 pFile->transCntrChng = 0;
1238 pFile->dbUpdate = 0;
1239 pFile->inNormalWrite = 1;
1240 }
1241#endif
1242
1243
danielk1977ecb2a962004-06-02 06:30:16 +00001244 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001245 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001246 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001247 }else if( eFileLock==EXCLUSIVE_LOCK ){
1248 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001249 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001250 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001251
1252end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001253 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001254 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1255 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001256 return rc;
1257}
1258
1259/*
dan08da86a2009-08-21 17:18:03 +00001260** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001261** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001262*/
1263static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001264 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001265 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001266 p->pNext = pInode->pUnused;
1267 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001268 pFile->h = -1;
1269 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001270}
1271
1272/*
drh308c2a52010-05-14 11:30:18 +00001273** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001274** must be either NO_LOCK or SHARED_LOCK.
1275**
1276** If the locking level of the file descriptor is already at or below
1277** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001278**
1279** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1280** the byte range is divided into 2 parts and the first part is unlocked then
1281** set to a read lock, then the other part is simply unlocked. This works
1282** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1283** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001284*/
drh308c2a52010-05-14 11:30:18 +00001285static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001286 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001287 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001288 struct flock lock;
1289 int rc = SQLITE_OK;
1290 int h;
drh0c2694b2009-09-03 16:23:44 +00001291 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001292
drh054889e2005-11-30 03:20:31 +00001293 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001294 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001295 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001296 getpid()));
drha6abd042004-06-09 17:37:22 +00001297
drh308c2a52010-05-14 11:30:18 +00001298 assert( eFileLock<=SHARED_LOCK );
1299 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001300 return SQLITE_OK;
1301 }
drh6c7d5c52008-11-21 20:32:33 +00001302 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001303 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001304 pInode = pFile->pInode;
1305 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001306 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001307 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001308 SimulateIOErrorBenign(1);
1309 SimulateIOError( h=(-1) )
1310 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001311
1312#ifndef NDEBUG
1313 /* When reducing a lock such that other processes can start
1314 ** reading the database file again, make sure that the
1315 ** transaction counter was updated if any part of the database
1316 ** file changed. If the transaction counter is not updated,
1317 ** other connections to the same file might not realize that
1318 ** the file has changed and hence might not know to flush their
1319 ** cache. The use of a stale cache can lead to database corruption.
1320 */
dan7c246102010-04-12 19:00:29 +00001321#if 0
drh8f941bc2009-01-14 23:03:40 +00001322 assert( pFile->inNormalWrite==0
1323 || pFile->dbUpdate==0
1324 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001325#endif
drh8f941bc2009-01-14 23:03:40 +00001326 pFile->inNormalWrite = 0;
1327#endif
1328
drh7ed97b92010-01-20 13:07:21 +00001329 /* downgrading to a shared lock on NFS involves clearing the write lock
1330 ** before establishing the readlock - to avoid a race condition we downgrade
1331 ** the lock in 2 blocks, so that part of the range will be covered by a
1332 ** write lock until the rest is covered by a read lock:
1333 ** 1: [WWWWW]
1334 ** 2: [....W]
1335 ** 3: [RRRRW]
1336 ** 4: [RRRR.]
1337 */
drh308c2a52010-05-14 11:30:18 +00001338 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001339 if( handleNFSUnlock ){
1340 off_t divSize = SHARED_SIZE - 1;
1341
1342 lock.l_type = F_UNLCK;
1343 lock.l_whence = SEEK_SET;
1344 lock.l_start = SHARED_FIRST;
1345 lock.l_len = divSize;
1346 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001347 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001348 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1349 if( IS_LOCK_ERROR(rc) ){
1350 pFile->lastErrno = tErrno;
1351 }
1352 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001353 }
drh7ed97b92010-01-20 13:07:21 +00001354 lock.l_type = F_RDLCK;
1355 lock.l_whence = SEEK_SET;
1356 lock.l_start = SHARED_FIRST;
1357 lock.l_len = divSize;
1358 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001359 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001360 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1361 if( IS_LOCK_ERROR(rc) ){
1362 pFile->lastErrno = tErrno;
1363 }
1364 goto end_unlock;
1365 }
1366 lock.l_type = F_UNLCK;
1367 lock.l_whence = SEEK_SET;
1368 lock.l_start = SHARED_FIRST+divSize;
1369 lock.l_len = SHARED_SIZE-divSize;
1370 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001371 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001372 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1373 if( IS_LOCK_ERROR(rc) ){
1374 pFile->lastErrno = tErrno;
1375 }
1376 goto end_unlock;
1377 }
1378 }else{
1379 lock.l_type = F_RDLCK;
1380 lock.l_whence = SEEK_SET;
1381 lock.l_start = SHARED_FIRST;
1382 lock.l_len = SHARED_SIZE;
1383 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001384 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001385 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1386 if( IS_LOCK_ERROR(rc) ){
1387 pFile->lastErrno = tErrno;
1388 }
1389 goto end_unlock;
1390 }
drh9c105bb2004-10-02 20:38:28 +00001391 }
1392 }
drhbbd42a62004-05-22 17:41:58 +00001393 lock.l_type = F_UNLCK;
1394 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001395 lock.l_start = PENDING_BYTE;
1396 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001397 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001398 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001399 }else{
drh0c2694b2009-09-03 16:23:44 +00001400 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001401 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1402 if( IS_LOCK_ERROR(rc) ){
1403 pFile->lastErrno = tErrno;
1404 }
drhcd731cf2009-03-28 23:23:02 +00001405 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001406 }
drhbbd42a62004-05-22 17:41:58 +00001407 }
drh308c2a52010-05-14 11:30:18 +00001408 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001409 /* Decrement the shared lock counter. Release the lock using an
1410 ** OS call only when all threads in this same process have released
1411 ** the lock.
1412 */
drh8af6c222010-05-14 12:43:01 +00001413 pInode->nShared--;
1414 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001415 lock.l_type = F_UNLCK;
1416 lock.l_whence = SEEK_SET;
1417 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001418 SimulateIOErrorBenign(1);
1419 SimulateIOError( h=(-1) )
1420 SimulateIOErrorBenign(0);
1421 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001422 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001423 }else{
drh0c2694b2009-09-03 16:23:44 +00001424 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001425 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001426 if( IS_LOCK_ERROR(rc) ){
1427 pFile->lastErrno = tErrno;
1428 }
drh8af6c222010-05-14 12:43:01 +00001429 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001430 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001431 }
drha6abd042004-06-09 17:37:22 +00001432 }
1433
drhbbd42a62004-05-22 17:41:58 +00001434 /* Decrement the count of locks against this same file. When the
1435 ** count reaches zero, close any other file descriptors whose close
1436 ** was deferred because of outstanding locks.
1437 */
drh8af6c222010-05-14 12:43:01 +00001438 pInode->nLock--;
1439 assert( pInode->nLock>=0 );
1440 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001441 int rc2 = closePendingFds(pFile);
1442 if( rc==SQLITE_OK ){
1443 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001444 }
drhbbd42a62004-05-22 17:41:58 +00001445 }
1446 }
aswift5b1a2562008-08-22 00:22:35 +00001447
1448end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001449 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001450 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001451 return rc;
drhbbd42a62004-05-22 17:41:58 +00001452}
1453
1454/*
drh308c2a52010-05-14 11:30:18 +00001455** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001456** must be either NO_LOCK or SHARED_LOCK.
1457**
1458** If the locking level of the file descriptor is already at or below
1459** the requested locking level, this routine is a no-op.
1460*/
drh308c2a52010-05-14 11:30:18 +00001461static int unixUnlock(sqlite3_file *id, int eFileLock){
1462 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001463}
1464
1465/*
danielk1977e339d652008-06-28 11:23:00 +00001466** This function performs the parts of the "close file" operation
1467** common to all locking schemes. It closes the directory and file
1468** handles, if they are valid, and sets all fields of the unixFile
1469** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001470**
1471** It is *not* necessary to hold the mutex when this routine is called,
1472** even on VxWorks. A mutex will be acquired on VxWorks by the
1473** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001474*/
1475static int closeUnixFile(sqlite3_file *id){
1476 unixFile *pFile = (unixFile*)id;
1477 if( pFile ){
1478 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001479 int err = close(pFile->dirfd);
1480 if( err ){
1481 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00001482 return unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", pFile->zPath);
aswiftaebf4132008-11-21 00:10:35 +00001483 }else{
1484 pFile->dirfd=-1;
1485 }
danielk1977e339d652008-06-28 11:23:00 +00001486 }
1487 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001488 int err = close(pFile->h);
1489 if( err ){
1490 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00001491 return unixLogError(SQLITE_IOERR_CLOSE, "close", pFile->zPath);
aswiftaebf4132008-11-21 00:10:35 +00001492 }
danielk1977e339d652008-06-28 11:23:00 +00001493 }
drh6c7d5c52008-11-21 20:32:33 +00001494#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001495 if( pFile->pId ){
1496 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001497 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001498 }
drh107886a2008-11-21 22:21:50 +00001499 vxworksReleaseFileId(pFile->pId);
1500 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001501 }
1502#endif
drhff59a112010-05-14 20:15:51 +00001503 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001504 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001505 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001506 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001507 }
1508 return SQLITE_OK;
1509}
1510
1511/*
danielk1977e3026632004-06-22 11:29:02 +00001512** Close a file.
1513*/
danielk197762079062007-08-15 17:08:46 +00001514static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001515 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001516 if( id ){
1517 unixFile *pFile = (unixFile *)id;
1518 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001519 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001520 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001521 /* If there are outstanding locks, do not actually close the file just
1522 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001523 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001524 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001525 */
dan08da86a2009-08-21 17:18:03 +00001526 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001527 }
danb0ac3e32010-06-16 10:55:42 +00001528 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001529 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001530 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001531 }
aswiftaebf4132008-11-21 00:10:35 +00001532 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001533}
1534
drh734c9862008-11-28 15:37:20 +00001535/************** End of the posix advisory lock implementation *****************
1536******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001537
drh734c9862008-11-28 15:37:20 +00001538/******************************************************************************
1539****************************** No-op Locking **********************************
1540**
1541** Of the various locking implementations available, this is by far the
1542** simplest: locking is ignored. No attempt is made to lock the database
1543** file for reading or writing.
1544**
1545** This locking mode is appropriate for use on read-only databases
1546** (ex: databases that are burned into CD-ROM, for example.) It can
1547** also be used if the application employs some external mechanism to
1548** prevent simultaneous access of the same database by two or more
1549** database connections. But there is a serious risk of database
1550** corruption if this locking mode is used in situations where multiple
1551** database connections are accessing the same database file at the same
1552** time and one or more of those connections are writing.
1553*/
drhbfe66312006-10-03 17:40:40 +00001554
drh734c9862008-11-28 15:37:20 +00001555static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1556 UNUSED_PARAMETER(NotUsed);
1557 *pResOut = 0;
1558 return SQLITE_OK;
1559}
drh734c9862008-11-28 15:37:20 +00001560static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1561 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1562 return SQLITE_OK;
1563}
drh734c9862008-11-28 15:37:20 +00001564static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1565 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1566 return SQLITE_OK;
1567}
1568
1569/*
drh9b35ea62008-11-29 02:20:26 +00001570** Close the file.
drh734c9862008-11-28 15:37:20 +00001571*/
1572static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001573 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001574}
1575
1576/******************* End of the no-op lock implementation *********************
1577******************************************************************************/
1578
1579/******************************************************************************
1580************************* Begin dot-file Locking ******************************
1581**
drh0c2694b2009-09-03 16:23:44 +00001582** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001583** files in order to control access to the database. This works on just
1584** about every filesystem imaginable. But there are serious downsides:
1585**
1586** (1) There is zero concurrency. A single reader blocks all other
1587** connections from reading or writing the database.
1588**
1589** (2) An application crash or power loss can leave stale lock files
1590** sitting around that need to be cleared manually.
1591**
1592** Nevertheless, a dotlock is an appropriate locking mode for use if no
1593** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001594**
1595** Dotfile locking works by creating a file in the same directory as the
1596** database and with the same name but with a ".lock" extension added.
1597** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1598** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001599*/
1600
1601/*
1602** The file suffix added to the data base filename in order to create the
1603** lock file.
1604*/
1605#define DOTLOCK_SUFFIX ".lock"
1606
drh7708e972008-11-29 00:56:52 +00001607/*
1608** This routine checks if there is a RESERVED lock held on the specified
1609** file by this or any other process. If such a lock is held, set *pResOut
1610** to a non-zero value otherwise *pResOut is set to zero. The return value
1611** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1612**
1613** In dotfile locking, either a lock exists or it does not. So in this
1614** variation of CheckReservedLock(), *pResOut is set to true if any lock
1615** is held on the file and false if the file is unlocked.
1616*/
drh734c9862008-11-28 15:37:20 +00001617static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1618 int rc = SQLITE_OK;
1619 int reserved = 0;
1620 unixFile *pFile = (unixFile*)id;
1621
1622 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1623
1624 assert( pFile );
1625
1626 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001627 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001628 /* Either this connection or some other connection in the same process
1629 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001630 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001631 }else{
1632 /* The lock is held if and only if the lockfile exists */
1633 const char *zLockFile = (const char*)pFile->lockingContext;
1634 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001635 }
drh308c2a52010-05-14 11:30:18 +00001636 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001637 *pResOut = reserved;
1638 return rc;
1639}
1640
drh7708e972008-11-29 00:56:52 +00001641/*
drh308c2a52010-05-14 11:30:18 +00001642** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001643** of the following:
1644**
1645** (1) SHARED_LOCK
1646** (2) RESERVED_LOCK
1647** (3) PENDING_LOCK
1648** (4) EXCLUSIVE_LOCK
1649**
1650** Sometimes when requesting one lock state, additional lock states
1651** are inserted in between. The locking might fail on one of the later
1652** transitions leaving the lock state different from what it started but
1653** still short of its goal. The following chart shows the allowed
1654** transitions and the inserted intermediate states:
1655**
1656** UNLOCKED -> SHARED
1657** SHARED -> RESERVED
1658** SHARED -> (PENDING) -> EXCLUSIVE
1659** RESERVED -> (PENDING) -> EXCLUSIVE
1660** PENDING -> EXCLUSIVE
1661**
1662** This routine will only increase a lock. Use the sqlite3OsUnlock()
1663** routine to lower a locking level.
1664**
1665** With dotfile locking, we really only support state (4): EXCLUSIVE.
1666** But we track the other locking levels internally.
1667*/
drh308c2a52010-05-14 11:30:18 +00001668static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001669 unixFile *pFile = (unixFile*)id;
1670 int fd;
1671 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001672 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001673
drh7708e972008-11-29 00:56:52 +00001674
1675 /* If we have any lock, then the lock file already exists. All we have
1676 ** to do is adjust our internal record of the lock level.
1677 */
drh308c2a52010-05-14 11:30:18 +00001678 if( pFile->eFileLock > NO_LOCK ){
1679 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001680#if !OS_VXWORKS
1681 /* Always update the timestamp on the old file */
1682 utimes(zLockFile, NULL);
1683#endif
drh7708e972008-11-29 00:56:52 +00001684 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001685 }
1686
1687 /* grab an exclusive lock */
1688 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1689 if( fd<0 ){
1690 /* failed to open/create the file, someone else may have stolen the lock */
1691 int tErrno = errno;
1692 if( EEXIST == tErrno ){
1693 rc = SQLITE_BUSY;
1694 } else {
1695 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1696 if( IS_LOCK_ERROR(rc) ){
1697 pFile->lastErrno = tErrno;
1698 }
1699 }
drh7708e972008-11-29 00:56:52 +00001700 return rc;
drh734c9862008-11-28 15:37:20 +00001701 }
1702 if( close(fd) ){
1703 pFile->lastErrno = errno;
1704 rc = SQLITE_IOERR_CLOSE;
1705 }
1706
1707 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001708 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001709 return rc;
1710}
1711
drh7708e972008-11-29 00:56:52 +00001712/*
drh308c2a52010-05-14 11:30:18 +00001713** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001714** must be either NO_LOCK or SHARED_LOCK.
1715**
1716** If the locking level of the file descriptor is already at or below
1717** the requested locking level, this routine is a no-op.
1718**
1719** When the locking level reaches NO_LOCK, delete the lock file.
1720*/
drh308c2a52010-05-14 11:30:18 +00001721static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001722 unixFile *pFile = (unixFile*)id;
1723 char *zLockFile = (char *)pFile->lockingContext;
1724
1725 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001726 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1727 pFile->eFileLock, getpid()));
1728 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001729
1730 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001731 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001732 return SQLITE_OK;
1733 }
drh7708e972008-11-29 00:56:52 +00001734
1735 /* To downgrade to shared, simply update our internal notion of the
1736 ** lock state. No need to mess with the file on disk.
1737 */
drh308c2a52010-05-14 11:30:18 +00001738 if( eFileLock==SHARED_LOCK ){
1739 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001740 return SQLITE_OK;
1741 }
1742
drh7708e972008-11-29 00:56:52 +00001743 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001744 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001745 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001746 int rc = 0;
1747 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001748 if( ENOENT != tErrno ){
1749 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1750 }
1751 if( IS_LOCK_ERROR(rc) ){
1752 pFile->lastErrno = tErrno;
1753 }
1754 return rc;
1755 }
drh308c2a52010-05-14 11:30:18 +00001756 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001757 return SQLITE_OK;
1758}
1759
1760/*
drh9b35ea62008-11-29 02:20:26 +00001761** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001762*/
1763static int dotlockClose(sqlite3_file *id) {
1764 int rc;
1765 if( id ){
1766 unixFile *pFile = (unixFile*)id;
1767 dotlockUnlock(id, NO_LOCK);
1768 sqlite3_free(pFile->lockingContext);
1769 }
drh734c9862008-11-28 15:37:20 +00001770 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001771 return rc;
1772}
1773/****************** End of the dot-file lock implementation *******************
1774******************************************************************************/
1775
1776/******************************************************************************
1777************************** Begin flock Locking ********************************
1778**
1779** Use the flock() system call to do file locking.
1780**
drh6b9d6dd2008-12-03 19:34:47 +00001781** flock() locking is like dot-file locking in that the various
1782** fine-grain locking levels supported by SQLite are collapsed into
1783** a single exclusive lock. In other words, SHARED, RESERVED, and
1784** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1785** still works when you do this, but concurrency is reduced since
1786** only a single process can be reading the database at a time.
1787**
drh734c9862008-11-28 15:37:20 +00001788** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1789** compiling for VXWORKS.
1790*/
1791#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001792
drh6b9d6dd2008-12-03 19:34:47 +00001793/*
1794** This routine checks if there is a RESERVED lock held on the specified
1795** file by this or any other process. If such a lock is held, set *pResOut
1796** to a non-zero value otherwise *pResOut is set to zero. The return value
1797** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1798*/
drh734c9862008-11-28 15:37:20 +00001799static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1800 int rc = SQLITE_OK;
1801 int reserved = 0;
1802 unixFile *pFile = (unixFile*)id;
1803
1804 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1805
1806 assert( pFile );
1807
1808 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001809 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001810 reserved = 1;
1811 }
1812
1813 /* Otherwise see if some other process holds it. */
1814 if( !reserved ){
1815 /* attempt to get the lock */
1816 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1817 if( !lrc ){
1818 /* got the lock, unlock it */
1819 lrc = flock(pFile->h, LOCK_UN);
1820 if ( lrc ) {
1821 int tErrno = errno;
1822 /* unlock failed with an error */
1823 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1824 if( IS_LOCK_ERROR(lrc) ){
1825 pFile->lastErrno = tErrno;
1826 rc = lrc;
1827 }
1828 }
1829 } else {
1830 int tErrno = errno;
1831 reserved = 1;
1832 /* someone else might have it reserved */
1833 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1834 if( IS_LOCK_ERROR(lrc) ){
1835 pFile->lastErrno = tErrno;
1836 rc = lrc;
1837 }
1838 }
1839 }
drh308c2a52010-05-14 11:30:18 +00001840 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001841
1842#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1843 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1844 rc = SQLITE_OK;
1845 reserved=1;
1846 }
1847#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1848 *pResOut = reserved;
1849 return rc;
1850}
1851
drh6b9d6dd2008-12-03 19:34:47 +00001852/*
drh308c2a52010-05-14 11:30:18 +00001853** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001854** of the following:
1855**
1856** (1) SHARED_LOCK
1857** (2) RESERVED_LOCK
1858** (3) PENDING_LOCK
1859** (4) EXCLUSIVE_LOCK
1860**
1861** Sometimes when requesting one lock state, additional lock states
1862** are inserted in between. The locking might fail on one of the later
1863** transitions leaving the lock state different from what it started but
1864** still short of its goal. The following chart shows the allowed
1865** transitions and the inserted intermediate states:
1866**
1867** UNLOCKED -> SHARED
1868** SHARED -> RESERVED
1869** SHARED -> (PENDING) -> EXCLUSIVE
1870** RESERVED -> (PENDING) -> EXCLUSIVE
1871** PENDING -> EXCLUSIVE
1872**
1873** flock() only really support EXCLUSIVE locks. We track intermediate
1874** lock states in the sqlite3_file structure, but all locks SHARED or
1875** above are really EXCLUSIVE locks and exclude all other processes from
1876** access the file.
1877**
1878** This routine will only increase a lock. Use the sqlite3OsUnlock()
1879** routine to lower a locking level.
1880*/
drh308c2a52010-05-14 11:30:18 +00001881static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001882 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001883 unixFile *pFile = (unixFile*)id;
1884
1885 assert( pFile );
1886
1887 /* if we already have a lock, it is exclusive.
1888 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001889 if (pFile->eFileLock > NO_LOCK) {
1890 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001891 return SQLITE_OK;
1892 }
1893
1894 /* grab an exclusive lock */
1895
1896 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1897 int tErrno = errno;
1898 /* didn't get, must be busy */
1899 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1900 if( IS_LOCK_ERROR(rc) ){
1901 pFile->lastErrno = tErrno;
1902 }
1903 } else {
1904 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001905 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001906 }
drh308c2a52010-05-14 11:30:18 +00001907 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1908 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001909#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1910 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1911 rc = SQLITE_BUSY;
1912 }
1913#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1914 return rc;
1915}
1916
drh6b9d6dd2008-12-03 19:34:47 +00001917
1918/*
drh308c2a52010-05-14 11:30:18 +00001919** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001920** must be either NO_LOCK or SHARED_LOCK.
1921**
1922** If the locking level of the file descriptor is already at or below
1923** the requested locking level, this routine is a no-op.
1924*/
drh308c2a52010-05-14 11:30:18 +00001925static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001926 unixFile *pFile = (unixFile*)id;
1927
1928 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001929 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1930 pFile->eFileLock, getpid()));
1931 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001932
1933 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001934 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001935 return SQLITE_OK;
1936 }
1937
1938 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001939 if (eFileLock==SHARED_LOCK) {
1940 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001941 return SQLITE_OK;
1942 }
1943
1944 /* no, really, unlock. */
1945 int rc = flock(pFile->h, LOCK_UN);
1946 if (rc) {
1947 int r, tErrno = errno;
1948 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1949 if( IS_LOCK_ERROR(r) ){
1950 pFile->lastErrno = tErrno;
1951 }
1952#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1953 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1954 r = SQLITE_BUSY;
1955 }
1956#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1957
1958 return r;
1959 } else {
drh308c2a52010-05-14 11:30:18 +00001960 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001961 return SQLITE_OK;
1962 }
1963}
1964
1965/*
1966** Close a file.
1967*/
1968static int flockClose(sqlite3_file *id) {
1969 if( id ){
1970 flockUnlock(id, NO_LOCK);
1971 }
1972 return closeUnixFile(id);
1973}
1974
1975#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1976
1977/******************* End of the flock lock implementation *********************
1978******************************************************************************/
1979
1980/******************************************************************************
1981************************ Begin Named Semaphore Locking ************************
1982**
1983** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00001984**
1985** Semaphore locking is like dot-lock and flock in that it really only
1986** supports EXCLUSIVE locking. Only a single process can read or write
1987** the database file at a time. This reduces potential concurrency, but
1988** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00001989*/
1990#if OS_VXWORKS
1991
drh6b9d6dd2008-12-03 19:34:47 +00001992/*
1993** This routine checks if there is a RESERVED lock held on the specified
1994** file by this or any other process. If such a lock is held, set *pResOut
1995** to a non-zero value otherwise *pResOut is set to zero. The return value
1996** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1997*/
drh734c9862008-11-28 15:37:20 +00001998static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1999 int rc = SQLITE_OK;
2000 int reserved = 0;
2001 unixFile *pFile = (unixFile*)id;
2002
2003 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2004
2005 assert( pFile );
2006
2007 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002008 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002009 reserved = 1;
2010 }
2011
2012 /* Otherwise see if some other process holds it. */
2013 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002014 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002015 struct stat statBuf;
2016
2017 if( sem_trywait(pSem)==-1 ){
2018 int tErrno = errno;
2019 if( EAGAIN != tErrno ){
2020 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2021 pFile->lastErrno = tErrno;
2022 } else {
2023 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002024 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002025 }
2026 }else{
2027 /* we could have it if we want it */
2028 sem_post(pSem);
2029 }
2030 }
drh308c2a52010-05-14 11:30:18 +00002031 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002032
2033 *pResOut = reserved;
2034 return rc;
2035}
2036
drh6b9d6dd2008-12-03 19:34:47 +00002037/*
drh308c2a52010-05-14 11:30:18 +00002038** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002039** of the following:
2040**
2041** (1) SHARED_LOCK
2042** (2) RESERVED_LOCK
2043** (3) PENDING_LOCK
2044** (4) EXCLUSIVE_LOCK
2045**
2046** Sometimes when requesting one lock state, additional lock states
2047** are inserted in between. The locking might fail on one of the later
2048** transitions leaving the lock state different from what it started but
2049** still short of its goal. The following chart shows the allowed
2050** transitions and the inserted intermediate states:
2051**
2052** UNLOCKED -> SHARED
2053** SHARED -> RESERVED
2054** SHARED -> (PENDING) -> EXCLUSIVE
2055** RESERVED -> (PENDING) -> EXCLUSIVE
2056** PENDING -> EXCLUSIVE
2057**
2058** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2059** lock states in the sqlite3_file structure, but all locks SHARED or
2060** above are really EXCLUSIVE locks and exclude all other processes from
2061** access the file.
2062**
2063** This routine will only increase a lock. Use the sqlite3OsUnlock()
2064** routine to lower a locking level.
2065*/
drh308c2a52010-05-14 11:30:18 +00002066static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002067 unixFile *pFile = (unixFile*)id;
2068 int fd;
drh8af6c222010-05-14 12:43:01 +00002069 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002070 int rc = SQLITE_OK;
2071
2072 /* if we already have a lock, it is exclusive.
2073 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002074 if (pFile->eFileLock > NO_LOCK) {
2075 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002076 rc = SQLITE_OK;
2077 goto sem_end_lock;
2078 }
2079
2080 /* lock semaphore now but bail out when already locked. */
2081 if( sem_trywait(pSem)==-1 ){
2082 rc = SQLITE_BUSY;
2083 goto sem_end_lock;
2084 }
2085
2086 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002087 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002088
2089 sem_end_lock:
2090 return rc;
2091}
2092
drh6b9d6dd2008-12-03 19:34:47 +00002093/*
drh308c2a52010-05-14 11:30:18 +00002094** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002095** must be either NO_LOCK or SHARED_LOCK.
2096**
2097** If the locking level of the file descriptor is already at or below
2098** the requested locking level, this routine is a no-op.
2099*/
drh308c2a52010-05-14 11:30:18 +00002100static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002101 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002102 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002103
2104 assert( pFile );
2105 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002106 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2107 pFile->eFileLock, getpid()));
2108 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002109
2110 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002111 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002112 return SQLITE_OK;
2113 }
2114
2115 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002116 if (eFileLock==SHARED_LOCK) {
2117 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002118 return SQLITE_OK;
2119 }
2120
2121 /* no, really unlock. */
2122 if ( sem_post(pSem)==-1 ) {
2123 int rc, tErrno = errno;
2124 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2125 if( IS_LOCK_ERROR(rc) ){
2126 pFile->lastErrno = tErrno;
2127 }
2128 return rc;
2129 }
drh308c2a52010-05-14 11:30:18 +00002130 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002131 return SQLITE_OK;
2132}
2133
2134/*
2135 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002136 */
drh734c9862008-11-28 15:37:20 +00002137static int semClose(sqlite3_file *id) {
2138 if( id ){
2139 unixFile *pFile = (unixFile*)id;
2140 semUnlock(id, NO_LOCK);
2141 assert( pFile );
2142 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002143 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002144 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002145 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002146 }
2147 return SQLITE_OK;
2148}
2149
2150#endif /* OS_VXWORKS */
2151/*
2152** Named semaphore locking is only available on VxWorks.
2153**
2154*************** End of the named semaphore lock implementation ****************
2155******************************************************************************/
2156
2157
2158/******************************************************************************
2159*************************** Begin AFP Locking *********************************
2160**
2161** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2162** on Apple Macintosh computers - both OS9 and OSX.
2163**
2164** Third-party implementations of AFP are available. But this code here
2165** only works on OSX.
2166*/
2167
drhd2cb50b2009-01-09 21:41:17 +00002168#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002169/*
2170** The afpLockingContext structure contains all afp lock specific state
2171*/
drhbfe66312006-10-03 17:40:40 +00002172typedef struct afpLockingContext afpLockingContext;
2173struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002174 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002175 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002176};
2177
2178struct ByteRangeLockPB2
2179{
2180 unsigned long long offset; /* offset to first byte to lock */
2181 unsigned long long length; /* nbr of bytes to lock */
2182 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2183 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2184 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2185 int fd; /* file desc to assoc this lock with */
2186};
2187
drhfd131da2007-08-07 17:13:03 +00002188#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002189
drh6b9d6dd2008-12-03 19:34:47 +00002190/*
2191** This is a utility for setting or clearing a bit-range lock on an
2192** AFP filesystem.
2193**
2194** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2195*/
2196static int afpSetLock(
2197 const char *path, /* Name of the file to be locked or unlocked */
2198 unixFile *pFile, /* Open file descriptor on path */
2199 unsigned long long offset, /* First byte to be locked */
2200 unsigned long long length, /* Number of bytes to lock */
2201 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002202){
drh6b9d6dd2008-12-03 19:34:47 +00002203 struct ByteRangeLockPB2 pb;
2204 int err;
drhbfe66312006-10-03 17:40:40 +00002205
2206 pb.unLockFlag = setLockFlag ? 0 : 1;
2207 pb.startEndFlag = 0;
2208 pb.offset = offset;
2209 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002210 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002211
drh308c2a52010-05-14 11:30:18 +00002212 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002213 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002214 offset, length));
drhbfe66312006-10-03 17:40:40 +00002215 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2216 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002217 int rc;
2218 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002219 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2220 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002221#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2222 rc = SQLITE_BUSY;
2223#else
drh734c9862008-11-28 15:37:20 +00002224 rc = sqliteErrorFromPosixError(tErrno,
2225 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002226#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002227 if( IS_LOCK_ERROR(rc) ){
2228 pFile->lastErrno = tErrno;
2229 }
2230 return rc;
drhbfe66312006-10-03 17:40:40 +00002231 } else {
aswift5b1a2562008-08-22 00:22:35 +00002232 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002233 }
2234}
2235
drh6b9d6dd2008-12-03 19:34:47 +00002236/*
2237** This routine checks if there is a RESERVED lock held on the specified
2238** file by this or any other process. If such a lock is held, set *pResOut
2239** to a non-zero value otherwise *pResOut is set to zero. The return value
2240** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2241*/
danielk1977e339d652008-06-28 11:23:00 +00002242static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002243 int rc = SQLITE_OK;
2244 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002245 unixFile *pFile = (unixFile*)id;
2246
aswift5b1a2562008-08-22 00:22:35 +00002247 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2248
2249 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002250 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002251 if( context->reserved ){
2252 *pResOut = 1;
2253 return SQLITE_OK;
2254 }
drh8af6c222010-05-14 12:43:01 +00002255 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002256
2257 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002258 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002259 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002260 }
2261
2262 /* Otherwise see if some other process holds it.
2263 */
aswift5b1a2562008-08-22 00:22:35 +00002264 if( !reserved ){
2265 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002266 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002267 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002268 /* if we succeeded in taking the reserved lock, unlock it to restore
2269 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002270 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002271 } else {
2272 /* if we failed to get the lock then someone else must have it */
2273 reserved = 1;
2274 }
2275 if( IS_LOCK_ERROR(lrc) ){
2276 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002277 }
2278 }
drhbfe66312006-10-03 17:40:40 +00002279
drh7ed97b92010-01-20 13:07:21 +00002280 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002281 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002282
2283 *pResOut = reserved;
2284 return rc;
drhbfe66312006-10-03 17:40:40 +00002285}
2286
drh6b9d6dd2008-12-03 19:34:47 +00002287/*
drh308c2a52010-05-14 11:30:18 +00002288** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002289** of the following:
2290**
2291** (1) SHARED_LOCK
2292** (2) RESERVED_LOCK
2293** (3) PENDING_LOCK
2294** (4) EXCLUSIVE_LOCK
2295**
2296** Sometimes when requesting one lock state, additional lock states
2297** are inserted in between. The locking might fail on one of the later
2298** transitions leaving the lock state different from what it started but
2299** still short of its goal. The following chart shows the allowed
2300** transitions and the inserted intermediate states:
2301**
2302** UNLOCKED -> SHARED
2303** SHARED -> RESERVED
2304** SHARED -> (PENDING) -> EXCLUSIVE
2305** RESERVED -> (PENDING) -> EXCLUSIVE
2306** PENDING -> EXCLUSIVE
2307**
2308** This routine will only increase a lock. Use the sqlite3OsUnlock()
2309** routine to lower a locking level.
2310*/
drh308c2a52010-05-14 11:30:18 +00002311static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002312 int rc = SQLITE_OK;
2313 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002314 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002315 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002316
2317 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002318 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2319 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002320 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002321
drhbfe66312006-10-03 17:40:40 +00002322 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002323 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002324 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002325 */
drh308c2a52010-05-14 11:30:18 +00002326 if( pFile->eFileLock>=eFileLock ){
2327 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2328 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002329 return SQLITE_OK;
2330 }
2331
2332 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002333 ** (1) We never move from unlocked to anything higher than shared lock.
2334 ** (2) SQLite never explicitly requests a pendig lock.
2335 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002336 */
drh308c2a52010-05-14 11:30:18 +00002337 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2338 assert( eFileLock!=PENDING_LOCK );
2339 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002340
drh8af6c222010-05-14 12:43:01 +00002341 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002342 */
drh6c7d5c52008-11-21 20:32:33 +00002343 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002344 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002345
2346 /* If some thread using this PID has a lock via a different unixFile*
2347 ** handle that precludes the requested lock, return BUSY.
2348 */
drh8af6c222010-05-14 12:43:01 +00002349 if( (pFile->eFileLock!=pInode->eFileLock &&
2350 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002351 ){
2352 rc = SQLITE_BUSY;
2353 goto afp_end_lock;
2354 }
2355
2356 /* If a SHARED lock is requested, and some thread using this PID already
2357 ** has a SHARED or RESERVED lock, then increment reference counts and
2358 ** return SQLITE_OK.
2359 */
drh308c2a52010-05-14 11:30:18 +00002360 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002361 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002362 assert( eFileLock==SHARED_LOCK );
2363 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002364 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002365 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002366 pInode->nShared++;
2367 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002368 goto afp_end_lock;
2369 }
drhbfe66312006-10-03 17:40:40 +00002370
2371 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002372 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2373 ** be released.
2374 */
drh308c2a52010-05-14 11:30:18 +00002375 if( eFileLock==SHARED_LOCK
2376 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002377 ){
2378 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002379 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002380 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002381 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002382 goto afp_end_lock;
2383 }
2384 }
2385
2386 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002387 ** operating system calls for the specified lock.
2388 */
drh308c2a52010-05-14 11:30:18 +00002389 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002390 int lrc1, lrc2, lrc1Errno;
2391 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002392
drh8af6c222010-05-14 12:43:01 +00002393 assert( pInode->nShared==0 );
2394 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002395
2396 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002397 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002398 /* note that the quality of the randomness doesn't matter that much */
2399 lk = random();
drh8af6c222010-05-14 12:43:01 +00002400 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002401 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002402 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002403 if( IS_LOCK_ERROR(lrc1) ){
2404 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002405 }
aswift5b1a2562008-08-22 00:22:35 +00002406 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002407 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002408
aswift5b1a2562008-08-22 00:22:35 +00002409 if( IS_LOCK_ERROR(lrc1) ) {
2410 pFile->lastErrno = lrc1Errno;
2411 rc = lrc1;
2412 goto afp_end_lock;
2413 } else if( IS_LOCK_ERROR(lrc2) ){
2414 rc = lrc2;
2415 goto afp_end_lock;
2416 } else if( lrc1 != SQLITE_OK ) {
2417 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002418 } else {
drh308c2a52010-05-14 11:30:18 +00002419 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002420 pInode->nLock++;
2421 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002422 }
drh8af6c222010-05-14 12:43:01 +00002423 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002424 /* We are trying for an exclusive lock but another thread in this
2425 ** same process is still holding a shared lock. */
2426 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002427 }else{
2428 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2429 ** assumed that there is a SHARED or greater lock on the file
2430 ** already.
2431 */
2432 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002433 assert( 0!=pFile->eFileLock );
2434 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002435 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002436 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002437 if( !failed ){
2438 context->reserved = 1;
2439 }
drhbfe66312006-10-03 17:40:40 +00002440 }
drh308c2a52010-05-14 11:30:18 +00002441 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002442 /* Acquire an EXCLUSIVE lock */
2443
2444 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002445 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002446 */
drh6b9d6dd2008-12-03 19:34:47 +00002447 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002448 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002449 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002450 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002451 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002452 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002453 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002454 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002455 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2456 ** a critical I/O error
2457 */
2458 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2459 SQLITE_IOERR_LOCK;
2460 goto afp_end_lock;
2461 }
2462 }else{
aswift5b1a2562008-08-22 00:22:35 +00002463 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002464 }
2465 }
aswift5b1a2562008-08-22 00:22:35 +00002466 if( failed ){
2467 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002468 }
2469 }
2470
2471 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002472 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002473 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002474 }else if( eFileLock==EXCLUSIVE_LOCK ){
2475 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002476 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002477 }
2478
2479afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002480 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002481 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2482 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002483 return rc;
2484}
2485
2486/*
drh308c2a52010-05-14 11:30:18 +00002487** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002488** must be either NO_LOCK or SHARED_LOCK.
2489**
2490** If the locking level of the file descriptor is already at or below
2491** the requested locking level, this routine is a no-op.
2492*/
drh308c2a52010-05-14 11:30:18 +00002493static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002494 int rc = SQLITE_OK;
2495 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002496 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002497 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2498 int skipShared = 0;
2499#ifdef SQLITE_TEST
2500 int h = pFile->h;
2501#endif
drhbfe66312006-10-03 17:40:40 +00002502
2503 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002504 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002505 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002506 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002507
drh308c2a52010-05-14 11:30:18 +00002508 assert( eFileLock<=SHARED_LOCK );
2509 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002510 return SQLITE_OK;
2511 }
drh6c7d5c52008-11-21 20:32:33 +00002512 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002513 pInode = pFile->pInode;
2514 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002515 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002516 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002517 SimulateIOErrorBenign(1);
2518 SimulateIOError( h=(-1) )
2519 SimulateIOErrorBenign(0);
2520
2521#ifndef NDEBUG
2522 /* When reducing a lock such that other processes can start
2523 ** reading the database file again, make sure that the
2524 ** transaction counter was updated if any part of the database
2525 ** file changed. If the transaction counter is not updated,
2526 ** other connections to the same file might not realize that
2527 ** the file has changed and hence might not know to flush their
2528 ** cache. The use of a stale cache can lead to database corruption.
2529 */
2530 assert( pFile->inNormalWrite==0
2531 || pFile->dbUpdate==0
2532 || pFile->transCntrChng==1 );
2533 pFile->inNormalWrite = 0;
2534#endif
aswiftaebf4132008-11-21 00:10:35 +00002535
drh308c2a52010-05-14 11:30:18 +00002536 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002537 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002538 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002539 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002540 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002541 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2542 } else {
2543 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002544 }
2545 }
drh308c2a52010-05-14 11:30:18 +00002546 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002547 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002548 }
drh308c2a52010-05-14 11:30:18 +00002549 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002550 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2551 if( !rc ){
2552 context->reserved = 0;
2553 }
aswiftaebf4132008-11-21 00:10:35 +00002554 }
drh8af6c222010-05-14 12:43:01 +00002555 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2556 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002557 }
aswiftaebf4132008-11-21 00:10:35 +00002558 }
drh308c2a52010-05-14 11:30:18 +00002559 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002560
drh7ed97b92010-01-20 13:07:21 +00002561 /* Decrement the shared lock counter. Release the lock using an
2562 ** OS call only when all threads in this same process have released
2563 ** the lock.
2564 */
drh8af6c222010-05-14 12:43:01 +00002565 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2566 pInode->nShared--;
2567 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002568 SimulateIOErrorBenign(1);
2569 SimulateIOError( h=(-1) )
2570 SimulateIOErrorBenign(0);
2571 if( !skipShared ){
2572 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2573 }
2574 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002575 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002576 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002577 }
2578 }
2579 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002580 pInode->nLock--;
2581 assert( pInode->nLock>=0 );
2582 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002583 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002584 }
2585 }
drhbfe66312006-10-03 17:40:40 +00002586 }
drh7ed97b92010-01-20 13:07:21 +00002587
drh6c7d5c52008-11-21 20:32:33 +00002588 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002589 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002590 return rc;
2591}
2592
2593/*
drh339eb0b2008-03-07 15:34:11 +00002594** Close a file & cleanup AFP specific locking context
2595*/
danielk1977e339d652008-06-28 11:23:00 +00002596static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002597 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002598 if( id ){
2599 unixFile *pFile = (unixFile*)id;
2600 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002601 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002602 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002603 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002604 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002605 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002606 ** the last lock is cleared.
2607 */
dan08da86a2009-08-21 17:18:03 +00002608 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002609 }
danb0ac3e32010-06-16 10:55:42 +00002610 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002611 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002612 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002613 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002614 }
drh7ed97b92010-01-20 13:07:21 +00002615 return rc;
drhbfe66312006-10-03 17:40:40 +00002616}
2617
drhd2cb50b2009-01-09 21:41:17 +00002618#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002619/*
2620** The code above is the AFP lock implementation. The code is specific
2621** to MacOSX and does not work on other unix platforms. No alternative
2622** is available. If you don't compile for a mac, then the "unix-afp"
2623** VFS is not available.
2624**
2625********************* End of the AFP lock implementation **********************
2626******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002627
drh7ed97b92010-01-20 13:07:21 +00002628/******************************************************************************
2629*************************** Begin NFS Locking ********************************/
2630
2631#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2632/*
drh308c2a52010-05-14 11:30:18 +00002633 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002634 ** must be either NO_LOCK or SHARED_LOCK.
2635 **
2636 ** If the locking level of the file descriptor is already at or below
2637 ** the requested locking level, this routine is a no-op.
2638 */
drh308c2a52010-05-14 11:30:18 +00002639static int nfsUnlock(sqlite3_file *id, int eFileLock){
2640 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002641}
2642
2643#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2644/*
2645** The code above is the NFS lock implementation. The code is specific
2646** to MacOSX and does not work on other unix platforms. No alternative
2647** is available.
2648**
2649********************* End of the NFS lock implementation **********************
2650******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002651
2652/******************************************************************************
2653**************** Non-locking sqlite3_file methods *****************************
2654**
2655** The next division contains implementations for all methods of the
2656** sqlite3_file object other than the locking methods. The locking
2657** methods were defined in divisions above (one locking method per
2658** division). Those methods that are common to all locking modes
2659** are gather together into this division.
2660*/
drhbfe66312006-10-03 17:40:40 +00002661
2662/*
drh734c9862008-11-28 15:37:20 +00002663** Seek to the offset passed as the second argument, then read cnt
2664** bytes into pBuf. Return the number of bytes actually read.
2665**
2666** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2667** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2668** one system to another. Since SQLite does not define USE_PREAD
2669** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2670** See tickets #2741 and #2681.
2671**
2672** To avoid stomping the errno value on a failed read the lastErrno value
2673** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002674*/
drh734c9862008-11-28 15:37:20 +00002675static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2676 int got;
drh7ed97b92010-01-20 13:07:21 +00002677#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002678 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002679#endif
drh734c9862008-11-28 15:37:20 +00002680 TIMER_START;
2681#if defined(USE_PREAD)
2682 got = pread(id->h, pBuf, cnt, offset);
2683 SimulateIOError( got = -1 );
2684#elif defined(USE_PREAD64)
2685 got = pread64(id->h, pBuf, cnt, offset);
2686 SimulateIOError( got = -1 );
2687#else
2688 newOffset = lseek(id->h, offset, SEEK_SET);
2689 SimulateIOError( newOffset-- );
2690 if( newOffset!=offset ){
2691 if( newOffset == -1 ){
2692 ((unixFile*)id)->lastErrno = errno;
2693 }else{
2694 ((unixFile*)id)->lastErrno = 0;
2695 }
2696 return -1;
2697 }
2698 got = read(id->h, pBuf, cnt);
2699#endif
2700 TIMER_END;
2701 if( got<0 ){
2702 ((unixFile*)id)->lastErrno = errno;
2703 }
drh308c2a52010-05-14 11:30:18 +00002704 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002705 return got;
drhbfe66312006-10-03 17:40:40 +00002706}
2707
2708/*
drh734c9862008-11-28 15:37:20 +00002709** Read data from a file into a buffer. Return SQLITE_OK if all
2710** bytes were read successfully and SQLITE_IOERR if anything goes
2711** wrong.
drh339eb0b2008-03-07 15:34:11 +00002712*/
drh734c9862008-11-28 15:37:20 +00002713static int unixRead(
2714 sqlite3_file *id,
2715 void *pBuf,
2716 int amt,
2717 sqlite3_int64 offset
2718){
dan08da86a2009-08-21 17:18:03 +00002719 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002720 int got;
2721 assert( id );
drh08c6d442009-02-09 17:34:07 +00002722
dan08da86a2009-08-21 17:18:03 +00002723 /* If this is a database file (not a journal, master-journal or temp
2724 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002725#if 0
dane946c392009-08-22 11:39:46 +00002726 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002727 || offset>=PENDING_BYTE+512
2728 || offset+amt<=PENDING_BYTE
2729 );
dan7c246102010-04-12 19:00:29 +00002730#endif
drh08c6d442009-02-09 17:34:07 +00002731
dan08da86a2009-08-21 17:18:03 +00002732 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002733 if( got==amt ){
2734 return SQLITE_OK;
2735 }else if( got<0 ){
2736 /* lastErrno set by seekAndRead */
2737 return SQLITE_IOERR_READ;
2738 }else{
dan08da86a2009-08-21 17:18:03 +00002739 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002740 /* Unread parts of the buffer must be zero-filled */
2741 memset(&((char*)pBuf)[got], 0, amt-got);
2742 return SQLITE_IOERR_SHORT_READ;
2743 }
2744}
2745
2746/*
2747** Seek to the offset in id->offset then read cnt bytes into pBuf.
2748** Return the number of bytes actually read. Update the offset.
2749**
2750** To avoid stomping the errno value on a failed write the lastErrno value
2751** is set before returning.
2752*/
2753static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2754 int got;
drh7ed97b92010-01-20 13:07:21 +00002755#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002756 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002757#endif
drh734c9862008-11-28 15:37:20 +00002758 TIMER_START;
2759#if defined(USE_PREAD)
2760 got = pwrite(id->h, pBuf, cnt, offset);
2761#elif defined(USE_PREAD64)
2762 got = pwrite64(id->h, pBuf, cnt, offset);
2763#else
2764 newOffset = lseek(id->h, offset, SEEK_SET);
2765 if( newOffset!=offset ){
2766 if( newOffset == -1 ){
2767 ((unixFile*)id)->lastErrno = errno;
2768 }else{
2769 ((unixFile*)id)->lastErrno = 0;
2770 }
2771 return -1;
2772 }
2773 got = write(id->h, pBuf, cnt);
2774#endif
2775 TIMER_END;
2776 if( got<0 ){
2777 ((unixFile*)id)->lastErrno = errno;
2778 }
2779
drh308c2a52010-05-14 11:30:18 +00002780 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002781 return got;
2782}
2783
2784
2785/*
2786** Write data from a buffer into a file. Return SQLITE_OK on success
2787** or some other error code on failure.
2788*/
2789static int unixWrite(
2790 sqlite3_file *id,
2791 const void *pBuf,
2792 int amt,
2793 sqlite3_int64 offset
2794){
dan08da86a2009-08-21 17:18:03 +00002795 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002796 int wrote = 0;
2797 assert( id );
2798 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002799
dan08da86a2009-08-21 17:18:03 +00002800 /* If this is a database file (not a journal, master-journal or temp
2801 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002802#if 0
dane946c392009-08-22 11:39:46 +00002803 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002804 || offset>=PENDING_BYTE+512
2805 || offset+amt<=PENDING_BYTE
2806 );
dan7c246102010-04-12 19:00:29 +00002807#endif
drh08c6d442009-02-09 17:34:07 +00002808
drh8f941bc2009-01-14 23:03:40 +00002809#ifndef NDEBUG
2810 /* If we are doing a normal write to a database file (as opposed to
2811 ** doing a hot-journal rollback or a write to some file other than a
2812 ** normal database file) then record the fact that the database
2813 ** has changed. If the transaction counter is modified, record that
2814 ** fact too.
2815 */
dan08da86a2009-08-21 17:18:03 +00002816 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002817 pFile->dbUpdate = 1; /* The database has been modified */
2818 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002819 int rc;
drh8f941bc2009-01-14 23:03:40 +00002820 char oldCntr[4];
2821 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002822 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002823 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002824 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002825 pFile->transCntrChng = 1; /* The transaction counter has changed */
2826 }
2827 }
2828 }
2829#endif
2830
dan08da86a2009-08-21 17:18:03 +00002831 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002832 amt -= wrote;
2833 offset += wrote;
2834 pBuf = &((char*)pBuf)[wrote];
2835 }
2836 SimulateIOError(( wrote=(-1), amt=1 ));
2837 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002838
drh734c9862008-11-28 15:37:20 +00002839 if( amt>0 ){
2840 if( wrote<0 ){
2841 /* lastErrno set by seekAndWrite */
2842 return SQLITE_IOERR_WRITE;
2843 }else{
dan08da86a2009-08-21 17:18:03 +00002844 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002845 return SQLITE_FULL;
2846 }
2847 }
dan6e09d692010-07-27 18:34:15 +00002848
drh734c9862008-11-28 15:37:20 +00002849 return SQLITE_OK;
2850}
2851
2852#ifdef SQLITE_TEST
2853/*
2854** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002855** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002856*/
2857int sqlite3_sync_count = 0;
2858int sqlite3_fullsync_count = 0;
2859#endif
2860
2861/*
drh89240432009-03-25 01:06:01 +00002862** We do not trust systems to provide a working fdatasync(). Some do.
2863** Others do no. To be safe, we will stick with the (slower) fsync().
2864** If you know that your system does support fdatasync() correctly,
2865** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002866*/
drh89240432009-03-25 01:06:01 +00002867#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002868# define fdatasync fsync
2869#endif
2870
2871/*
2872** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2873** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2874** only available on Mac OS X. But that could change.
2875*/
2876#ifdef F_FULLFSYNC
2877# define HAVE_FULLFSYNC 1
2878#else
2879# define HAVE_FULLFSYNC 0
2880#endif
2881
2882
2883/*
2884** The fsync() system call does not work as advertised on many
2885** unix systems. The following procedure is an attempt to make
2886** it work better.
2887**
2888** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2889** for testing when we want to run through the test suite quickly.
2890** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2891** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2892** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002893**
2894** SQLite sets the dataOnly flag if the size of the file is unchanged.
2895** The idea behind dataOnly is that it should only write the file content
2896** to disk, not the inode. We only set dataOnly if the file size is
2897** unchanged since the file size is part of the inode. However,
2898** Ted Ts'o tells us that fdatasync() will also write the inode if the
2899** file size has changed. The only real difference between fdatasync()
2900** and fsync(), Ted tells us, is that fdatasync() will not flush the
2901** inode if the mtime or owner or other inode attributes have changed.
2902** We only care about the file size, not the other file attributes, so
2903** as far as SQLite is concerned, an fdatasync() is always adequate.
2904** So, we always use fdatasync() if it is available, regardless of
2905** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002906*/
2907static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002908 int rc;
drh734c9862008-11-28 15:37:20 +00002909
2910 /* The following "ifdef/elif/else/" block has the same structure as
2911 ** the one below. It is replicated here solely to avoid cluttering
2912 ** up the real code with the UNUSED_PARAMETER() macros.
2913 */
2914#ifdef SQLITE_NO_SYNC
2915 UNUSED_PARAMETER(fd);
2916 UNUSED_PARAMETER(fullSync);
2917 UNUSED_PARAMETER(dataOnly);
2918#elif HAVE_FULLFSYNC
2919 UNUSED_PARAMETER(dataOnly);
2920#else
2921 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002922 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002923#endif
2924
2925 /* Record the number of times that we do a normal fsync() and
2926 ** FULLSYNC. This is used during testing to verify that this procedure
2927 ** gets called with the correct arguments.
2928 */
2929#ifdef SQLITE_TEST
2930 if( fullSync ) sqlite3_fullsync_count++;
2931 sqlite3_sync_count++;
2932#endif
2933
2934 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2935 ** no-op
2936 */
2937#ifdef SQLITE_NO_SYNC
2938 rc = SQLITE_OK;
2939#elif HAVE_FULLFSYNC
2940 if( fullSync ){
2941 rc = fcntl(fd, F_FULLFSYNC, 0);
2942 }else{
2943 rc = 1;
2944 }
2945 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002946 ** It shouldn't be possible for fullfsync to fail on the local
2947 ** file system (on OSX), so failure indicates that FULLFSYNC
2948 ** isn't supported for this file system. So, attempt an fsync
2949 ** and (for now) ignore the overhead of a superfluous fcntl call.
2950 ** It'd be better to detect fullfsync support once and avoid
2951 ** the fcntl call every time sync is called.
2952 */
drh734c9862008-11-28 15:37:20 +00002953 if( rc ) rc = fsync(fd);
2954
drh7ed97b92010-01-20 13:07:21 +00002955#elif defined(__APPLE__)
2956 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2957 ** so currently we default to the macro that redefines fdatasync to fsync
2958 */
2959 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002960#else
drh0b647ff2009-03-21 14:41:04 +00002961 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002962#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002963 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002964 rc = fsync(fd);
2965 }
drh0b647ff2009-03-21 14:41:04 +00002966#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002967#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2968
2969 if( OS_VXWORKS && rc!= -1 ){
2970 rc = 0;
2971 }
chw97185482008-11-17 08:05:31 +00002972 return rc;
drhbfe66312006-10-03 17:40:40 +00002973}
2974
drh734c9862008-11-28 15:37:20 +00002975/*
2976** Make sure all writes to a particular file are committed to disk.
2977**
2978** If dataOnly==0 then both the file itself and its metadata (file
2979** size, access time, etc) are synced. If dataOnly!=0 then only the
2980** file data is synced.
2981**
2982** Under Unix, also make sure that the directory entry for the file
2983** has been created by fsync-ing the directory that contains the file.
2984** If we do not do this and we encounter a power failure, the directory
2985** entry for the journal might not exist after we reboot. The next
2986** SQLite to access the file will not know that the journal exists (because
2987** the directory entry for the journal was never created) and the transaction
2988** will not roll back - possibly leading to database corruption.
2989*/
2990static int unixSync(sqlite3_file *id, int flags){
2991 int rc;
2992 unixFile *pFile = (unixFile*)id;
2993
2994 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2995 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2996
2997 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2998 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2999 || (flags&0x0F)==SQLITE_SYNC_FULL
3000 );
3001
3002 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3003 ** line is to test that doing so does not cause any problems.
3004 */
3005 SimulateDiskfullError( return SQLITE_FULL );
3006
3007 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003008 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003009 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3010 SimulateIOError( rc=1 );
3011 if( rc ){
3012 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003013 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003014 }
3015 if( pFile->dirfd>=0 ){
3016 int err;
drh308c2a52010-05-14 11:30:18 +00003017 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3018 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003019#ifndef SQLITE_DISABLE_DIRSYNC
3020 /* The directory sync is only attempted if full_fsync is
3021 ** turned off or unavailable. If a full_fsync occurred above,
3022 ** then the directory sync is superfluous.
3023 */
3024 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3025 /*
3026 ** We have received multiple reports of fsync() returning
3027 ** errors when applied to directories on certain file systems.
3028 ** A failed directory sync is not a big deal. So it seems
3029 ** better to ignore the error. Ticket #1657
3030 */
3031 /* pFile->lastErrno = errno; */
3032 /* return SQLITE_IOERR; */
3033 }
3034#endif
3035 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3036 if( err==0 ){ /* directory when we are done */
3037 pFile->dirfd = -1;
3038 }else{
3039 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003040 rc = unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003041 }
3042 }
3043 return rc;
3044}
3045
3046/*
3047** Truncate an open file to a specified size
3048*/
3049static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003050 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003051 int rc;
dan6e09d692010-07-27 18:34:15 +00003052 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003053 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003054
3055 /* If the user has configured a chunk-size for this file, truncate the
3056 ** file so that it consists of an integer number of chunks (i.e. the
3057 ** actual file size after the operation may be larger than the requested
3058 ** size).
3059 */
3060 if( pFile->szChunk ){
3061 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3062 }
3063
3064 rc = ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003065 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003066 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003067 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003068 }else{
drh3313b142009-11-06 04:13:18 +00003069#ifndef NDEBUG
3070 /* If we are doing a normal write to a database file (as opposed to
3071 ** doing a hot-journal rollback or a write to some file other than a
3072 ** normal database file) and we truncate the file to zero length,
3073 ** that effectively updates the change counter. This might happen
3074 ** when restoring a database using the backup API from a zero-length
3075 ** source.
3076 */
dan6e09d692010-07-27 18:34:15 +00003077 if( pFile->inNormalWrite && nByte==0 ){
3078 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003079 }
3080#endif
3081
drh734c9862008-11-28 15:37:20 +00003082 return SQLITE_OK;
3083 }
3084}
3085
3086/*
3087** Determine the current size of a file in bytes
3088*/
3089static int unixFileSize(sqlite3_file *id, i64 *pSize){
3090 int rc;
3091 struct stat buf;
3092 assert( id );
3093 rc = fstat(((unixFile*)id)->h, &buf);
3094 SimulateIOError( rc=1 );
3095 if( rc!=0 ){
3096 ((unixFile*)id)->lastErrno = errno;
3097 return SQLITE_IOERR_FSTAT;
3098 }
3099 *pSize = buf.st_size;
3100
drh8af6c222010-05-14 12:43:01 +00003101 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003102 ** writes a single byte into that file in order to work around a bug
3103 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3104 ** layers, we need to report this file size as zero even though it is
3105 ** really 1. Ticket #3260.
3106 */
3107 if( *pSize==1 ) *pSize = 0;
3108
3109
3110 return SQLITE_OK;
3111}
3112
drhd2cb50b2009-01-09 21:41:17 +00003113#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003114/*
3115** Handler for proxy-locking file-control verbs. Defined below in the
3116** proxying locking division.
3117*/
3118static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003119#endif
drh715ff302008-12-03 22:32:44 +00003120
dan502019c2010-07-28 14:26:17 +00003121/*
3122** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3123** file-control operation.
3124**
3125** If the user has configured a chunk-size for this file, it could be
3126** that the file needs to be extended at this point. Otherwise, the
3127** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3128*/
3129static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3130 if( pFile->szChunk ){
3131 i64 nSize; /* Required file size */
3132 struct stat buf; /* Used to hold return values of fstat() */
3133
3134 if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
3135
3136 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3137 if( nSize>(i64)buf.st_size ){
3138#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3139 if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
3140 return SQLITE_IOERR_WRITE;
3141 }
3142#else
3143 /* If the OS does not have posix_fallocate(), fake it. First use
3144 ** ftruncate() to set the file size, then write a single byte to
3145 ** the last byte in each block within the extended region. This
3146 ** is the same technique used by glibc to implement posix_fallocate()
3147 ** on systems that do not have a real fallocate() system call.
3148 */
3149 int nBlk = buf.st_blksize; /* File-system block size */
3150 i64 iWrite; /* Next offset to write to */
3151 int nWrite; /* Return value from seekAndWrite() */
3152
3153 if( ftruncate(pFile->h, nSize) ){
3154 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003155 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003156 }
3157 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3158 do {
3159 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3160 iWrite += nBlk;
3161 } while( nWrite==1 && iWrite<nSize );
3162 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3163#endif
3164 }
3165 }
3166
3167 return SQLITE_OK;
3168}
danielk1977ad94b582007-08-20 06:44:22 +00003169
danielk1977e3026632004-06-22 11:29:02 +00003170/*
drh9e33c2c2007-08-31 18:34:59 +00003171** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003172*/
drhcc6bb3e2007-08-31 16:11:35 +00003173static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003174 switch( op ){
3175 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003176 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003177 return SQLITE_OK;
3178 }
drh7708e972008-11-29 00:56:52 +00003179 case SQLITE_LAST_ERRNO: {
3180 *(int*)pArg = ((unixFile*)id)->lastErrno;
3181 return SQLITE_OK;
3182 }
dan6e09d692010-07-27 18:34:15 +00003183 case SQLITE_FCNTL_CHUNK_SIZE: {
3184 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003185 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003186 }
drh9ff27ec2010-05-19 19:26:05 +00003187 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003188 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003189 }
drh8f941bc2009-01-14 23:03:40 +00003190#ifndef NDEBUG
3191 /* The pager calls this method to signal that it has done
3192 ** a rollback and that the database is therefore unchanged and
3193 ** it hence it is OK for the transaction change counter to be
3194 ** unchanged.
3195 */
3196 case SQLITE_FCNTL_DB_UNCHANGED: {
3197 ((unixFile*)id)->dbUpdate = 0;
3198 return SQLITE_OK;
3199 }
3200#endif
drhd2cb50b2009-01-09 21:41:17 +00003201#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003202 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003203 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003204 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003205 }
drhd2cb50b2009-01-09 21:41:17 +00003206#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003207 case SQLITE_FCNTL_SYNC_OMITTED: {
3208 return SQLITE_OK; /* A no-op */
3209 }
drh9e33c2c2007-08-31 18:34:59 +00003210 }
drh0b52b7d2011-01-26 19:46:22 +00003211 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003212}
3213
3214/*
danielk1977a3d4c882007-03-23 10:08:38 +00003215** Return the sector size in bytes of the underlying block device for
3216** the specified file. This is almost always 512 bytes, but may be
3217** larger for some devices.
3218**
3219** SQLite code assumes this function cannot fail. It also assumes that
3220** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003221** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003222** same for both.
3223*/
danielk1977397d65f2008-11-19 11:35:39 +00003224static int unixSectorSize(sqlite3_file *NotUsed){
3225 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003226 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003227}
3228
danielk197790949c22007-08-17 16:50:38 +00003229/*
danielk1977397d65f2008-11-19 11:35:39 +00003230** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003231*/
danielk1977397d65f2008-11-19 11:35:39 +00003232static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3233 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003234 return 0;
3235}
3236
drhd9e5c4f2010-05-12 18:01:39 +00003237#ifndef SQLITE_OMIT_WAL
3238
3239
3240/*
drhd91c68f2010-05-14 14:52:25 +00003241** Object used to represent an shared memory buffer.
3242**
3243** When multiple threads all reference the same wal-index, each thread
3244** has its own unixShm object, but they all point to a single instance
3245** of this unixShmNode object. In other words, each wal-index is opened
3246** only once per process.
3247**
3248** Each unixShmNode object is connected to a single unixInodeInfo object.
3249** We could coalesce this object into unixInodeInfo, but that would mean
3250** every open file that does not use shared memory (in other words, most
3251** open files) would have to carry around this extra information. So
3252** the unixInodeInfo object contains a pointer to this unixShmNode object
3253** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003254**
3255** unixMutexHeld() must be true when creating or destroying
3256** this object or while reading or writing the following fields:
3257**
3258** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003259**
3260** The following fields are read-only after the object is created:
3261**
3262** fid
3263** zFilename
3264**
drhd91c68f2010-05-14 14:52:25 +00003265** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003266** unixMutexHeld() is true when reading or writing any other field
3267** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003268*/
drhd91c68f2010-05-14 14:52:25 +00003269struct unixShmNode {
3270 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003271 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003272 char *zFilename; /* Name of the mmapped file */
3273 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003274 int szRegion; /* Size of shared-memory regions */
3275 int nRegion; /* Size of array apRegion */
3276 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003277 int nRef; /* Number of unixShm objects pointing to this */
3278 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003279#ifdef SQLITE_DEBUG
3280 u8 exclMask; /* Mask of exclusive locks held */
3281 u8 sharedMask; /* Mask of shared locks held */
3282 u8 nextShmId; /* Next available unixShm.id value */
3283#endif
3284};
3285
3286/*
drhd9e5c4f2010-05-12 18:01:39 +00003287** Structure used internally by this VFS to record the state of an
3288** open shared memory connection.
3289**
drhd91c68f2010-05-14 14:52:25 +00003290** The following fields are initialized when this object is created and
3291** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003292**
drhd91c68f2010-05-14 14:52:25 +00003293** unixShm.pFile
3294** unixShm.id
3295**
3296** All other fields are read/write. The unixShm.pFile->mutex must be held
3297** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003298*/
3299struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003300 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3301 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003302 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003303 u16 sharedMask; /* Mask of shared locks held */
3304 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003305#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003306 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003307#endif
3308};
3309
3310/*
drhd9e5c4f2010-05-12 18:01:39 +00003311** Constants used for locking
3312*/
drhbd9676c2010-06-23 17:58:38 +00003313#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003314#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003315
drhd9e5c4f2010-05-12 18:01:39 +00003316/*
drh73b64e42010-05-30 19:55:15 +00003317** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003318**
3319** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3320** otherwise.
3321*/
3322static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003323 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3324 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003325 int ofst, /* First byte of the locking range */
3326 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003327){
3328 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003329 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003330
drhd91c68f2010-05-14 14:52:25 +00003331 /* Access to the unixShmNode object is serialized by the caller */
3332 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003333
drh73b64e42010-05-30 19:55:15 +00003334 /* Shared locks never span more than one byte */
3335 assert( n==1 || lockType!=F_RDLCK );
3336
3337 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003338 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003339
drhd9e5c4f2010-05-12 18:01:39 +00003340 /* Initialize the locking parameters */
3341 memset(&f, 0, sizeof(f));
3342 f.l_type = lockType;
3343 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003344 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003345 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003346
drh73b64e42010-05-30 19:55:15 +00003347 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003348 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3349
3350 /* Update the global lock state and do debug tracing */
3351#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003352 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003353 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003354 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003355 if( rc==SQLITE_OK ){
3356 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003357 OSTRACE(("unlock %d ok", ofst));
3358 pShmNode->exclMask &= ~mask;
3359 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003360 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003361 OSTRACE(("read-lock %d ok", ofst));
3362 pShmNode->exclMask &= ~mask;
3363 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003364 }else{
3365 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003366 OSTRACE(("write-lock %d ok", ofst));
3367 pShmNode->exclMask |= mask;
3368 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003369 }
3370 }else{
3371 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003372 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003373 }else if( lockType==F_RDLCK ){
3374 OSTRACE(("read-lock failed"));
3375 }else{
3376 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003377 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003378 }
3379 }
drh20e1f082010-05-31 16:10:12 +00003380 OSTRACE((" - afterwards %03x,%03x\n",
3381 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003382 }
drhd9e5c4f2010-05-12 18:01:39 +00003383#endif
3384
3385 return rc;
3386}
3387
drhd9e5c4f2010-05-12 18:01:39 +00003388
3389/*
drhd91c68f2010-05-14 14:52:25 +00003390** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003391**
3392** This is not a VFS shared-memory method; it is a utility function called
3393** by VFS shared-memory methods.
3394*/
drhd91c68f2010-05-14 14:52:25 +00003395static void unixShmPurge(unixFile *pFd){
3396 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003397 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003398 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003399 int i;
drhd91c68f2010-05-14 14:52:25 +00003400 assert( p->pInode==pFd->pInode );
3401 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003402 for(i=0; i<p->nRegion; i++){
3403 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003404 }
dan18801912010-06-14 14:07:50 +00003405 sqlite3_free(p->apRegion);
drhd91c68f2010-05-14 14:52:25 +00003406 if( p->h>=0 ) close(p->h);
3407 p->pInode->pShmNode = 0;
3408 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003409 }
3410}
3411
3412/*
danda9fe0c2010-07-13 18:44:03 +00003413** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003414** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003415**
drh7234c6d2010-06-19 15:10:09 +00003416** The file used to implement shared-memory is in the same directory
3417** as the open database file and has the same name as the open database
3418** file with the "-shm" suffix added. For example, if the database file
3419** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003420** for shared memory will be called "/home/user1/config.db-shm".
3421**
3422** Another approach to is to use files in /dev/shm or /dev/tmp or an
3423** some other tmpfs mount. But if a file in a different directory
3424** from the database file is used, then differing access permissions
3425** or a chroot() might cause two different processes on the same
3426** database to end up using different files for shared memory -
3427** meaning that their memory would not really be shared - resulting
3428** in database corruption. Nevertheless, this tmpfs file usage
3429** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3430** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3431** option results in an incompatible build of SQLite; builds of SQLite
3432** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3433** same database file at the same time, database corruption will likely
3434** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3435** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003436**
3437** When opening a new shared-memory file, if no other instances of that
3438** file are currently open, in this process or in other processes, then
3439** the file must be truncated to zero length or have its header cleared.
3440*/
danda9fe0c2010-07-13 18:44:03 +00003441static int unixOpenSharedMemory(unixFile *pDbFd){
3442 struct unixShm *p = 0; /* The connection to be opened */
3443 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3444 int rc; /* Result code */
3445 unixInodeInfo *pInode; /* The inode of fd */
3446 char *zShmFilename; /* Name of the file used for SHM */
3447 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003448
danda9fe0c2010-07-13 18:44:03 +00003449 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003450 p = sqlite3_malloc( sizeof(*p) );
3451 if( p==0 ) return SQLITE_NOMEM;
3452 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003453 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003454
danda9fe0c2010-07-13 18:44:03 +00003455 /* Check to see if a unixShmNode object already exists. Reuse an existing
3456 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003457 */
3458 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003459 pInode = pDbFd->pInode;
3460 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003461 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003462 struct stat sStat; /* fstat() info for database file */
3463
3464 /* Call fstat() to figure out the permissions on the database file. If
3465 ** a new *-shm file is created, an attempt will be made to create it
3466 ** with the same permissions. The actual permissions the file is created
3467 ** with are subject to the current umask setting.
3468 */
3469 if( fstat(pDbFd->h, &sStat) ){
3470 rc = SQLITE_IOERR_FSTAT;
3471 goto shm_open_err;
3472 }
3473
drha4ced192010-07-15 18:32:40 +00003474#ifdef SQLITE_SHM_DIRECTORY
3475 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3476#else
drh7234c6d2010-06-19 15:10:09 +00003477 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003478#endif
drh7234c6d2010-06-19 15:10:09 +00003479 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003480 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003481 rc = SQLITE_NOMEM;
3482 goto shm_open_err;
3483 }
drhd91c68f2010-05-14 14:52:25 +00003484 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003485 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003486#ifdef SQLITE_SHM_DIRECTORY
3487 sqlite3_snprintf(nShmFilename, zShmFilename,
3488 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3489 (u32)sStat.st_ino, (u32)sStat.st_dev);
3490#else
drh7234c6d2010-06-19 15:10:09 +00003491 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003492#endif
drhd91c68f2010-05-14 14:52:25 +00003493 pShmNode->h = -1;
3494 pDbFd->pInode->pShmNode = pShmNode;
3495 pShmNode->pInode = pDbFd->pInode;
3496 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3497 if( pShmNode->mutex==0 ){
3498 rc = SQLITE_NOMEM;
3499 goto shm_open_err;
3500 }
drhd9e5c4f2010-05-12 18:01:39 +00003501
danddb0ac42010-07-14 14:48:58 +00003502 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003503 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003504 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003505 goto shm_open_err;
3506 }
3507
drhd9e5c4f2010-05-12 18:01:39 +00003508 /* Check to see if another process is holding the dead-man switch.
3509 ** If not, truncate the file to zero length.
3510 */
drhd91c68f2010-05-14 14:52:25 +00003511 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003512 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhd91c68f2010-05-14 14:52:25 +00003513 if( ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003514 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003515 }
3516 }
3517 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003518 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003519 }
3520 if( rc ) goto shm_open_err;
3521 }
3522
drhd91c68f2010-05-14 14:52:25 +00003523 /* Make the new connection a child of the unixShmNode */
3524 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003525#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003526 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003527#endif
drhd91c68f2010-05-14 14:52:25 +00003528 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003529 pDbFd->pShm = p;
3530 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003531
3532 /* The reference count on pShmNode has already been incremented under
3533 ** the cover of the unixEnterMutex() mutex and the pointer from the
3534 ** new (struct unixShm) object to the pShmNode has been set. All that is
3535 ** left to do is to link the new object into the linked list starting
3536 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3537 ** mutex.
3538 */
3539 sqlite3_mutex_enter(pShmNode->mutex);
3540 p->pNext = pShmNode->pFirst;
3541 pShmNode->pFirst = p;
3542 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003543 return SQLITE_OK;
3544
3545 /* Jump here on any error */
3546shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003547 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003548 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003549 unixLeaveMutex();
3550 return rc;
3551}
3552
3553/*
danda9fe0c2010-07-13 18:44:03 +00003554** This function is called to obtain a pointer to region iRegion of the
3555** shared-memory associated with the database file fd. Shared-memory regions
3556** are numbered starting from zero. Each shared-memory region is szRegion
3557** bytes in size.
3558**
3559** If an error occurs, an error code is returned and *pp is set to NULL.
3560**
3561** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3562** region has not been allocated (by any client, including one running in a
3563** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3564** bExtend is non-zero and the requested shared-memory region has not yet
3565** been allocated, it is allocated by this function.
3566**
3567** If the shared-memory region has already been allocated or is allocated by
3568** this call as described above, then it is mapped into this processes
3569** address space (if it is not already), *pp is set to point to the mapped
3570** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003571*/
danda9fe0c2010-07-13 18:44:03 +00003572static int unixShmMap(
3573 sqlite3_file *fd, /* Handle open on database file */
3574 int iRegion, /* Region to retrieve */
3575 int szRegion, /* Size of regions */
3576 int bExtend, /* True to extend file if necessary */
3577 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003578){
danda9fe0c2010-07-13 18:44:03 +00003579 unixFile *pDbFd = (unixFile*)fd;
3580 unixShm *p;
3581 unixShmNode *pShmNode;
3582 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003583
danda9fe0c2010-07-13 18:44:03 +00003584 /* If the shared-memory file has not yet been opened, open it now. */
3585 if( pDbFd->pShm==0 ){
3586 rc = unixOpenSharedMemory(pDbFd);
3587 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003588 }
drhd9e5c4f2010-05-12 18:01:39 +00003589
danda9fe0c2010-07-13 18:44:03 +00003590 p = pDbFd->pShm;
3591 pShmNode = p->pShmNode;
3592 sqlite3_mutex_enter(pShmNode->mutex);
3593 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3594
3595 if( pShmNode->nRegion<=iRegion ){
3596 char **apNew; /* New apRegion[] array */
3597 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3598 struct stat sStat; /* Used by fstat() */
3599
3600 pShmNode->szRegion = szRegion;
3601
3602 /* The requested region is not mapped into this processes address space.
3603 ** Check to see if it has been allocated (i.e. if the wal-index file is
3604 ** large enough to contain the requested region).
3605 */
3606 if( fstat(pShmNode->h, &sStat) ){
3607 rc = SQLITE_IOERR_SHMSIZE;
3608 goto shmpage_out;
3609 }
3610
3611 if( sStat.st_size<nByte ){
3612 /* The requested memory region does not exist. If bExtend is set to
3613 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3614 **
3615 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3616 ** the requested memory region.
3617 */
3618 if( !bExtend ) goto shmpage_out;
3619 if( ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003620 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003621 goto shmpage_out;
3622 }
3623 }
3624
3625 /* Map the requested memory region into this processes address space. */
3626 apNew = (char **)sqlite3_realloc(
3627 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3628 );
3629 if( !apNew ){
3630 rc = SQLITE_IOERR_NOMEM;
3631 goto shmpage_out;
3632 }
3633 pShmNode->apRegion = apNew;
3634 while(pShmNode->nRegion<=iRegion){
3635 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003636 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003637 );
3638 if( pMem==MAP_FAILED ){
3639 rc = SQLITE_IOERR;
3640 goto shmpage_out;
3641 }
3642 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3643 pShmNode->nRegion++;
3644 }
3645 }
3646
3647shmpage_out:
3648 if( pShmNode->nRegion>iRegion ){
3649 *pp = pShmNode->apRegion[iRegion];
3650 }else{
3651 *pp = 0;
3652 }
3653 sqlite3_mutex_leave(pShmNode->mutex);
3654 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003655}
3656
3657/*
drhd9e5c4f2010-05-12 18:01:39 +00003658** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003659**
3660** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3661** different here than in posix. In xShmLock(), one can go from unlocked
3662** to shared and back or from unlocked to exclusive and back. But one may
3663** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003664*/
3665static int unixShmLock(
3666 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003667 int ofst, /* First lock to acquire or release */
3668 int n, /* Number of locks to acquire or release */
3669 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003670){
drh73b64e42010-05-30 19:55:15 +00003671 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3672 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3673 unixShm *pX; /* For looping over all siblings */
3674 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3675 int rc = SQLITE_OK; /* Result code */
3676 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003677
drhd91c68f2010-05-14 14:52:25 +00003678 assert( pShmNode==pDbFd->pInode->pShmNode );
3679 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003680 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003681 assert( n>=1 );
3682 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3683 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3684 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3685 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3686 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003687
drhc99597c2010-05-31 01:41:15 +00003688 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003689 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003690 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003691 if( flags & SQLITE_SHM_UNLOCK ){
3692 u16 allMask = 0; /* Mask of locks held by siblings */
3693
3694 /* See if any siblings hold this same lock */
3695 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3696 if( pX==p ) continue;
3697 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3698 allMask |= pX->sharedMask;
3699 }
3700
3701 /* Unlock the system-level locks */
3702 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003703 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003704 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003705 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003706 }
drh73b64e42010-05-30 19:55:15 +00003707
3708 /* Undo the local locks */
3709 if( rc==SQLITE_OK ){
3710 p->exclMask &= ~mask;
3711 p->sharedMask &= ~mask;
3712 }
3713 }else if( flags & SQLITE_SHM_SHARED ){
3714 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3715
3716 /* Find out which shared locks are already held by sibling connections.
3717 ** If any sibling already holds an exclusive lock, go ahead and return
3718 ** SQLITE_BUSY.
3719 */
3720 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003721 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003722 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003723 break;
3724 }
3725 allShared |= pX->sharedMask;
3726 }
3727
3728 /* Get shared locks at the system level, if necessary */
3729 if( rc==SQLITE_OK ){
3730 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003731 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003732 }else{
drh73b64e42010-05-30 19:55:15 +00003733 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003734 }
drhd9e5c4f2010-05-12 18:01:39 +00003735 }
drh73b64e42010-05-30 19:55:15 +00003736
3737 /* Get the local shared locks */
3738 if( rc==SQLITE_OK ){
3739 p->sharedMask |= mask;
3740 }
3741 }else{
3742 /* Make sure no sibling connections hold locks that will block this
3743 ** lock. If any do, return SQLITE_BUSY right away.
3744 */
3745 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003746 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3747 rc = SQLITE_BUSY;
3748 break;
3749 }
3750 }
3751
3752 /* Get the exclusive locks at the system level. Then if successful
3753 ** also mark the local connection as being locked.
3754 */
3755 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003756 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003757 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003758 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003759 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003760 }
drhd9e5c4f2010-05-12 18:01:39 +00003761 }
3762 }
drhd91c68f2010-05-14 14:52:25 +00003763 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003764 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3765 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003766 return rc;
3767}
3768
drh286a2882010-05-20 23:51:06 +00003769/*
3770** Implement a memory barrier or memory fence on shared memory.
3771**
3772** All loads and stores begun before the barrier must complete before
3773** any load or store begun after the barrier.
3774*/
3775static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003776 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003777){
drhff828942010-06-26 21:34:06 +00003778 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003779 unixEnterMutex();
3780 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003781}
3782
dan18801912010-06-14 14:07:50 +00003783/*
danda9fe0c2010-07-13 18:44:03 +00003784** Close a connection to shared-memory. Delete the underlying
3785** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003786**
3787** If there is no shared memory associated with the connection then this
3788** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003789*/
danda9fe0c2010-07-13 18:44:03 +00003790static int unixShmUnmap(
3791 sqlite3_file *fd, /* The underlying database file */
3792 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003793){
danda9fe0c2010-07-13 18:44:03 +00003794 unixShm *p; /* The connection to be closed */
3795 unixShmNode *pShmNode; /* The underlying shared-memory file */
3796 unixShm **pp; /* For looping over sibling connections */
3797 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003798
danda9fe0c2010-07-13 18:44:03 +00003799 pDbFd = (unixFile*)fd;
3800 p = pDbFd->pShm;
3801 if( p==0 ) return SQLITE_OK;
3802 pShmNode = p->pShmNode;
3803
3804 assert( pShmNode==pDbFd->pInode->pShmNode );
3805 assert( pShmNode->pInode==pDbFd->pInode );
3806
3807 /* Remove connection p from the set of connections associated
3808 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003809 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003810 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3811 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003812
danda9fe0c2010-07-13 18:44:03 +00003813 /* Free the connection p */
3814 sqlite3_free(p);
3815 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003816 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003817
3818 /* If pShmNode->nRef has reached 0, then close the underlying
3819 ** shared-memory file, too */
3820 unixEnterMutex();
3821 assert( pShmNode->nRef>0 );
3822 pShmNode->nRef--;
3823 if( pShmNode->nRef==0 ){
3824 if( deleteFlag ) unlink(pShmNode->zFilename);
3825 unixShmPurge(pDbFd);
3826 }
3827 unixLeaveMutex();
3828
3829 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003830}
drh286a2882010-05-20 23:51:06 +00003831
danda9fe0c2010-07-13 18:44:03 +00003832
drhd9e5c4f2010-05-12 18:01:39 +00003833#else
drh6b017cc2010-06-14 18:01:46 +00003834# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003835# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003836# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003837# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003838#endif /* #ifndef SQLITE_OMIT_WAL */
3839
drh734c9862008-11-28 15:37:20 +00003840/*
3841** Here ends the implementation of all sqlite3_file methods.
3842**
3843********************** End sqlite3_file Methods *******************************
3844******************************************************************************/
3845
3846/*
drh6b9d6dd2008-12-03 19:34:47 +00003847** This division contains definitions of sqlite3_io_methods objects that
3848** implement various file locking strategies. It also contains definitions
3849** of "finder" functions. A finder-function is used to locate the appropriate
3850** sqlite3_io_methods object for a particular database file. The pAppData
3851** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3852** the correct finder-function for that VFS.
3853**
3854** Most finder functions return a pointer to a fixed sqlite3_io_methods
3855** object. The only interesting finder-function is autolockIoFinder, which
3856** looks at the filesystem type and tries to guess the best locking
3857** strategy from that.
3858**
drh1875f7a2008-12-08 18:19:17 +00003859** For finder-funtion F, two objects are created:
3860**
3861** (1) The real finder-function named "FImpt()".
3862**
dane946c392009-08-22 11:39:46 +00003863** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003864**
3865**
3866** A pointer to the F pointer is used as the pAppData value for VFS
3867** objects. We have to do this instead of letting pAppData point
3868** directly at the finder-function since C90 rules prevent a void*
3869** from be cast into a function pointer.
3870**
drh6b9d6dd2008-12-03 19:34:47 +00003871**
drh7708e972008-11-29 00:56:52 +00003872** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003873**
drh7708e972008-11-29 00:56:52 +00003874** * A constant sqlite3_io_methods object call METHOD that has locking
3875** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3876**
3877** * An I/O method finder function called FINDER that returns a pointer
3878** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003879*/
drhd9e5c4f2010-05-12 18:01:39 +00003880#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003881static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003882 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003883 CLOSE, /* xClose */ \
3884 unixRead, /* xRead */ \
3885 unixWrite, /* xWrite */ \
3886 unixTruncate, /* xTruncate */ \
3887 unixSync, /* xSync */ \
3888 unixFileSize, /* xFileSize */ \
3889 LOCK, /* xLock */ \
3890 UNLOCK, /* xUnlock */ \
3891 CKLOCK, /* xCheckReservedLock */ \
3892 unixFileControl, /* xFileControl */ \
3893 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003894 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003895 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00003896 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003897 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00003898 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00003899}; \
drh0c2694b2009-09-03 16:23:44 +00003900static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3901 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003902 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003903} \
drh0c2694b2009-09-03 16:23:44 +00003904static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003905 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003906
3907/*
3908** Here are all of the sqlite3_io_methods objects for each of the
3909** locking strategies. Functions that return pointers to these methods
3910** are also created.
3911*/
3912IOMETHODS(
3913 posixIoFinder, /* Finder function name */
3914 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003915 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00003916 unixClose, /* xClose method */
3917 unixLock, /* xLock method */
3918 unixUnlock, /* xUnlock method */
3919 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003920)
drh7708e972008-11-29 00:56:52 +00003921IOMETHODS(
3922 nolockIoFinder, /* Finder function name */
3923 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003924 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003925 nolockClose, /* xClose method */
3926 nolockLock, /* xLock method */
3927 nolockUnlock, /* xUnlock method */
3928 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003929)
drh7708e972008-11-29 00:56:52 +00003930IOMETHODS(
3931 dotlockIoFinder, /* Finder function name */
3932 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003933 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003934 dotlockClose, /* xClose method */
3935 dotlockLock, /* xLock method */
3936 dotlockUnlock, /* xUnlock method */
3937 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003938)
drh7708e972008-11-29 00:56:52 +00003939
chw78a13182009-04-07 05:35:03 +00003940#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003941IOMETHODS(
3942 flockIoFinder, /* Finder function name */
3943 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003944 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003945 flockClose, /* xClose method */
3946 flockLock, /* xLock method */
3947 flockUnlock, /* xUnlock method */
3948 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003949)
drh7708e972008-11-29 00:56:52 +00003950#endif
3951
drh6c7d5c52008-11-21 20:32:33 +00003952#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003953IOMETHODS(
3954 semIoFinder, /* Finder function name */
3955 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003956 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003957 semClose, /* xClose method */
3958 semLock, /* xLock method */
3959 semUnlock, /* xUnlock method */
3960 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003961)
aswiftaebf4132008-11-21 00:10:35 +00003962#endif
drh7708e972008-11-29 00:56:52 +00003963
drhd2cb50b2009-01-09 21:41:17 +00003964#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003965IOMETHODS(
3966 afpIoFinder, /* Finder function name */
3967 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003968 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003969 afpClose, /* xClose method */
3970 afpLock, /* xLock method */
3971 afpUnlock, /* xUnlock method */
3972 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003973)
drh715ff302008-12-03 22:32:44 +00003974#endif
3975
3976/*
3977** The proxy locking method is a "super-method" in the sense that it
3978** opens secondary file descriptors for the conch and lock files and
3979** it uses proxy, dot-file, AFP, and flock() locking methods on those
3980** secondary files. For this reason, the division that implements
3981** proxy locking is located much further down in the file. But we need
3982** to go ahead and define the sqlite3_io_methods and finder function
3983** for proxy locking here. So we forward declare the I/O methods.
3984*/
drhd2cb50b2009-01-09 21:41:17 +00003985#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003986static int proxyClose(sqlite3_file*);
3987static int proxyLock(sqlite3_file*, int);
3988static int proxyUnlock(sqlite3_file*, int);
3989static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003990IOMETHODS(
3991 proxyIoFinder, /* Finder function name */
3992 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003993 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003994 proxyClose, /* xClose method */
3995 proxyLock, /* xLock method */
3996 proxyUnlock, /* xUnlock method */
3997 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003998)
aswiftaebf4132008-11-21 00:10:35 +00003999#endif
drh7708e972008-11-29 00:56:52 +00004000
drh7ed97b92010-01-20 13:07:21 +00004001/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4002#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4003IOMETHODS(
4004 nfsIoFinder, /* Finder function name */
4005 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004006 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004007 unixClose, /* xClose method */
4008 unixLock, /* xLock method */
4009 nfsUnlock, /* xUnlock method */
4010 unixCheckReservedLock /* xCheckReservedLock method */
4011)
4012#endif
drh7708e972008-11-29 00:56:52 +00004013
drhd2cb50b2009-01-09 21:41:17 +00004014#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004015/*
drh6b9d6dd2008-12-03 19:34:47 +00004016** This "finder" function attempts to determine the best locking strategy
4017** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004018** object that implements that strategy.
4019**
4020** This is for MacOSX only.
4021*/
drh1875f7a2008-12-08 18:19:17 +00004022static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004023 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004024 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004025){
4026 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004027 const char *zFilesystem; /* Filesystem type name */
4028 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004029 } aMap[] = {
4030 { "hfs", &posixIoMethods },
4031 { "ufs", &posixIoMethods },
4032 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004033 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004034 { "webdav", &nolockIoMethods },
4035 { 0, 0 }
4036 };
4037 int i;
4038 struct statfs fsInfo;
4039 struct flock lockInfo;
4040
4041 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004042 /* If filePath==NULL that means we are dealing with a transient file
4043 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004044 return &nolockIoMethods;
4045 }
4046 if( statfs(filePath, &fsInfo) != -1 ){
4047 if( fsInfo.f_flags & MNT_RDONLY ){
4048 return &nolockIoMethods;
4049 }
4050 for(i=0; aMap[i].zFilesystem; i++){
4051 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4052 return aMap[i].pMethods;
4053 }
4054 }
4055 }
4056
4057 /* Default case. Handles, amongst others, "nfs".
4058 ** Test byte-range lock using fcntl(). If the call succeeds,
4059 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004060 */
drh7708e972008-11-29 00:56:52 +00004061 lockInfo.l_len = 1;
4062 lockInfo.l_start = 0;
4063 lockInfo.l_whence = SEEK_SET;
4064 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004065 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004066 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4067 return &nfsIoMethods;
4068 } else {
4069 return &posixIoMethods;
4070 }
drh7708e972008-11-29 00:56:52 +00004071 }else{
4072 return &dotlockIoMethods;
4073 }
4074}
drh0c2694b2009-09-03 16:23:44 +00004075static const sqlite3_io_methods
4076 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004077
drhd2cb50b2009-01-09 21:41:17 +00004078#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004079
chw78a13182009-04-07 05:35:03 +00004080#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4081/*
4082** This "finder" function attempts to determine the best locking strategy
4083** for the database file "filePath". It then returns the sqlite3_io_methods
4084** object that implements that strategy.
4085**
4086** This is for VXWorks only.
4087*/
4088static const sqlite3_io_methods *autolockIoFinderImpl(
4089 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004090 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004091){
4092 struct flock lockInfo;
4093
4094 if( !filePath ){
4095 /* If filePath==NULL that means we are dealing with a transient file
4096 ** that does not need to be locked. */
4097 return &nolockIoMethods;
4098 }
4099
4100 /* Test if fcntl() is supported and use POSIX style locks.
4101 ** Otherwise fall back to the named semaphore method.
4102 */
4103 lockInfo.l_len = 1;
4104 lockInfo.l_start = 0;
4105 lockInfo.l_whence = SEEK_SET;
4106 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004107 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004108 return &posixIoMethods;
4109 }else{
4110 return &semIoMethods;
4111 }
4112}
drh0c2694b2009-09-03 16:23:44 +00004113static const sqlite3_io_methods
4114 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004115
4116#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4117
drh7708e972008-11-29 00:56:52 +00004118/*
4119** An abstract type for a pointer to a IO method finder function:
4120*/
drh0c2694b2009-09-03 16:23:44 +00004121typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004122
aswiftaebf4132008-11-21 00:10:35 +00004123
drh734c9862008-11-28 15:37:20 +00004124/****************************************************************************
4125**************************** sqlite3_vfs methods ****************************
4126**
4127** This division contains the implementation of methods on the
4128** sqlite3_vfs object.
4129*/
4130
danielk1977a3d4c882007-03-23 10:08:38 +00004131/*
danielk1977e339d652008-06-28 11:23:00 +00004132** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004133*/
4134static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004135 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004136 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004137 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004138 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004139 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004140 int noLock, /* Omit locking if true */
4141 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004142){
drh7708e972008-11-29 00:56:52 +00004143 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004144 unixFile *pNew = (unixFile *)pId;
4145 int rc = SQLITE_OK;
4146
drh8af6c222010-05-14 12:43:01 +00004147 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004148
dane946c392009-08-22 11:39:46 +00004149 /* Parameter isDelete is only used on vxworks. Express this explicitly
4150 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004151 */
drh7708e972008-11-29 00:56:52 +00004152 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004153
dan00157392010-10-05 11:33:15 +00004154 /* Usually the path zFilename should not be a relative pathname. The
4155 ** exception is when opening the proxy "conch" file in builds that
4156 ** include the special Apple locking styles.
4157 */
dan00157392010-10-05 11:33:15 +00004158#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004159 assert( zFilename==0 || zFilename[0]=='/'
4160 || pVfs->pAppData==(void*)&autolockIoFinder );
4161#else
4162 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004163#endif
dan00157392010-10-05 11:33:15 +00004164
drh308c2a52010-05-14 11:30:18 +00004165 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004166 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004167 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004168 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004169 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004170
drh6c7d5c52008-11-21 20:32:33 +00004171#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004172 pNew->pId = vxworksFindFileId(zFilename);
4173 if( pNew->pId==0 ){
4174 noLock = 1;
4175 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004176 }
4177#endif
4178
drhda0e7682008-07-30 15:27:54 +00004179 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004180 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004181 }else{
drh0c2694b2009-09-03 16:23:44 +00004182 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004183#if SQLITE_ENABLE_LOCKING_STYLE
4184 /* Cache zFilename in the locking context (AFP and dotlock override) for
4185 ** proxyLock activation is possible (remote proxy is based on db name)
4186 ** zFilename remains valid until file is closed, to support */
4187 pNew->lockingContext = (void*)zFilename;
4188#endif
drhda0e7682008-07-30 15:27:54 +00004189 }
danielk1977e339d652008-06-28 11:23:00 +00004190
drh7ed97b92010-01-20 13:07:21 +00004191 if( pLockingStyle == &posixIoMethods
4192#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4193 || pLockingStyle == &nfsIoMethods
4194#endif
4195 ){
drh7708e972008-11-29 00:56:52 +00004196 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004197 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004198 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004199 /* If an error occured in findInodeInfo(), close the file descriptor
4200 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004201 ** in two scenarios:
4202 **
4203 ** (a) A call to fstat() failed.
4204 ** (b) A malloc failed.
4205 **
4206 ** Scenario (b) may only occur if the process is holding no other
4207 ** file descriptors open on the same file. If there were other file
4208 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004209 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004210 ** handle h - as it is guaranteed that no posix locks will be released
4211 ** by doing so.
4212 **
4213 ** If scenario (a) caused the error then things are not so safe. The
4214 ** implicit assumption here is that if fstat() fails, things are in
4215 ** such bad shape that dropping a lock or two doesn't matter much.
4216 */
4217 close(h);
4218 h = -1;
4219 }
drh7708e972008-11-29 00:56:52 +00004220 unixLeaveMutex();
4221 }
danielk1977e339d652008-06-28 11:23:00 +00004222
drhd2cb50b2009-01-09 21:41:17 +00004223#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004224 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004225 /* AFP locking uses the file path so it needs to be included in
4226 ** the afpLockingContext.
4227 */
4228 afpLockingContext *pCtx;
4229 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4230 if( pCtx==0 ){
4231 rc = SQLITE_NOMEM;
4232 }else{
4233 /* NB: zFilename exists and remains valid until the file is closed
4234 ** according to requirement F11141. So we do not need to make a
4235 ** copy of the filename. */
4236 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004237 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004238 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004239 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004240 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004241 if( rc!=SQLITE_OK ){
4242 sqlite3_free(pNew->lockingContext);
4243 close(h);
4244 h = -1;
4245 }
drh7708e972008-11-29 00:56:52 +00004246 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004247 }
drh7708e972008-11-29 00:56:52 +00004248 }
4249#endif
danielk1977e339d652008-06-28 11:23:00 +00004250
drh7708e972008-11-29 00:56:52 +00004251 else if( pLockingStyle == &dotlockIoMethods ){
4252 /* Dotfile locking uses the file path so it needs to be included in
4253 ** the dotlockLockingContext
4254 */
4255 char *zLockFile;
4256 int nFilename;
drhea678832008-12-10 19:26:22 +00004257 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004258 zLockFile = (char *)sqlite3_malloc(nFilename);
4259 if( zLockFile==0 ){
4260 rc = SQLITE_NOMEM;
4261 }else{
4262 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004263 }
drh7708e972008-11-29 00:56:52 +00004264 pNew->lockingContext = zLockFile;
4265 }
danielk1977e339d652008-06-28 11:23:00 +00004266
drh6c7d5c52008-11-21 20:32:33 +00004267#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004268 else if( pLockingStyle == &semIoMethods ){
4269 /* Named semaphore locking uses the file path so it needs to be
4270 ** included in the semLockingContext
4271 */
4272 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004273 rc = findInodeInfo(pNew, &pNew->pInode);
4274 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4275 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004276 int n;
drh2238dcc2009-08-27 17:56:20 +00004277 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004278 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004279 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004280 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004281 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4282 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004283 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004284 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004285 }
chw97185482008-11-17 08:05:31 +00004286 }
drh7708e972008-11-29 00:56:52 +00004287 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004288 }
drh7708e972008-11-29 00:56:52 +00004289#endif
aswift5b1a2562008-08-22 00:22:35 +00004290
4291 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004292#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004293 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004294 if( h>=0 ) close(h);
4295 h = -1;
chw97185482008-11-17 08:05:31 +00004296 unlink(zFilename);
4297 isDelete = 0;
4298 }
4299 pNew->isDelete = isDelete;
4300#endif
danielk1977e339d652008-06-28 11:23:00 +00004301 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004302 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004303 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004304 }else{
drh7708e972008-11-29 00:56:52 +00004305 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004306 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004307 }
danielk1977e339d652008-06-28 11:23:00 +00004308 return rc;
drh054889e2005-11-30 03:20:31 +00004309}
drh9c06c952005-11-26 00:25:00 +00004310
danielk1977ad94b582007-08-20 06:44:22 +00004311/*
4312** Open a file descriptor to the directory containing file zFilename.
4313** If successful, *pFd is set to the opened file descriptor and
4314** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4315** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4316** value.
4317**
4318** If SQLITE_OK is returned, the caller is responsible for closing
4319** the file descriptor *pFd using close().
4320*/
danielk1977fee2d252007-08-18 10:59:19 +00004321static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004322 int ii;
drh777b17a2007-09-20 10:02:54 +00004323 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004324 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004325
drh153c62c2007-08-24 03:51:33 +00004326 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004327 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004328 if( ii>0 ){
4329 zDirname[ii] = '\0';
4330 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004331 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004332#ifdef FD_CLOEXEC
4333 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4334#endif
drh308c2a52010-05-14 11:30:18 +00004335 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004336 }
4337 }
danielk1977fee2d252007-08-18 10:59:19 +00004338 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004339 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004340}
4341
danielk1977b4b47412007-08-17 15:53:36 +00004342/*
drh8b3cf822010-06-01 21:02:51 +00004343** Return the name of a directory in which to put temporary files.
4344** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004345*/
drh7234c6d2010-06-19 15:10:09 +00004346static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004347 static const char *azDirs[] = {
4348 0,
aswiftaebf4132008-11-21 00:10:35 +00004349 0,
danielk197717b90b52008-06-06 11:11:25 +00004350 "/var/tmp",
4351 "/usr/tmp",
4352 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004353 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004354 };
drh8b3cf822010-06-01 21:02:51 +00004355 unsigned int i;
4356 struct stat buf;
4357 const char *zDir = 0;
4358
4359 azDirs[0] = sqlite3_temp_directory;
4360 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004361 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004362 if( zDir==0 ) continue;
4363 if( stat(zDir, &buf) ) continue;
4364 if( !S_ISDIR(buf.st_mode) ) continue;
drh7234c6d2010-06-19 15:10:09 +00004365 if( access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004366 break;
4367 }
4368 return zDir;
4369}
4370
4371/*
4372** Create a temporary file name in zBuf. zBuf must be allocated
4373** by the calling process and must be big enough to hold at least
4374** pVfs->mxPathname bytes.
4375*/
4376static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004377 static const unsigned char zChars[] =
4378 "abcdefghijklmnopqrstuvwxyz"
4379 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4380 "0123456789";
drh41022642008-11-21 00:24:42 +00004381 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004382 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004383
4384 /* It's odd to simulate an io-error here, but really this is just
4385 ** using the io-error infrastructure to test that SQLite handles this
4386 ** function failing.
4387 */
4388 SimulateIOError( return SQLITE_IOERR );
4389
drh7234c6d2010-06-19 15:10:09 +00004390 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004391 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004392
4393 /* Check that the output buffer is large enough for the temporary file
4394 ** name. If it is not, return SQLITE_ERROR.
4395 */
danielk197700e13612008-11-17 19:18:54 +00004396 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004397 return SQLITE_ERROR;
4398 }
4399
4400 do{
4401 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004402 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004403 sqlite3_randomness(15, &zBuf[j]);
4404 for(i=0; i<15; i++, j++){
4405 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4406 }
4407 zBuf[j] = 0;
4408 }while( access(zBuf,0)==0 );
4409 return SQLITE_OK;
4410}
4411
drhd2cb50b2009-01-09 21:41:17 +00004412#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004413/*
4414** Routine to transform a unixFile into a proxy-locking unixFile.
4415** Implementation in the proxy-lock division, but used by unixOpen()
4416** if SQLITE_PREFER_PROXY_LOCKING is defined.
4417*/
4418static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004419#endif
drhc66d5b62008-12-03 22:48:32 +00004420
dan08da86a2009-08-21 17:18:03 +00004421/*
4422** Search for an unused file descriptor that was opened on the database
4423** file (not a journal or master-journal file) identified by pathname
4424** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4425** argument to this function.
4426**
4427** Such a file descriptor may exist if a database connection was closed
4428** but the associated file descriptor could not be closed because some
4429** other file descriptor open on the same file is holding a file-lock.
4430** Refer to comments in the unixClose() function and the lengthy comment
4431** describing "Posix Advisory Locking" at the start of this file for
4432** further details. Also, ticket #4018.
4433**
4434** If a suitable file descriptor is found, then it is returned. If no
4435** such file descriptor is located, -1 is returned.
4436*/
dane946c392009-08-22 11:39:46 +00004437static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4438 UnixUnusedFd *pUnused = 0;
4439
4440 /* Do not search for an unused file descriptor on vxworks. Not because
4441 ** vxworks would not benefit from the change (it might, we're not sure),
4442 ** but because no way to test it is currently available. It is better
4443 ** not to risk breaking vxworks support for the sake of such an obscure
4444 ** feature. */
4445#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004446 struct stat sStat; /* Results of stat() call */
4447
4448 /* A stat() call may fail for various reasons. If this happens, it is
4449 ** almost certain that an open() call on the same path will also fail.
4450 ** For this reason, if an error occurs in the stat() call here, it is
4451 ** ignored and -1 is returned. The caller will try to open a new file
4452 ** descriptor on the same path, fail, and return an error to SQLite.
4453 **
4454 ** Even if a subsequent open() call does succeed, the consequences of
4455 ** not searching for a resusable file descriptor are not dire. */
4456 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004457 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004458
4459 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004460 pInode = inodeList;
4461 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4462 || pInode->fileId.ino!=sStat.st_ino) ){
4463 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004464 }
drh8af6c222010-05-14 12:43:01 +00004465 if( pInode ){
dane946c392009-08-22 11:39:46 +00004466 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004467 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004468 pUnused = *pp;
4469 if( pUnused ){
4470 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004471 }
4472 }
4473 unixLeaveMutex();
4474 }
dane946c392009-08-22 11:39:46 +00004475#endif /* if !OS_VXWORKS */
4476 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004477}
danielk197717b90b52008-06-06 11:11:25 +00004478
4479/*
danddb0ac42010-07-14 14:48:58 +00004480** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004481** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004482** and a value suitable for passing as the third argument to open(2) is
4483** written to *pMode. If an IO error occurs, an SQLite error code is
4484** returned and the value of *pMode is not modified.
4485**
4486** If the file being opened is a temporary file, it is always created with
4487** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004488** is a database or master journal file, it is created with the permissions
4489** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004490**
drh8ab58662010-07-15 18:38:39 +00004491** Finally, if the file being opened is a WAL or regular journal file, then
4492** this function queries the file-system for the permissions on the
4493** corresponding database file and sets *pMode to this value. Whenever
4494** possible, WAL and journal files are created using the same permissions
4495** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004496*/
4497static int findCreateFileMode(
4498 const char *zPath, /* Path of file (possibly) being created */
4499 int flags, /* Flags passed as 4th argument to xOpen() */
4500 mode_t *pMode /* OUT: Permissions to open file with */
4501){
4502 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004503 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004504 char zDb[MAX_PATHNAME+1]; /* Database file path */
4505 int nDb; /* Number of valid bytes in zDb */
4506 struct stat sStat; /* Output of stat() on database file */
4507
dana0c989d2010-11-05 18:07:37 +00004508 /* zPath is a path to a WAL or journal file. The following block derives
4509 ** the path to the associated database file from zPath. This block handles
4510 ** the following naming conventions:
4511 **
4512 ** "<path to db>-journal"
4513 ** "<path to db>-wal"
4514 ** "<path to db>-journal-NNNN"
4515 ** "<path to db>-wal-NNNN"
4516 **
4517 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4518 ** used by the test_multiplex.c module.
4519 */
4520 nDb = sqlite3Strlen30(zPath) - 1;
4521 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4522 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004523 memcpy(zDb, zPath, nDb);
4524 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004525
danddb0ac42010-07-14 14:48:58 +00004526 if( 0==stat(zDb, &sStat) ){
4527 *pMode = sStat.st_mode & 0777;
4528 }else{
4529 rc = SQLITE_IOERR_FSTAT;
4530 }
4531 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4532 *pMode = 0600;
4533 }else{
4534 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4535 }
4536 return rc;
4537}
4538
4539/*
danielk1977ad94b582007-08-20 06:44:22 +00004540** Open the file zPath.
4541**
danielk1977b4b47412007-08-17 15:53:36 +00004542** Previously, the SQLite OS layer used three functions in place of this
4543** one:
4544**
4545** sqlite3OsOpenReadWrite();
4546** sqlite3OsOpenReadOnly();
4547** sqlite3OsOpenExclusive();
4548**
4549** These calls correspond to the following combinations of flags:
4550**
4551** ReadWrite() -> (READWRITE | CREATE)
4552** ReadOnly() -> (READONLY)
4553** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4554**
4555** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4556** true, the file was configured to be automatically deleted when the
4557** file handle closed. To achieve the same effect using this new
4558** interface, add the DELETEONCLOSE flag to those specified above for
4559** OpenExclusive().
4560*/
4561static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004562 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4563 const char *zPath, /* Pathname of file to be opened */
4564 sqlite3_file *pFile, /* The file descriptor to be filled in */
4565 int flags, /* Input flags to control the opening */
4566 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004567){
dan08da86a2009-08-21 17:18:03 +00004568 unixFile *p = (unixFile *)pFile;
4569 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004570 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004571 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004572 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004573 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004574 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004575
4576 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4577 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4578 int isCreate = (flags & SQLITE_OPEN_CREATE);
4579 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4580 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004581#if SQLITE_ENABLE_LOCKING_STYLE
4582 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4583#endif
danielk1977b4b47412007-08-17 15:53:36 +00004584
danielk1977fee2d252007-08-18 10:59:19 +00004585 /* If creating a master or main-file journal, this function will open
4586 ** a file-descriptor on the directory too. The first time unixSync()
4587 ** is called the directory file descriptor will be fsync()ed and close()d.
4588 */
danddb0ac42010-07-14 14:48:58 +00004589 int isOpenDirectory = (isCreate && (
4590 eType==SQLITE_OPEN_MASTER_JOURNAL
4591 || eType==SQLITE_OPEN_MAIN_JOURNAL
4592 || eType==SQLITE_OPEN_WAL
4593 ));
danielk1977fee2d252007-08-18 10:59:19 +00004594
danielk197717b90b52008-06-06 11:11:25 +00004595 /* If argument zPath is a NULL pointer, this function is required to open
4596 ** a temporary file. Use this buffer to store the file name in.
4597 */
4598 char zTmpname[MAX_PATHNAME+1];
4599 const char *zName = zPath;
4600
danielk1977fee2d252007-08-18 10:59:19 +00004601 /* Check the following statements are true:
4602 **
4603 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4604 ** (b) if CREATE is set, then READWRITE must also be set, and
4605 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004606 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004607 */
danielk1977b4b47412007-08-17 15:53:36 +00004608 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004609 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004610 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004611 assert(isDelete==0 || isCreate);
4612
danddb0ac42010-07-14 14:48:58 +00004613 /* The main DB, main journal, WAL file and master journal are never
4614 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004615 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4616 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4617 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004618 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004619
danielk1977fee2d252007-08-18 10:59:19 +00004620 /* Assert that the upper layer has set one of the "file-type" flags. */
4621 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4622 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4623 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004624 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004625 );
4626
dan08da86a2009-08-21 17:18:03 +00004627 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004628
dan08da86a2009-08-21 17:18:03 +00004629 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004630 UnixUnusedFd *pUnused;
4631 pUnused = findReusableFd(zName, flags);
4632 if( pUnused ){
4633 fd = pUnused->fd;
4634 }else{
dan6aa657f2009-08-24 18:57:58 +00004635 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004636 if( !pUnused ){
4637 return SQLITE_NOMEM;
4638 }
4639 }
4640 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004641 }else if( !zName ){
4642 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004643 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004644 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004645 if( rc!=SQLITE_OK ){
4646 return rc;
4647 }
4648 zName = zTmpname;
4649 }
4650
dan08da86a2009-08-21 17:18:03 +00004651 /* Determine the value of the flags parameter passed to POSIX function
4652 ** open(). These must be calculated even if open() is not called, as
4653 ** they may be stored as part of the file handle and used by the
4654 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004655 if( isReadonly ) openFlags |= O_RDONLY;
4656 if( isReadWrite ) openFlags |= O_RDWR;
4657 if( isCreate ) openFlags |= O_CREAT;
4658 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4659 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004660
danielk1977b4b47412007-08-17 15:53:36 +00004661 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004662 mode_t openMode; /* Permissions to create file with */
4663 rc = findCreateFileMode(zName, flags, &openMode);
4664 if( rc!=SQLITE_OK ){
4665 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004666 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004667 return rc;
4668 }
dane946c392009-08-22 11:39:46 +00004669 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004670 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004671 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4672 /* Failed to open the file for read/write access. Try read-only. */
4673 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004674 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004675 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004676 openFlags |= O_RDONLY;
4677 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004678 }
4679 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004680 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004681 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004682 }
danielk1977b4b47412007-08-17 15:53:36 +00004683 }
dan08da86a2009-08-21 17:18:03 +00004684 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004685 if( pOutFlags ){
4686 *pOutFlags = flags;
4687 }
4688
dane946c392009-08-22 11:39:46 +00004689 if( p->pUnused ){
4690 p->pUnused->fd = fd;
4691 p->pUnused->flags = flags;
4692 }
4693
danielk1977b4b47412007-08-17 15:53:36 +00004694 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004695#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004696 zPath = zName;
4697#else
danielk197717b90b52008-06-06 11:11:25 +00004698 unlink(zName);
chw97185482008-11-17 08:05:31 +00004699#endif
danielk1977b4b47412007-08-17 15:53:36 +00004700 }
drh41022642008-11-21 00:24:42 +00004701#if SQLITE_ENABLE_LOCKING_STYLE
4702 else{
dan08da86a2009-08-21 17:18:03 +00004703 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004704 }
4705#endif
4706
danielk1977fee2d252007-08-18 10:59:19 +00004707 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004708 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004709 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004710 /* It is safe to close fd at this point, because it is guaranteed not
4711 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004712 ** it would not be safe to close as this would release any locks held
4713 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004714 assert( eType!=SQLITE_OPEN_MAIN_DB );
4715 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004716 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004717 }
4718 }
danielk1977e339d652008-06-28 11:23:00 +00004719
4720#ifdef FD_CLOEXEC
4721 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4722#endif
4723
drhda0e7682008-07-30 15:27:54 +00004724 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004725
drh7ed97b92010-01-20 13:07:21 +00004726
4727#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4728 struct statfs fsInfo;
4729 if( fstatfs(fd, &fsInfo) == -1 ){
4730 ((unixFile*)pFile)->lastErrno = errno;
4731 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4732 close(fd); /* silently leak if fail, in error */
4733 return SQLITE_IOERR_ACCESS;
4734 }
4735 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4736 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4737 }
4738#endif
4739
4740#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004741#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004742 isAutoProxy = 1;
4743#endif
4744 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004745 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4746 int useProxy = 0;
4747
dan08da86a2009-08-21 17:18:03 +00004748 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4749 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004750 if( envforce!=NULL ){
4751 useProxy = atoi(envforce)>0;
4752 }else{
4753 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004754 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004755 /* In theory, the close(fd) call is sub-optimal. If the file opened
4756 ** with fd is a database file, and there are other connections open
4757 ** on that file that are currently holding advisory locks on it,
4758 ** then the call to close() will cancel those locks. In practice,
4759 ** we're assuming that statfs() doesn't fail very often. At least
4760 ** not while other file descriptors opened by the same process on
4761 ** the same file are working. */
4762 p->lastErrno = errno;
4763 if( dirfd>=0 ){
4764 close(dirfd); /* silently leak if fail, in error */
4765 }
aswiftaebf4132008-11-21 00:10:35 +00004766 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004767 rc = SQLITE_IOERR_ACCESS;
4768 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004769 }
4770 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4771 }
4772 if( useProxy ){
4773 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4774 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004775 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004776 if( rc!=SQLITE_OK ){
4777 /* Use unixClose to clean up the resources added in fillInUnixFile
4778 ** and clear all the structure's references. Specifically,
4779 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4780 */
4781 unixClose(pFile);
4782 return rc;
4783 }
aswiftaebf4132008-11-21 00:10:35 +00004784 }
dane946c392009-08-22 11:39:46 +00004785 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004786 }
4787 }
4788#endif
4789
dane946c392009-08-22 11:39:46 +00004790 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4791open_finished:
4792 if( rc!=SQLITE_OK ){
4793 sqlite3_free(p->pUnused);
4794 }
4795 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004796}
4797
dane946c392009-08-22 11:39:46 +00004798
danielk1977b4b47412007-08-17 15:53:36 +00004799/*
danielk1977fee2d252007-08-18 10:59:19 +00004800** Delete the file at zPath. If the dirSync argument is true, fsync()
4801** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004802*/
drh6b9d6dd2008-12-03 19:34:47 +00004803static int unixDelete(
4804 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4805 const char *zPath, /* Name of file to be deleted */
4806 int dirSync /* If true, fsync() directory after deleting file */
4807){
danielk1977fee2d252007-08-18 10:59:19 +00004808 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004809 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004810 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004811 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00004812 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00004813 }
danielk1977d39fa702008-10-16 13:27:40 +00004814#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004815 if( dirSync ){
4816 int fd;
4817 rc = openDirectory(zPath, &fd);
4818 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004819#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004820 if( fsync(fd)==-1 )
4821#else
4822 if( fsync(fd) )
4823#endif
4824 {
dane18d4952011-02-21 11:46:24 +00004825 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00004826 }
aswiftaebf4132008-11-21 00:10:35 +00004827 if( close(fd)&&!rc ){
dane18d4952011-02-21 11:46:24 +00004828 rc = unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", zPath);
aswiftaebf4132008-11-21 00:10:35 +00004829 }
danielk1977fee2d252007-08-18 10:59:19 +00004830 }
4831 }
danielk1977d138dd82008-10-15 16:02:48 +00004832#endif
danielk1977fee2d252007-08-18 10:59:19 +00004833 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004834}
4835
danielk197790949c22007-08-17 16:50:38 +00004836/*
4837** Test the existance of or access permissions of file zPath. The
4838** test performed depends on the value of flags:
4839**
4840** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4841** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4842** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4843**
4844** Otherwise return 0.
4845*/
danielk1977861f7452008-06-05 11:39:11 +00004846static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004847 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4848 const char *zPath, /* Path of the file to examine */
4849 int flags, /* What do we want to learn about the zPath file? */
4850 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004851){
rse25c0d1a2007-09-20 08:38:14 +00004852 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004853 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004854 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004855 switch( flags ){
4856 case SQLITE_ACCESS_EXISTS:
4857 amode = F_OK;
4858 break;
4859 case SQLITE_ACCESS_READWRITE:
4860 amode = W_OK|R_OK;
4861 break;
drh50d3f902007-08-27 21:10:36 +00004862 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004863 amode = R_OK;
4864 break;
4865
4866 default:
4867 assert(!"Invalid flags argument");
4868 }
danielk1977861f7452008-06-05 11:39:11 +00004869 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004870 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4871 struct stat buf;
4872 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4873 *pResOut = 0;
4874 }
4875 }
danielk1977861f7452008-06-05 11:39:11 +00004876 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004877}
4878
danielk1977b4b47412007-08-17 15:53:36 +00004879
4880/*
4881** Turn a relative pathname into a full pathname. The relative path
4882** is stored as a nul-terminated string in the buffer pointed to by
4883** zPath.
4884**
4885** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4886** (in this case, MAX_PATHNAME bytes). The full-path is written to
4887** this buffer before returning.
4888*/
danielk1977adfb9b02007-09-17 07:02:56 +00004889static int unixFullPathname(
4890 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4891 const char *zPath, /* Possibly relative input path */
4892 int nOut, /* Size of output buffer in bytes */
4893 char *zOut /* Output buffer */
4894){
danielk1977843e65f2007-09-01 16:16:15 +00004895
4896 /* It's odd to simulate an io-error here, but really this is just
4897 ** using the io-error infrastructure to test that SQLite handles this
4898 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004899 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004900 */
4901 SimulateIOError( return SQLITE_ERROR );
4902
drh153c62c2007-08-24 03:51:33 +00004903 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004904 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004905
drh3c7f2dc2007-12-06 13:26:20 +00004906 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004907 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004908 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004909 }else{
4910 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004911 if( getcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00004912 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004913 }
drhea678832008-12-10 19:26:22 +00004914 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004915 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004916 }
4917 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004918}
4919
drh0ccebe72005-06-07 22:22:50 +00004920
drh761df872006-12-21 01:29:22 +00004921#ifndef SQLITE_OMIT_LOAD_EXTENSION
4922/*
4923** Interfaces for opening a shared library, finding entry points
4924** within the shared library, and closing the shared library.
4925*/
4926#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004927static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4928 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004929 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4930}
danielk197795c8a542007-09-01 06:51:27 +00004931
4932/*
4933** SQLite calls this function immediately after a call to unixDlSym() or
4934** unixDlOpen() fails (returns a null pointer). If a more detailed error
4935** message is available, it is written to zBufOut. If no error message
4936** is available, zBufOut is left unmodified and SQLite uses a default
4937** error message.
4938*/
danielk1977397d65f2008-11-19 11:35:39 +00004939static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00004940 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004941 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004942 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004943 zErr = dlerror();
4944 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004945 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004946 }
drh6c7d5c52008-11-21 20:32:33 +00004947 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004948}
drh1875f7a2008-12-08 18:19:17 +00004949static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4950 /*
4951 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4952 ** cast into a pointer to a function. And yet the library dlsym() routine
4953 ** returns a void* which is really a pointer to a function. So how do we
4954 ** use dlsym() with -pedantic-errors?
4955 **
4956 ** Variable x below is defined to be a pointer to a function taking
4957 ** parameters void* and const char* and returning a pointer to a function.
4958 ** We initialize x by assigning it a pointer to the dlsym() function.
4959 ** (That assignment requires a cast.) Then we call the function that
4960 ** x points to.
4961 **
4962 ** This work-around is unlikely to work correctly on any system where
4963 ** you really cannot cast a function pointer into void*. But then, on the
4964 ** other hand, dlsym() will not work on such a system either, so we have
4965 ** not really lost anything.
4966 */
4967 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004968 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004969 x = (void(*(*)(void*,const char*))(void))dlsym;
4970 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004971}
danielk1977397d65f2008-11-19 11:35:39 +00004972static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4973 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004974 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004975}
danielk1977b4b47412007-08-17 15:53:36 +00004976#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4977 #define unixDlOpen 0
4978 #define unixDlError 0
4979 #define unixDlSym 0
4980 #define unixDlClose 0
4981#endif
4982
4983/*
danielk197790949c22007-08-17 16:50:38 +00004984** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004985*/
danielk1977397d65f2008-11-19 11:35:39 +00004986static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4987 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004988 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004989
drhbbd42a62004-05-22 17:41:58 +00004990 /* We have to initialize zBuf to prevent valgrind from reporting
4991 ** errors. The reports issued by valgrind are incorrect - we would
4992 ** prefer that the randomness be increased by making use of the
4993 ** uninitialized space in zBuf - but valgrind errors tend to worry
4994 ** some users. Rather than argue, it seems easier just to initialize
4995 ** the whole array and silence valgrind, even if that means less randomness
4996 ** in the random seed.
4997 **
4998 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004999 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005000 ** tests repeatable.
5001 */
danielk1977b4b47412007-08-17 15:53:36 +00005002 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005003#if !defined(SQLITE_TEST)
5004 {
drh842b8642005-01-21 17:53:17 +00005005 int pid, fd;
5006 fd = open("/dev/urandom", O_RDONLY);
5007 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005008 time_t t;
5009 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005010 memcpy(zBuf, &t, sizeof(t));
5011 pid = getpid();
5012 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005013 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005014 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005015 }else{
drh72cbd072008-10-14 17:58:38 +00005016 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00005017 close(fd);
5018 }
drhbbd42a62004-05-22 17:41:58 +00005019 }
5020#endif
drh72cbd072008-10-14 17:58:38 +00005021 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005022}
5023
danielk1977b4b47412007-08-17 15:53:36 +00005024
drhbbd42a62004-05-22 17:41:58 +00005025/*
5026** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005027** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005028** The return value is the number of microseconds of sleep actually
5029** requested from the underlying operating system, a number which
5030** might be greater than or equal to the argument, but not less
5031** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005032*/
danielk1977397d65f2008-11-19 11:35:39 +00005033static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005034#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005035 struct timespec sp;
5036
5037 sp.tv_sec = microseconds / 1000000;
5038 sp.tv_nsec = (microseconds % 1000000) * 1000;
5039 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005040 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005041 return microseconds;
5042#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005043 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005044 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005045 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005046#else
danielk1977b4b47412007-08-17 15:53:36 +00005047 int seconds = (microseconds+999999)/1000000;
5048 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005049 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005050 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005051#endif
drh88f474a2006-01-02 20:00:12 +00005052}
5053
5054/*
drh6b9d6dd2008-12-03 19:34:47 +00005055** The following variable, if set to a non-zero value, is interpreted as
5056** the number of seconds since 1970 and is used to set the result of
5057** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005058*/
5059#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005060int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005061#endif
5062
5063/*
drhb7e8ea22010-05-03 14:32:30 +00005064** Find the current time (in Universal Coordinated Time). Write into *piNow
5065** the current time and date as a Julian Day number times 86_400_000. In
5066** other words, write into *piNow the number of milliseconds since the Julian
5067** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5068** proleptic Gregorian calendar.
5069**
5070** On success, return 0. Return 1 if the time and date cannot be found.
5071*/
5072static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5073 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5074#if defined(NO_GETTOD)
5075 time_t t;
5076 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005077 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005078#elif OS_VXWORKS
5079 struct timespec sNow;
5080 clock_gettime(CLOCK_REALTIME, &sNow);
5081 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5082#else
5083 struct timeval sNow;
5084 gettimeofday(&sNow, 0);
5085 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5086#endif
5087
5088#ifdef SQLITE_TEST
5089 if( sqlite3_current_time ){
5090 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5091 }
5092#endif
5093 UNUSED_PARAMETER(NotUsed);
5094 return 0;
5095}
5096
5097/*
drhbbd42a62004-05-22 17:41:58 +00005098** Find the current time (in Universal Coordinated Time). Write the
5099** current time and date as a Julian Day number into *prNow and
5100** return 0. Return 1 if the time and date cannot be found.
5101*/
danielk1977397d65f2008-11-19 11:35:39 +00005102static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005103 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005104 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005105 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005106 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005107 return 0;
5108}
danielk1977b4b47412007-08-17 15:53:36 +00005109
drh6b9d6dd2008-12-03 19:34:47 +00005110/*
5111** We added the xGetLastError() method with the intention of providing
5112** better low-level error messages when operating-system problems come up
5113** during SQLite operation. But so far, none of that has been implemented
5114** in the core. So this routine is never called. For now, it is merely
5115** a place-holder.
5116*/
danielk1977397d65f2008-11-19 11:35:39 +00005117static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5118 UNUSED_PARAMETER(NotUsed);
5119 UNUSED_PARAMETER(NotUsed2);
5120 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005121 return 0;
5122}
5123
drhf2424c52010-04-26 00:04:55 +00005124
5125/*
drh734c9862008-11-28 15:37:20 +00005126************************ End of sqlite3_vfs methods ***************************
5127******************************************************************************/
5128
drh715ff302008-12-03 22:32:44 +00005129/******************************************************************************
5130************************** Begin Proxy Locking ********************************
5131**
5132** Proxy locking is a "uber-locking-method" in this sense: It uses the
5133** other locking methods on secondary lock files. Proxy locking is a
5134** meta-layer over top of the primitive locking implemented above. For
5135** this reason, the division that implements of proxy locking is deferred
5136** until late in the file (here) after all of the other I/O methods have
5137** been defined - so that the primitive locking methods are available
5138** as services to help with the implementation of proxy locking.
5139**
5140****
5141**
5142** The default locking schemes in SQLite use byte-range locks on the
5143** database file to coordinate safe, concurrent access by multiple readers
5144** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5145** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5146** as POSIX read & write locks over fixed set of locations (via fsctl),
5147** on AFP and SMB only exclusive byte-range locks are available via fsctl
5148** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5149** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5150** address in the shared range is taken for a SHARED lock, the entire
5151** shared range is taken for an EXCLUSIVE lock):
5152**
5153** PENDING_BYTE 0x40000000
5154** RESERVED_BYTE 0x40000001
5155** SHARED_RANGE 0x40000002 -> 0x40000200
5156**
5157** This works well on the local file system, but shows a nearly 100x
5158** slowdown in read performance on AFP because the AFP client disables
5159** the read cache when byte-range locks are present. Enabling the read
5160** cache exposes a cache coherency problem that is present on all OS X
5161** supported network file systems. NFS and AFP both observe the
5162** close-to-open semantics for ensuring cache coherency
5163** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5164** address the requirements for concurrent database access by multiple
5165** readers and writers
5166** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5167**
5168** To address the performance and cache coherency issues, proxy file locking
5169** changes the way database access is controlled by limiting access to a
5170** single host at a time and moving file locks off of the database file
5171** and onto a proxy file on the local file system.
5172**
5173**
5174** Using proxy locks
5175** -----------------
5176**
5177** C APIs
5178**
5179** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5180** <proxy_path> | ":auto:");
5181** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5182**
5183**
5184** SQL pragmas
5185**
5186** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5187** PRAGMA [database.]lock_proxy_file
5188**
5189** Specifying ":auto:" means that if there is a conch file with a matching
5190** host ID in it, the proxy path in the conch file will be used, otherwise
5191** a proxy path based on the user's temp dir
5192** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5193** actual proxy file name is generated from the name and path of the
5194** database file. For example:
5195**
5196** For database path "/Users/me/foo.db"
5197** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5198**
5199** Once a lock proxy is configured for a database connection, it can not
5200** be removed, however it may be switched to a different proxy path via
5201** the above APIs (assuming the conch file is not being held by another
5202** connection or process).
5203**
5204**
5205** How proxy locking works
5206** -----------------------
5207**
5208** Proxy file locking relies primarily on two new supporting files:
5209**
5210** * conch file to limit access to the database file to a single host
5211** at a time
5212**
5213** * proxy file to act as a proxy for the advisory locks normally
5214** taken on the database
5215**
5216** The conch file - to use a proxy file, sqlite must first "hold the conch"
5217** by taking an sqlite-style shared lock on the conch file, reading the
5218** contents and comparing the host's unique host ID (see below) and lock
5219** proxy path against the values stored in the conch. The conch file is
5220** stored in the same directory as the database file and the file name
5221** is patterned after the database file name as ".<databasename>-conch".
5222** If the conch file does not exist, or it's contents do not match the
5223** host ID and/or proxy path, then the lock is escalated to an exclusive
5224** lock and the conch file contents is updated with the host ID and proxy
5225** path and the lock is downgraded to a shared lock again. If the conch
5226** is held by another process (with a shared lock), the exclusive lock
5227** will fail and SQLITE_BUSY is returned.
5228**
5229** The proxy file - a single-byte file used for all advisory file locks
5230** normally taken on the database file. This allows for safe sharing
5231** of the database file for multiple readers and writers on the same
5232** host (the conch ensures that they all use the same local lock file).
5233**
drh715ff302008-12-03 22:32:44 +00005234** Requesting the lock proxy does not immediately take the conch, it is
5235** only taken when the first request to lock database file is made.
5236** This matches the semantics of the traditional locking behavior, where
5237** opening a connection to a database file does not take a lock on it.
5238** The shared lock and an open file descriptor are maintained until
5239** the connection to the database is closed.
5240**
5241** The proxy file and the lock file are never deleted so they only need
5242** to be created the first time they are used.
5243**
5244** Configuration options
5245** ---------------------
5246**
5247** SQLITE_PREFER_PROXY_LOCKING
5248**
5249** Database files accessed on non-local file systems are
5250** automatically configured for proxy locking, lock files are
5251** named automatically using the same logic as
5252** PRAGMA lock_proxy_file=":auto:"
5253**
5254** SQLITE_PROXY_DEBUG
5255**
5256** Enables the logging of error messages during host id file
5257** retrieval and creation
5258**
drh715ff302008-12-03 22:32:44 +00005259** LOCKPROXYDIR
5260**
5261** Overrides the default directory used for lock proxy files that
5262** are named automatically via the ":auto:" setting
5263**
5264** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5265**
5266** Permissions to use when creating a directory for storing the
5267** lock proxy files, only used when LOCKPROXYDIR is not set.
5268**
5269**
5270** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5271** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5272** force proxy locking to be used for every database file opened, and 0
5273** will force automatic proxy locking to be disabled for all database
5274** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5275** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5276*/
5277
5278/*
5279** Proxy locking is only available on MacOSX
5280*/
drhd2cb50b2009-01-09 21:41:17 +00005281#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005282
drh715ff302008-12-03 22:32:44 +00005283/*
5284** The proxyLockingContext has the path and file structures for the remote
5285** and local proxy files in it
5286*/
5287typedef struct proxyLockingContext proxyLockingContext;
5288struct proxyLockingContext {
5289 unixFile *conchFile; /* Open conch file */
5290 char *conchFilePath; /* Name of the conch file */
5291 unixFile *lockProxy; /* Open proxy lock file */
5292 char *lockProxyPath; /* Name of the proxy lock file */
5293 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005294 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005295 void *oldLockingContext; /* Original lockingcontext to restore on close */
5296 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5297};
5298
drh7ed97b92010-01-20 13:07:21 +00005299/*
5300** The proxy lock file path for the database at dbPath is written into lPath,
5301** which must point to valid, writable memory large enough for a maxLen length
5302** file path.
drh715ff302008-12-03 22:32:44 +00005303*/
drh715ff302008-12-03 22:32:44 +00005304static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5305 int len;
5306 int dbLen;
5307 int i;
5308
5309#ifdef LOCKPROXYDIR
5310 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5311#else
5312# ifdef _CS_DARWIN_USER_TEMP_DIR
5313 {
drh7ed97b92010-01-20 13:07:21 +00005314 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005315 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5316 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005317 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005318 }
drh7ed97b92010-01-20 13:07:21 +00005319 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005320 }
5321# else
5322 len = strlcpy(lPath, "/tmp/", maxLen);
5323# endif
5324#endif
5325
5326 if( lPath[len-1]!='/' ){
5327 len = strlcat(lPath, "/", maxLen);
5328 }
5329
5330 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005331 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005332 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005333 char c = dbPath[i];
5334 lPath[i+len] = (c=='/')?'_':c;
5335 }
5336 lPath[i+len]='\0';
5337 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005338 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005339 return SQLITE_OK;
5340}
5341
drh7ed97b92010-01-20 13:07:21 +00005342/*
5343 ** Creates the lock file and any missing directories in lockPath
5344 */
5345static int proxyCreateLockPath(const char *lockPath){
5346 int i, len;
5347 char buf[MAXPATHLEN];
5348 int start = 0;
5349
5350 assert(lockPath!=NULL);
5351 /* try to create all the intermediate directories */
5352 len = (int)strlen(lockPath);
5353 buf[0] = lockPath[0];
5354 for( i=1; i<len; i++ ){
5355 if( lockPath[i] == '/' && (i - start > 0) ){
5356 /* only mkdir if leaf dir != "." or "/" or ".." */
5357 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5358 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5359 buf[i]='\0';
5360 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5361 int err=errno;
5362 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005363 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005364 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005365 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005366 return err;
5367 }
5368 }
5369 }
5370 start=i+1;
5371 }
5372 buf[i] = lockPath[i];
5373 }
drh308c2a52010-05-14 11:30:18 +00005374 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005375 return 0;
5376}
5377
drh715ff302008-12-03 22:32:44 +00005378/*
5379** Create a new VFS file descriptor (stored in memory obtained from
5380** sqlite3_malloc) and open the file named "path" in the file descriptor.
5381**
5382** The caller is responsible not only for closing the file descriptor
5383** but also for freeing the memory associated with the file descriptor.
5384*/
drh7ed97b92010-01-20 13:07:21 +00005385static int proxyCreateUnixFile(
5386 const char *path, /* path for the new unixFile */
5387 unixFile **ppFile, /* unixFile created and returned by ref */
5388 int islockfile /* if non zero missing dirs will be created */
5389) {
5390 int fd = -1;
5391 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005392 unixFile *pNew;
5393 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005394 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005395 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005396 int terrno = 0;
5397 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005398
drh7ed97b92010-01-20 13:07:21 +00005399 /* 1. first try to open/create the file
5400 ** 2. if that fails, and this is a lock file (not-conch), try creating
5401 ** the parent directories and then try again.
5402 ** 3. if that fails, try to open the file read-only
5403 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5404 */
5405 pUnused = findReusableFd(path, openFlags);
5406 if( pUnused ){
5407 fd = pUnused->fd;
5408 }else{
5409 pUnused = sqlite3_malloc(sizeof(*pUnused));
5410 if( !pUnused ){
5411 return SQLITE_NOMEM;
5412 }
5413 }
5414 if( fd<0 ){
5415 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5416 terrno = errno;
5417 if( fd<0 && errno==ENOENT && islockfile ){
5418 if( proxyCreateLockPath(path) == SQLITE_OK ){
5419 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5420 }
5421 }
5422 }
5423 if( fd<0 ){
5424 openFlags = O_RDONLY;
5425 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5426 terrno = errno;
5427 }
5428 if( fd<0 ){
5429 if( islockfile ){
5430 return SQLITE_BUSY;
5431 }
5432 switch (terrno) {
5433 case EACCES:
5434 return SQLITE_PERM;
5435 case EIO:
5436 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5437 default:
drh9978c972010-02-23 17:36:32 +00005438 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005439 }
5440 }
5441
5442 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5443 if( pNew==NULL ){
5444 rc = SQLITE_NOMEM;
5445 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005446 }
5447 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005448 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005449 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005450 pUnused->fd = fd;
5451 pUnused->flags = openFlags;
5452 pNew->pUnused = pUnused;
5453
5454 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5455 if( rc==SQLITE_OK ){
5456 *ppFile = pNew;
5457 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005458 }
drh7ed97b92010-01-20 13:07:21 +00005459end_create_proxy:
5460 close(fd); /* silently leak fd if error, we're already in error */
5461 sqlite3_free(pNew);
5462 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005463 return rc;
5464}
5465
drh7ed97b92010-01-20 13:07:21 +00005466#ifdef SQLITE_TEST
5467/* simulate multiple hosts by creating unique hostid file paths */
5468int sqlite3_hostid_num = 0;
5469#endif
5470
5471#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5472
drh0ab216a2010-07-02 17:10:40 +00005473/* Not always defined in the headers as it ought to be */
5474extern int gethostuuid(uuid_t id, const struct timespec *wait);
5475
drh7ed97b92010-01-20 13:07:21 +00005476/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5477** bytes of writable memory.
5478*/
5479static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005480 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5481 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005482#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5483 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005484 {
5485 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5486 if( gethostuuid(pHostID, &timeout) ){
5487 int err = errno;
5488 if( pError ){
5489 *pError = err;
5490 }
5491 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005492 }
drh7ed97b92010-01-20 13:07:21 +00005493 }
drhe8b0c9b2010-09-25 14:13:17 +00005494#endif
drh7ed97b92010-01-20 13:07:21 +00005495#ifdef SQLITE_TEST
5496 /* simulate multiple hosts by creating unique hostid file paths */
5497 if( sqlite3_hostid_num != 0){
5498 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5499 }
5500#endif
5501
5502 return SQLITE_OK;
5503}
5504
5505/* The conch file contains the header, host id and lock file path
5506 */
5507#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5508#define PROXY_HEADERLEN 1 /* conch file header length */
5509#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5510#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5511
5512/*
5513** Takes an open conch file, copies the contents to a new path and then moves
5514** it back. The newly created file's file descriptor is assigned to the
5515** conch file structure and finally the original conch file descriptor is
5516** closed. Returns zero if successful.
5517*/
5518static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5519 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5520 unixFile *conchFile = pCtx->conchFile;
5521 char tPath[MAXPATHLEN];
5522 char buf[PROXY_MAXCONCHLEN];
5523 char *cPath = pCtx->conchFilePath;
5524 size_t readLen = 0;
5525 size_t pathLen = 0;
5526 char errmsg[64] = "";
5527 int fd = -1;
5528 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005529 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005530
5531 /* create a new path by replace the trailing '-conch' with '-break' */
5532 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5533 if( pathLen>MAXPATHLEN || pathLen<6 ||
5534 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005535 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005536 goto end_breaklock;
5537 }
5538 /* read the conch content */
5539 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5540 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005541 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005542 goto end_breaklock;
5543 }
5544 /* write it out to the temporary break file */
5545 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5546 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005547 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005548 goto end_breaklock;
5549 }
drh0ab216a2010-07-02 17:10:40 +00005550 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005551 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005552 goto end_breaklock;
5553 }
5554 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005555 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005556 goto end_breaklock;
5557 }
5558 rc = 0;
5559 fprintf(stderr, "broke stale lock on %s\n", cPath);
5560 close(conchFile->h);
5561 conchFile->h = fd;
5562 conchFile->openFlags = O_RDWR | O_CREAT;
5563
5564end_breaklock:
5565 if( rc ){
5566 if( fd>=0 ){
5567 unlink(tPath);
5568 close(fd);
5569 }
5570 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5571 }
5572 return rc;
5573}
5574
5575/* Take the requested lock on the conch file and break a stale lock if the
5576** host id matches.
5577*/
5578static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5579 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5580 unixFile *conchFile = pCtx->conchFile;
5581 int rc = SQLITE_OK;
5582 int nTries = 0;
5583 struct timespec conchModTime;
5584
5585 do {
5586 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5587 nTries ++;
5588 if( rc==SQLITE_BUSY ){
5589 /* If the lock failed (busy):
5590 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5591 * 2nd try: fail if the mod time changed or host id is different, wait
5592 * 10 sec and try again
5593 * 3rd try: break the lock unless the mod time has changed.
5594 */
5595 struct stat buf;
5596 if( fstat(conchFile->h, &buf) ){
5597 pFile->lastErrno = errno;
5598 return SQLITE_IOERR_LOCK;
5599 }
5600
5601 if( nTries==1 ){
5602 conchModTime = buf.st_mtimespec;
5603 usleep(500000); /* wait 0.5 sec and try the lock again*/
5604 continue;
5605 }
5606
5607 assert( nTries>1 );
5608 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5609 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5610 return SQLITE_BUSY;
5611 }
5612
5613 if( nTries==2 ){
5614 char tBuf[PROXY_MAXCONCHLEN];
5615 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5616 if( len<0 ){
5617 pFile->lastErrno = errno;
5618 return SQLITE_IOERR_LOCK;
5619 }
5620 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5621 /* don't break the lock if the host id doesn't match */
5622 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5623 return SQLITE_BUSY;
5624 }
5625 }else{
5626 /* don't break the lock on short read or a version mismatch */
5627 return SQLITE_BUSY;
5628 }
5629 usleep(10000000); /* wait 10 sec and try the lock again */
5630 continue;
5631 }
5632
5633 assert( nTries==3 );
5634 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5635 rc = SQLITE_OK;
5636 if( lockType==EXCLUSIVE_LOCK ){
5637 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5638 }
5639 if( !rc ){
5640 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5641 }
5642 }
5643 }
5644 } while( rc==SQLITE_BUSY && nTries<3 );
5645
5646 return rc;
5647}
5648
5649/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005650** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5651** lockPath means that the lockPath in the conch file will be used if the
5652** host IDs match, or a new lock path will be generated automatically
5653** and written to the conch file.
5654*/
5655static int proxyTakeConch(unixFile *pFile){
5656 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5657
drh7ed97b92010-01-20 13:07:21 +00005658 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005659 return SQLITE_OK;
5660 }else{
5661 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005662 uuid_t myHostID;
5663 int pError = 0;
5664 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005665 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005666 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005667 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005668 int createConch = 0;
5669 int hostIdMatch = 0;
5670 int readLen = 0;
5671 int tryOldLockPath = 0;
5672 int forceNewLockPath = 0;
5673
drh308c2a52010-05-14 11:30:18 +00005674 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5675 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005676
drh7ed97b92010-01-20 13:07:21 +00005677 rc = proxyGetHostID(myHostID, &pError);
5678 if( (rc&0xff)==SQLITE_IOERR ){
5679 pFile->lastErrno = pError;
5680 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005681 }
drh7ed97b92010-01-20 13:07:21 +00005682 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005683 if( rc!=SQLITE_OK ){
5684 goto end_takeconch;
5685 }
drh7ed97b92010-01-20 13:07:21 +00005686 /* read the existing conch file */
5687 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5688 if( readLen<0 ){
5689 /* I/O error: lastErrno set by seekAndRead */
5690 pFile->lastErrno = conchFile->lastErrno;
5691 rc = SQLITE_IOERR_READ;
5692 goto end_takeconch;
5693 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5694 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5695 /* a short read or version format mismatch means we need to create a new
5696 ** conch file.
5697 */
5698 createConch = 1;
5699 }
5700 /* if the host id matches and the lock path already exists in the conch
5701 ** we'll try to use the path there, if we can't open that path, we'll
5702 ** retry with a new auto-generated path
5703 */
5704 do { /* in case we need to try again for an :auto: named lock file */
5705
5706 if( !createConch && !forceNewLockPath ){
5707 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5708 PROXY_HOSTIDLEN);
5709 /* if the conch has data compare the contents */
5710 if( !pCtx->lockProxyPath ){
5711 /* for auto-named local lock file, just check the host ID and we'll
5712 ** use the local lock file path that's already in there
5713 */
5714 if( hostIdMatch ){
5715 size_t pathLen = (readLen - PROXY_PATHINDEX);
5716
5717 if( pathLen>=MAXPATHLEN ){
5718 pathLen=MAXPATHLEN-1;
5719 }
5720 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5721 lockPath[pathLen] = 0;
5722 tempLockPath = lockPath;
5723 tryOldLockPath = 1;
5724 /* create a copy of the lock path if the conch is taken */
5725 goto end_takeconch;
5726 }
5727 }else if( hostIdMatch
5728 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5729 readLen-PROXY_PATHINDEX)
5730 ){
5731 /* conch host and lock path match */
5732 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005733 }
drh7ed97b92010-01-20 13:07:21 +00005734 }
5735
5736 /* if the conch isn't writable and doesn't match, we can't take it */
5737 if( (conchFile->openFlags&O_RDWR) == 0 ){
5738 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005739 goto end_takeconch;
5740 }
drh7ed97b92010-01-20 13:07:21 +00005741
5742 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005743 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005744 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5745 tempLockPath = lockPath;
5746 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005747 }
drh7ed97b92010-01-20 13:07:21 +00005748
5749 /* update conch with host and path (this will fail if other process
5750 ** has a shared lock already), if the host id matches, use the big
5751 ** stick.
drh715ff302008-12-03 22:32:44 +00005752 */
drh7ed97b92010-01-20 13:07:21 +00005753 futimes(conchFile->h, NULL);
5754 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005755 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005756 /* We are trying for an exclusive lock but another thread in this
5757 ** same process is still holding a shared lock. */
5758 rc = SQLITE_BUSY;
5759 } else {
5760 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005761 }
drh715ff302008-12-03 22:32:44 +00005762 }else{
drh7ed97b92010-01-20 13:07:21 +00005763 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005764 }
drh7ed97b92010-01-20 13:07:21 +00005765 if( rc==SQLITE_OK ){
5766 char writeBuffer[PROXY_MAXCONCHLEN];
5767 int writeSize = 0;
5768
5769 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5770 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5771 if( pCtx->lockProxyPath!=NULL ){
5772 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5773 }else{
5774 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5775 }
5776 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5777 ftruncate(conchFile->h, writeSize);
5778 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5779 fsync(conchFile->h);
5780 /* If we created a new conch file (not just updated the contents of a
5781 ** valid conch file), try to match the permissions of the database
5782 */
5783 if( rc==SQLITE_OK && createConch ){
5784 struct stat buf;
5785 int err = fstat(pFile->h, &buf);
5786 if( err==0 ){
5787 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5788 S_IROTH|S_IWOTH);
5789 /* try to match the database file R/W permissions, ignore failure */
5790#ifndef SQLITE_PROXY_DEBUG
5791 fchmod(conchFile->h, cmode);
5792#else
5793 if( fchmod(conchFile->h, cmode)!=0 ){
5794 int code = errno;
5795 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5796 cmode, code, strerror(code));
5797 } else {
5798 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5799 }
5800 }else{
5801 int code = errno;
5802 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5803 err, code, strerror(code));
5804#endif
5805 }
drh715ff302008-12-03 22:32:44 +00005806 }
5807 }
drh7ed97b92010-01-20 13:07:21 +00005808 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5809
5810 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005811 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005812 if( rc==SQLITE_OK && pFile->openFlags ){
5813 if( pFile->h>=0 ){
5814#ifdef STRICT_CLOSE_ERROR
5815 if( close(pFile->h) ){
5816 pFile->lastErrno = errno;
5817 return SQLITE_IOERR_CLOSE;
5818 }
5819#else
5820 close(pFile->h); /* silently leak fd if fail */
5821#endif
5822 }
5823 pFile->h = -1;
5824 int fd = open(pCtx->dbPath, pFile->openFlags,
5825 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005826 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005827 if( fd>=0 ){
5828 pFile->h = fd;
5829 }else{
drh9978c972010-02-23 17:36:32 +00005830 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005831 during locking */
5832 }
5833 }
5834 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5835 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5836 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5837 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5838 /* we couldn't create the proxy lock file with the old lock file path
5839 ** so try again via auto-naming
5840 */
5841 forceNewLockPath = 1;
5842 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005843 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005844 }
5845 }
5846 if( rc==SQLITE_OK ){
5847 /* Need to make a copy of path if we extracted the value
5848 ** from the conch file or the path was allocated on the stack
5849 */
5850 if( tempLockPath ){
5851 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5852 if( !pCtx->lockProxyPath ){
5853 rc = SQLITE_NOMEM;
5854 }
5855 }
5856 }
5857 if( rc==SQLITE_OK ){
5858 pCtx->conchHeld = 1;
5859
5860 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5861 afpLockingContext *afpCtx;
5862 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5863 afpCtx->dbPath = pCtx->lockProxyPath;
5864 }
5865 } else {
5866 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5867 }
drh308c2a52010-05-14 11:30:18 +00005868 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5869 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005870 return rc;
drh308c2a52010-05-14 11:30:18 +00005871 } while (1); /* in case we need to retry the :auto: lock file -
5872 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005873 }
5874}
5875
5876/*
5877** If pFile holds a lock on a conch file, then release that lock.
5878*/
5879static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005880 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005881 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5882 unixFile *conchFile; /* Name of the conch file */
5883
5884 pCtx = (proxyLockingContext *)pFile->lockingContext;
5885 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005886 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005887 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005888 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005889 if( pCtx->conchHeld>0 ){
5890 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5891 }
drh715ff302008-12-03 22:32:44 +00005892 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005893 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5894 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005895 return rc;
5896}
5897
5898/*
5899** Given the name of a database file, compute the name of its conch file.
5900** Store the conch filename in memory obtained from sqlite3_malloc().
5901** Make *pConchPath point to the new name. Return SQLITE_OK on success
5902** or SQLITE_NOMEM if unable to obtain memory.
5903**
5904** The caller is responsible for ensuring that the allocated memory
5905** space is eventually freed.
5906**
5907** *pConchPath is set to NULL if a memory allocation error occurs.
5908*/
5909static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5910 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005911 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005912 char *conchPath; /* buffer in which to construct conch name */
5913
5914 /* Allocate space for the conch filename and initialize the name to
5915 ** the name of the original database file. */
5916 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5917 if( conchPath==0 ){
5918 return SQLITE_NOMEM;
5919 }
5920 memcpy(conchPath, dbPath, len+1);
5921
5922 /* now insert a "." before the last / character */
5923 for( i=(len-1); i>=0; i-- ){
5924 if( conchPath[i]=='/' ){
5925 i++;
5926 break;
5927 }
5928 }
5929 conchPath[i]='.';
5930 while ( i<len ){
5931 conchPath[i+1]=dbPath[i];
5932 i++;
5933 }
5934
5935 /* append the "-conch" suffix to the file */
5936 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005937 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005938
5939 return SQLITE_OK;
5940}
5941
5942
5943/* Takes a fully configured proxy locking-style unix file and switches
5944** the local lock file path
5945*/
5946static int switchLockProxyPath(unixFile *pFile, const char *path) {
5947 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5948 char *oldPath = pCtx->lockProxyPath;
5949 int rc = SQLITE_OK;
5950
drh308c2a52010-05-14 11:30:18 +00005951 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005952 return SQLITE_BUSY;
5953 }
5954
5955 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5956 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5957 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5958 return SQLITE_OK;
5959 }else{
5960 unixFile *lockProxy = pCtx->lockProxy;
5961 pCtx->lockProxy=NULL;
5962 pCtx->conchHeld = 0;
5963 if( lockProxy!=NULL ){
5964 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5965 if( rc ) return rc;
5966 sqlite3_free(lockProxy);
5967 }
5968 sqlite3_free(oldPath);
5969 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5970 }
5971
5972 return rc;
5973}
5974
5975/*
5976** pFile is a file that has been opened by a prior xOpen call. dbPath
5977** is a string buffer at least MAXPATHLEN+1 characters in size.
5978**
5979** This routine find the filename associated with pFile and writes it
5980** int dbPath.
5981*/
5982static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005983#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005984 if( pFile->pMethod == &afpIoMethods ){
5985 /* afp style keeps a reference to the db path in the filePath field
5986 ** of the struct */
drhea678832008-12-10 19:26:22 +00005987 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005988 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5989 } else
drh715ff302008-12-03 22:32:44 +00005990#endif
5991 if( pFile->pMethod == &dotlockIoMethods ){
5992 /* dot lock style uses the locking context to store the dot lock
5993 ** file path */
5994 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5995 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5996 }else{
5997 /* all other styles use the locking context to store the db file path */
5998 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005999 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006000 }
6001 return SQLITE_OK;
6002}
6003
6004/*
6005** Takes an already filled in unix file and alters it so all file locking
6006** will be performed on the local proxy lock file. The following fields
6007** are preserved in the locking context so that they can be restored and
6008** the unix structure properly cleaned up at close time:
6009** ->lockingContext
6010** ->pMethod
6011*/
6012static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6013 proxyLockingContext *pCtx;
6014 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6015 char *lockPath=NULL;
6016 int rc = SQLITE_OK;
6017
drh308c2a52010-05-14 11:30:18 +00006018 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006019 return SQLITE_BUSY;
6020 }
6021 proxyGetDbPathForUnixFile(pFile, dbPath);
6022 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6023 lockPath=NULL;
6024 }else{
6025 lockPath=(char *)path;
6026 }
6027
drh308c2a52010-05-14 11:30:18 +00006028 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6029 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006030
6031 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6032 if( pCtx==0 ){
6033 return SQLITE_NOMEM;
6034 }
6035 memset(pCtx, 0, sizeof(*pCtx));
6036
6037 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6038 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006039 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6040 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6041 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6042 ** (c) the file system is read-only, then enable no-locking access.
6043 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6044 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6045 */
6046 struct statfs fsInfo;
6047 struct stat conchInfo;
6048 int goLockless = 0;
6049
6050 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6051 int err = errno;
6052 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6053 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6054 }
6055 }
6056 if( goLockless ){
6057 pCtx->conchHeld = -1; /* read only FS/ lockless */
6058 rc = SQLITE_OK;
6059 }
6060 }
drh715ff302008-12-03 22:32:44 +00006061 }
6062 if( rc==SQLITE_OK && lockPath ){
6063 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6064 }
6065
6066 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006067 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6068 if( pCtx->dbPath==NULL ){
6069 rc = SQLITE_NOMEM;
6070 }
6071 }
6072 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006073 /* all memory is allocated, proxys are created and assigned,
6074 ** switch the locking context and pMethod then return.
6075 */
drh715ff302008-12-03 22:32:44 +00006076 pCtx->oldLockingContext = pFile->lockingContext;
6077 pFile->lockingContext = pCtx;
6078 pCtx->pOldMethod = pFile->pMethod;
6079 pFile->pMethod = &proxyIoMethods;
6080 }else{
6081 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006082 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006083 sqlite3_free(pCtx->conchFile);
6084 }
drhd56b1212010-08-11 06:14:15 +00006085 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006086 sqlite3_free(pCtx->conchFilePath);
6087 sqlite3_free(pCtx);
6088 }
drh308c2a52010-05-14 11:30:18 +00006089 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6090 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006091 return rc;
6092}
6093
6094
6095/*
6096** This routine handles sqlite3_file_control() calls that are specific
6097** to proxy locking.
6098*/
6099static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6100 switch( op ){
6101 case SQLITE_GET_LOCKPROXYFILE: {
6102 unixFile *pFile = (unixFile*)id;
6103 if( pFile->pMethod == &proxyIoMethods ){
6104 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6105 proxyTakeConch(pFile);
6106 if( pCtx->lockProxyPath ){
6107 *(const char **)pArg = pCtx->lockProxyPath;
6108 }else{
6109 *(const char **)pArg = ":auto: (not held)";
6110 }
6111 } else {
6112 *(const char **)pArg = NULL;
6113 }
6114 return SQLITE_OK;
6115 }
6116 case SQLITE_SET_LOCKPROXYFILE: {
6117 unixFile *pFile = (unixFile*)id;
6118 int rc = SQLITE_OK;
6119 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6120 if( pArg==NULL || (const char *)pArg==0 ){
6121 if( isProxyStyle ){
6122 /* turn off proxy locking - not supported */
6123 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6124 }else{
6125 /* turn off proxy locking - already off - NOOP */
6126 rc = SQLITE_OK;
6127 }
6128 }else{
6129 const char *proxyPath = (const char *)pArg;
6130 if( isProxyStyle ){
6131 proxyLockingContext *pCtx =
6132 (proxyLockingContext*)pFile->lockingContext;
6133 if( !strcmp(pArg, ":auto:")
6134 || (pCtx->lockProxyPath &&
6135 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6136 ){
6137 rc = SQLITE_OK;
6138 }else{
6139 rc = switchLockProxyPath(pFile, proxyPath);
6140 }
6141 }else{
6142 /* turn on proxy file locking */
6143 rc = proxyTransformUnixFile(pFile, proxyPath);
6144 }
6145 }
6146 return rc;
6147 }
6148 default: {
6149 assert( 0 ); /* The call assures that only valid opcodes are sent */
6150 }
6151 }
6152 /*NOTREACHED*/
6153 return SQLITE_ERROR;
6154}
6155
6156/*
6157** Within this division (the proxying locking implementation) the procedures
6158** above this point are all utilities. The lock-related methods of the
6159** proxy-locking sqlite3_io_method object follow.
6160*/
6161
6162
6163/*
6164** This routine checks if there is a RESERVED lock held on the specified
6165** file by this or any other process. If such a lock is held, set *pResOut
6166** to a non-zero value otherwise *pResOut is set to zero. The return value
6167** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6168*/
6169static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6170 unixFile *pFile = (unixFile*)id;
6171 int rc = proxyTakeConch(pFile);
6172 if( rc==SQLITE_OK ){
6173 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006174 if( pCtx->conchHeld>0 ){
6175 unixFile *proxy = pCtx->lockProxy;
6176 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6177 }else{ /* conchHeld < 0 is lockless */
6178 pResOut=0;
6179 }
drh715ff302008-12-03 22:32:44 +00006180 }
6181 return rc;
6182}
6183
6184/*
drh308c2a52010-05-14 11:30:18 +00006185** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006186** of the following:
6187**
6188** (1) SHARED_LOCK
6189** (2) RESERVED_LOCK
6190** (3) PENDING_LOCK
6191** (4) EXCLUSIVE_LOCK
6192**
6193** Sometimes when requesting one lock state, additional lock states
6194** are inserted in between. The locking might fail on one of the later
6195** transitions leaving the lock state different from what it started but
6196** still short of its goal. The following chart shows the allowed
6197** transitions and the inserted intermediate states:
6198**
6199** UNLOCKED -> SHARED
6200** SHARED -> RESERVED
6201** SHARED -> (PENDING) -> EXCLUSIVE
6202** RESERVED -> (PENDING) -> EXCLUSIVE
6203** PENDING -> EXCLUSIVE
6204**
6205** This routine will only increase a lock. Use the sqlite3OsUnlock()
6206** routine to lower a locking level.
6207*/
drh308c2a52010-05-14 11:30:18 +00006208static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006209 unixFile *pFile = (unixFile*)id;
6210 int rc = proxyTakeConch(pFile);
6211 if( rc==SQLITE_OK ){
6212 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006213 if( pCtx->conchHeld>0 ){
6214 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006215 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6216 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006217 }else{
6218 /* conchHeld < 0 is lockless */
6219 }
drh715ff302008-12-03 22:32:44 +00006220 }
6221 return rc;
6222}
6223
6224
6225/*
drh308c2a52010-05-14 11:30:18 +00006226** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006227** must be either NO_LOCK or SHARED_LOCK.
6228**
6229** If the locking level of the file descriptor is already at or below
6230** the requested locking level, this routine is a no-op.
6231*/
drh308c2a52010-05-14 11:30:18 +00006232static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006233 unixFile *pFile = (unixFile*)id;
6234 int rc = proxyTakeConch(pFile);
6235 if( rc==SQLITE_OK ){
6236 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006237 if( pCtx->conchHeld>0 ){
6238 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006239 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6240 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006241 }else{
6242 /* conchHeld < 0 is lockless */
6243 }
drh715ff302008-12-03 22:32:44 +00006244 }
6245 return rc;
6246}
6247
6248/*
6249** Close a file that uses proxy locks.
6250*/
6251static int proxyClose(sqlite3_file *id) {
6252 if( id ){
6253 unixFile *pFile = (unixFile*)id;
6254 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6255 unixFile *lockProxy = pCtx->lockProxy;
6256 unixFile *conchFile = pCtx->conchFile;
6257 int rc = SQLITE_OK;
6258
6259 if( lockProxy ){
6260 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6261 if( rc ) return rc;
6262 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6263 if( rc ) return rc;
6264 sqlite3_free(lockProxy);
6265 pCtx->lockProxy = 0;
6266 }
6267 if( conchFile ){
6268 if( pCtx->conchHeld ){
6269 rc = proxyReleaseConch(pFile);
6270 if( rc ) return rc;
6271 }
6272 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6273 if( rc ) return rc;
6274 sqlite3_free(conchFile);
6275 }
drhd56b1212010-08-11 06:14:15 +00006276 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006277 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006278 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006279 /* restore the original locking context and pMethod then close it */
6280 pFile->lockingContext = pCtx->oldLockingContext;
6281 pFile->pMethod = pCtx->pOldMethod;
6282 sqlite3_free(pCtx);
6283 return pFile->pMethod->xClose(id);
6284 }
6285 return SQLITE_OK;
6286}
6287
6288
6289
drhd2cb50b2009-01-09 21:41:17 +00006290#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006291/*
6292** The proxy locking style is intended for use with AFP filesystems.
6293** And since AFP is only supported on MacOSX, the proxy locking is also
6294** restricted to MacOSX.
6295**
6296**
6297******************* End of the proxy lock implementation **********************
6298******************************************************************************/
6299
drh734c9862008-11-28 15:37:20 +00006300/*
danielk1977e339d652008-06-28 11:23:00 +00006301** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006302**
6303** This routine registers all VFS implementations for unix-like operating
6304** systems. This routine, and the sqlite3_os_end() routine that follows,
6305** should be the only routines in this file that are visible from other
6306** files.
drh6b9d6dd2008-12-03 19:34:47 +00006307**
6308** This routine is called once during SQLite initialization and by a
6309** single thread. The memory allocation and mutex subsystems have not
6310** necessarily been initialized when this routine is called, and so they
6311** should not be used.
drh153c62c2007-08-24 03:51:33 +00006312*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006313int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006314 /*
6315 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006316 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6317 ** to the "finder" function. (pAppData is a pointer to a pointer because
6318 ** silly C90 rules prohibit a void* from being cast to a function pointer
6319 ** and so we have to go through the intermediate pointer to avoid problems
6320 ** when compiling with -pedantic-errors on GCC.)
6321 **
6322 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006323 ** finder-function. The finder-function returns a pointer to the
6324 ** sqlite_io_methods object that implements the desired locking
6325 ** behaviors. See the division above that contains the IOMETHODS
6326 ** macro for addition information on finder-functions.
6327 **
6328 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6329 ** object. But the "autolockIoFinder" available on MacOSX does a little
6330 ** more than that; it looks at the filesystem type that hosts the
6331 ** database file and tries to choose an locking method appropriate for
6332 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006333 */
drh7708e972008-11-29 00:56:52 +00006334 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006335 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006336 sizeof(unixFile), /* szOsFile */ \
6337 MAX_PATHNAME, /* mxPathname */ \
6338 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006339 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006340 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006341 unixOpen, /* xOpen */ \
6342 unixDelete, /* xDelete */ \
6343 unixAccess, /* xAccess */ \
6344 unixFullPathname, /* xFullPathname */ \
6345 unixDlOpen, /* xDlOpen */ \
6346 unixDlError, /* xDlError */ \
6347 unixDlSym, /* xDlSym */ \
6348 unixDlClose, /* xDlClose */ \
6349 unixRandomness, /* xRandomness */ \
6350 unixSleep, /* xSleep */ \
6351 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006352 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006353 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006354 }
6355
drh6b9d6dd2008-12-03 19:34:47 +00006356 /*
6357 ** All default VFSes for unix are contained in the following array.
6358 **
6359 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6360 ** by the SQLite core when the VFS is registered. So the following
6361 ** array cannot be const.
6362 */
danielk1977e339d652008-06-28 11:23:00 +00006363 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006364#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006365 UNIXVFS("unix", autolockIoFinder ),
6366#else
6367 UNIXVFS("unix", posixIoFinder ),
6368#endif
6369 UNIXVFS("unix-none", nolockIoFinder ),
6370 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006371#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006372 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006373#endif
6374#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006375 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006376#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006377 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006378#endif
chw78a13182009-04-07 05:35:03 +00006379#endif
drhd2cb50b2009-01-09 21:41:17 +00006380#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006381 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006382 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006383 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006384#endif
drh153c62c2007-08-24 03:51:33 +00006385 };
drh6b9d6dd2008-12-03 19:34:47 +00006386 unsigned int i; /* Loop counter */
6387
6388 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006389 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006390 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006391 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006392 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006393}
danielk1977e339d652008-06-28 11:23:00 +00006394
6395/*
drh6b9d6dd2008-12-03 19:34:47 +00006396** Shutdown the operating system interface.
6397**
6398** Some operating systems might need to do some cleanup in this routine,
6399** to release dynamically allocated objects. But not on unix.
6400** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006401*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006402int sqlite3_os_end(void){
6403 return SQLITE_OK;
6404}
drhdce8bdb2007-08-16 13:01:44 +00006405
danielk197729bafea2008-06-26 10:41:19 +00006406#endif /* SQLITE_OS_UNIX */