blob: fa200ae80019019ebaa83ff8efd0718183fce969 [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/*
danb0ac3e32010-06-16 10:55:42 +0000742** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
743** If all such file descriptors are closed without error, the list is
744** cleared and SQLITE_OK returned.
745**
746** Otherwise, if an error occurs, then successfully closed file descriptor
747** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
748** not deleted and SQLITE_IOERR_CLOSE returned.
749*/
750static int closePendingFds(unixFile *pFile){
751 int rc = SQLITE_OK;
752 unixInodeInfo *pInode = pFile->pInode;
753 UnixUnusedFd *pError = 0;
754 UnixUnusedFd *p;
755 UnixUnusedFd *pNext;
756 for(p=pInode->pUnused; p; p=pNext){
757 pNext = p->pNext;
758 if( close(p->fd) ){
759 pFile->lastErrno = errno;
760 rc = SQLITE_IOERR_CLOSE;
761 p->pNext = pError;
762 pError = p;
763 }else{
764 sqlite3_free(p);
765 }
766 }
767 pInode->pUnused = pError;
768 return rc;
769}
770
771/*
drh8af6c222010-05-14 12:43:01 +0000772** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000773**
774** The mutex entered using the unixEnterMutex() function must be held
775** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000776*/
danb0ac3e32010-06-16 10:55:42 +0000777static void releaseInodeInfo(unixFile *pFile){
778 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000779 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000780 if( pInode ){
781 pInode->nRef--;
782 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000783 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000784 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000785 if( pInode->pPrev ){
786 assert( pInode->pPrev->pNext==pInode );
787 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000788 }else{
drh8af6c222010-05-14 12:43:01 +0000789 assert( inodeList==pInode );
790 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000791 }
drh8af6c222010-05-14 12:43:01 +0000792 if( pInode->pNext ){
793 assert( pInode->pNext->pPrev==pInode );
794 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000795 }
drh8af6c222010-05-14 12:43:01 +0000796 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000797 }
drhbbd42a62004-05-22 17:41:58 +0000798 }
799}
800
801/*
drh8af6c222010-05-14 12:43:01 +0000802** Given a file descriptor, locate the unixInodeInfo object that
803** describes that file descriptor. Create a new one if necessary. The
804** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000805**
dan9359c7b2009-08-21 08:29:10 +0000806** The mutex entered using the unixEnterMutex() function must be held
807** when this function is called.
808**
drh6c7d5c52008-11-21 20:32:33 +0000809** Return an appropriate error code.
810*/
drh8af6c222010-05-14 12:43:01 +0000811static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000812 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000813 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000814){
815 int rc; /* System call return code */
816 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000817 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
818 struct stat statbuf; /* Low-level file information */
819 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000820
dan9359c7b2009-08-21 08:29:10 +0000821 assert( unixMutexHeld() );
822
drh6c7d5c52008-11-21 20:32:33 +0000823 /* Get low-level information about the file that we can used to
824 ** create a unique name for the file.
825 */
826 fd = pFile->h;
827 rc = fstat(fd, &statbuf);
828 if( rc!=0 ){
829 pFile->lastErrno = errno;
830#ifdef EOVERFLOW
831 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
832#endif
833 return SQLITE_IOERR;
834 }
835
drheb0d74f2009-02-03 15:27:02 +0000836#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000837 /* On OS X on an msdos filesystem, the inode number is reported
838 ** incorrectly for zero-size files. See ticket #3260. To work
839 ** around this problem (we consider it a bug in OS X, not SQLite)
840 ** we always increase the file size to 1 by writing a single byte
841 ** prior to accessing the inode number. The one byte written is
842 ** an ASCII 'S' character which also happens to be the first byte
843 ** in the header of every SQLite database. In this way, if there
844 ** is a race condition such that another thread has already populated
845 ** the first page of the database, no damage is done.
846 */
drh7ed97b92010-01-20 13:07:21 +0000847 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +0000848 rc = write(fd, "S", 1);
849 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000850 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000851 return SQLITE_IOERR;
852 }
drh6c7d5c52008-11-21 20:32:33 +0000853 rc = fstat(fd, &statbuf);
854 if( rc!=0 ){
855 pFile->lastErrno = errno;
856 return SQLITE_IOERR;
857 }
858 }
drheb0d74f2009-02-03 15:27:02 +0000859#endif
drh6c7d5c52008-11-21 20:32:33 +0000860
drh8af6c222010-05-14 12:43:01 +0000861 memset(&fileId, 0, sizeof(fileId));
862 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000863#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000864 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000865#else
drh8af6c222010-05-14 12:43:01 +0000866 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000867#endif
drh8af6c222010-05-14 12:43:01 +0000868 pInode = inodeList;
869 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
870 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000871 }
drh8af6c222010-05-14 12:43:01 +0000872 if( pInode==0 ){
873 pInode = sqlite3_malloc( sizeof(*pInode) );
874 if( pInode==0 ){
875 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000876 }
drh8af6c222010-05-14 12:43:01 +0000877 memset(pInode, 0, sizeof(*pInode));
878 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
879 pInode->nRef = 1;
880 pInode->pNext = inodeList;
881 pInode->pPrev = 0;
882 if( inodeList ) inodeList->pPrev = pInode;
883 inodeList = pInode;
884 }else{
885 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000886 }
drh8af6c222010-05-14 12:43:01 +0000887 *ppInode = pInode;
888 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000889}
drh6c7d5c52008-11-21 20:32:33 +0000890
aswift5b1a2562008-08-22 00:22:35 +0000891
892/*
danielk197713adf8a2004-06-03 16:08:41 +0000893** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000894** file by this or any other process. If such a lock is held, set *pResOut
895** to a non-zero value otherwise *pResOut is set to zero. The return value
896** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000897*/
danielk1977861f7452008-06-05 11:39:11 +0000898static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000899 int rc = SQLITE_OK;
900 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000901 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000902
danielk1977861f7452008-06-05 11:39:11 +0000903 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
904
drh054889e2005-11-30 03:20:31 +0000905 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000906 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000907
908 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000909 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000910 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000911 }
912
drh2ac3ee92004-06-07 16:27:46 +0000913 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000914 */
danielk197709480a92009-02-09 05:32:32 +0000915#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000916 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000917 struct flock lock;
918 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000919 lock.l_start = RESERVED_BYTE;
920 lock.l_len = 1;
921 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +0000922 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
923 int tErrno = errno;
924 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
925 pFile->lastErrno = tErrno;
926 } else if( lock.l_type!=F_UNLCK ){
927 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000928 }
929 }
danielk197709480a92009-02-09 05:32:32 +0000930#endif
danielk197713adf8a2004-06-03 16:08:41 +0000931
drh6c7d5c52008-11-21 20:32:33 +0000932 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +0000933 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +0000934
aswift5b1a2562008-08-22 00:22:35 +0000935 *pResOut = reserved;
936 return rc;
danielk197713adf8a2004-06-03 16:08:41 +0000937}
938
939/*
drh308c2a52010-05-14 11:30:18 +0000940** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +0000941** of the following:
942**
drh2ac3ee92004-06-07 16:27:46 +0000943** (1) SHARED_LOCK
944** (2) RESERVED_LOCK
945** (3) PENDING_LOCK
946** (4) EXCLUSIVE_LOCK
947**
drhb3e04342004-06-08 00:47:47 +0000948** Sometimes when requesting one lock state, additional lock states
949** are inserted in between. The locking might fail on one of the later
950** transitions leaving the lock state different from what it started but
951** still short of its goal. The following chart shows the allowed
952** transitions and the inserted intermediate states:
953**
954** UNLOCKED -> SHARED
955** SHARED -> RESERVED
956** SHARED -> (PENDING) -> EXCLUSIVE
957** RESERVED -> (PENDING) -> EXCLUSIVE
958** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000959**
drha6abd042004-06-09 17:37:22 +0000960** This routine will only increase a lock. Use the sqlite3OsUnlock()
961** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000962*/
drh308c2a52010-05-14 11:30:18 +0000963static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +0000964 /* The following describes the implementation of the various locks and
965 ** lock transitions in terms of the POSIX advisory shared and exclusive
966 ** lock primitives (called read-locks and write-locks below, to avoid
967 ** confusion with SQLite lock names). The algorithms are complicated
968 ** slightly in order to be compatible with windows systems simultaneously
969 ** accessing the same database file, in case that is ever required.
970 **
971 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
972 ** byte', each single bytes at well known offsets, and the 'shared byte
973 ** range', a range of 510 bytes at a well known offset.
974 **
975 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
976 ** byte'. If this is successful, a random byte from the 'shared byte
977 ** range' is read-locked and the lock on the 'pending byte' released.
978 **
danielk197790ba3bd2004-06-25 08:32:25 +0000979 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
980 ** A RESERVED lock is implemented by grabbing a write-lock on the
981 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000982 **
983 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000984 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
985 ** on the 'pending byte'. This ensures that no new SHARED locks can be
986 ** obtained, but existing SHARED locks are allowed to persist. A process
987 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
988 ** This property is used by the algorithm for rolling back a journal file
989 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000990 **
danielk197790ba3bd2004-06-25 08:32:25 +0000991 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
992 ** implemented by obtaining a write-lock on the entire 'shared byte
993 ** range'. Since all other locks require a read-lock on one of the bytes
994 ** within this range, this ensures that no other locks are held on the
995 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000996 **
997 ** The reason a single byte cannot be used instead of the 'shared byte
998 ** range' is that some versions of windows do not support read-locks. By
999 ** locking a random byte from a range, concurrent SHARED locks may exist
1000 ** even if the locking primitive used is always a write-lock.
1001 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001002 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001003 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001004 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001005 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001006 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001007 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001008
drh054889e2005-11-30 03:20:31 +00001009 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001010 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1011 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001012 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001013
1014 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001015 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001016 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001017 */
drh308c2a52010-05-14 11:30:18 +00001018 if( pFile->eFileLock>=eFileLock ){
1019 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1020 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001021 return SQLITE_OK;
1022 }
1023
drh0c2694b2009-09-03 16:23:44 +00001024 /* Make sure the locking sequence is correct.
1025 ** (1) We never move from unlocked to anything higher than shared lock.
1026 ** (2) SQLite never explicitly requests a pendig lock.
1027 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001028 */
drh308c2a52010-05-14 11:30:18 +00001029 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1030 assert( eFileLock!=PENDING_LOCK );
1031 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001032
drh8af6c222010-05-14 12:43:01 +00001033 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001034 */
drh6c7d5c52008-11-21 20:32:33 +00001035 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001036 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001037
danielk1977ad94b582007-08-20 06:44:22 +00001038 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001039 ** handle that precludes the requested lock, return BUSY.
1040 */
drh8af6c222010-05-14 12:43:01 +00001041 if( (pFile->eFileLock!=pInode->eFileLock &&
1042 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001043 ){
1044 rc = SQLITE_BUSY;
1045 goto end_lock;
1046 }
1047
1048 /* If a SHARED lock is requested, and some thread using this PID already
1049 ** has a SHARED or RESERVED lock, then increment reference counts and
1050 ** return SQLITE_OK.
1051 */
drh308c2a52010-05-14 11:30:18 +00001052 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001053 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001054 assert( eFileLock==SHARED_LOCK );
1055 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001056 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001057 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001058 pInode->nShared++;
1059 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001060 goto end_lock;
1061 }
1062
danielk19779a1d0ab2004-06-01 14:09:28 +00001063
drh3cde3bb2004-06-12 02:17:14 +00001064 /* A PENDING lock is needed before acquiring a SHARED lock and before
1065 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1066 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001067 */
drh0c2694b2009-09-03 16:23:44 +00001068 lock.l_len = 1L;
1069 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001070 if( eFileLock==SHARED_LOCK
1071 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001072 ){
drh308c2a52010-05-14 11:30:18 +00001073 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001074 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001075 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001076 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001077 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001078 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1079 if( IS_LOCK_ERROR(rc) ){
1080 pFile->lastErrno = tErrno;
1081 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001082 goto end_lock;
1083 }
drh3cde3bb2004-06-12 02:17:14 +00001084 }
1085
1086
1087 /* If control gets to this point, then actually go ahead and make
1088 ** operating system calls for the specified lock.
1089 */
drh308c2a52010-05-14 11:30:18 +00001090 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001091 assert( pInode->nShared==0 );
1092 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001093
drh2ac3ee92004-06-07 16:27:46 +00001094 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001095 lock.l_start = SHARED_FIRST;
1096 lock.l_len = SHARED_SIZE;
1097 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1098 tErrno = errno;
1099 }
drh2ac3ee92004-06-07 16:27:46 +00001100 /* Drop the temporary PENDING lock */
1101 lock.l_start = PENDING_BYTE;
1102 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001103 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001104 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001105 if( s != -1 ){
1106 /* This could happen with a network mount */
1107 tErrno = errno;
1108 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1109 if( IS_LOCK_ERROR(rc) ){
1110 pFile->lastErrno = tErrno;
1111 }
1112 goto end_lock;
1113 }
drh2b4b5962005-06-15 17:47:55 +00001114 }
drhe2396a12007-03-29 20:19:58 +00001115 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001116 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1117 if( IS_LOCK_ERROR(rc) ){
1118 pFile->lastErrno = tErrno;
1119 }
drhbbd42a62004-05-22 17:41:58 +00001120 }else{
drh308c2a52010-05-14 11:30:18 +00001121 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001122 pInode->nLock++;
1123 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001124 }
drh8af6c222010-05-14 12:43:01 +00001125 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001126 /* We are trying for an exclusive lock but another thread in this
1127 ** same process is still holding a shared lock. */
1128 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001129 }else{
drh3cde3bb2004-06-12 02:17:14 +00001130 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001131 ** assumed that there is a SHARED or greater lock on the file
1132 ** already.
1133 */
drh308c2a52010-05-14 11:30:18 +00001134 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001135 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001136 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001137 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001138 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001139 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001140 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001141 lock.l_start = SHARED_FIRST;
1142 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001143 break;
1144 default:
1145 assert(0);
1146 }
drh7ed97b92010-01-20 13:07:21 +00001147 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001148 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001149 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001150 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1151 if( IS_LOCK_ERROR(rc) ){
1152 pFile->lastErrno = tErrno;
1153 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001154 }
drhbbd42a62004-05-22 17:41:58 +00001155 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001156
drh8f941bc2009-01-14 23:03:40 +00001157
1158#ifndef NDEBUG
1159 /* Set up the transaction-counter change checking flags when
1160 ** transitioning from a SHARED to a RESERVED lock. The change
1161 ** from SHARED to RESERVED marks the beginning of a normal
1162 ** write operation (not a hot journal rollback).
1163 */
1164 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001165 && pFile->eFileLock<=SHARED_LOCK
1166 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001167 ){
1168 pFile->transCntrChng = 0;
1169 pFile->dbUpdate = 0;
1170 pFile->inNormalWrite = 1;
1171 }
1172#endif
1173
1174
danielk1977ecb2a962004-06-02 06:30:16 +00001175 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001176 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001177 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001178 }else if( eFileLock==EXCLUSIVE_LOCK ){
1179 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001180 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001181 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001182
1183end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001184 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001185 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1186 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001187 return rc;
1188}
1189
1190/*
dan08da86a2009-08-21 17:18:03 +00001191** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001192** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001193*/
1194static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001195 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001196 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001197 p->pNext = pInode->pUnused;
1198 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001199 pFile->h = -1;
1200 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001201}
1202
1203/*
drh308c2a52010-05-14 11:30:18 +00001204** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001205** must be either NO_LOCK or SHARED_LOCK.
1206**
1207** If the locking level of the file descriptor is already at or below
1208** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001209**
1210** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1211** the byte range is divided into 2 parts and the first part is unlocked then
1212** set to a read lock, then the other part is simply unlocked. This works
1213** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1214** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001215*/
drh308c2a52010-05-14 11:30:18 +00001216static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001217 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001218 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001219 struct flock lock;
1220 int rc = SQLITE_OK;
1221 int h;
drh0c2694b2009-09-03 16:23:44 +00001222 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001223
drh054889e2005-11-30 03:20:31 +00001224 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001225 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001226 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001227 getpid()));
drha6abd042004-06-09 17:37:22 +00001228
drh308c2a52010-05-14 11:30:18 +00001229 assert( eFileLock<=SHARED_LOCK );
1230 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001231 return SQLITE_OK;
1232 }
drh6c7d5c52008-11-21 20:32:33 +00001233 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001234 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001235 pInode = pFile->pInode;
1236 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001237 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001238 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001239 SimulateIOErrorBenign(1);
1240 SimulateIOError( h=(-1) )
1241 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001242
1243#ifndef NDEBUG
1244 /* When reducing a lock such that other processes can start
1245 ** reading the database file again, make sure that the
1246 ** transaction counter was updated if any part of the database
1247 ** file changed. If the transaction counter is not updated,
1248 ** other connections to the same file might not realize that
1249 ** the file has changed and hence might not know to flush their
1250 ** cache. The use of a stale cache can lead to database corruption.
1251 */
dan7c246102010-04-12 19:00:29 +00001252#if 0
drh8f941bc2009-01-14 23:03:40 +00001253 assert( pFile->inNormalWrite==0
1254 || pFile->dbUpdate==0
1255 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001256#endif
drh8f941bc2009-01-14 23:03:40 +00001257 pFile->inNormalWrite = 0;
1258#endif
1259
drh7ed97b92010-01-20 13:07:21 +00001260 /* downgrading to a shared lock on NFS involves clearing the write lock
1261 ** before establishing the readlock - to avoid a race condition we downgrade
1262 ** the lock in 2 blocks, so that part of the range will be covered by a
1263 ** write lock until the rest is covered by a read lock:
1264 ** 1: [WWWWW]
1265 ** 2: [....W]
1266 ** 3: [RRRRW]
1267 ** 4: [RRRR.]
1268 */
drh308c2a52010-05-14 11:30:18 +00001269 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001270 if( handleNFSUnlock ){
1271 off_t divSize = SHARED_SIZE - 1;
1272
1273 lock.l_type = F_UNLCK;
1274 lock.l_whence = SEEK_SET;
1275 lock.l_start = SHARED_FIRST;
1276 lock.l_len = divSize;
1277 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001278 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001279 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1280 if( IS_LOCK_ERROR(rc) ){
1281 pFile->lastErrno = tErrno;
1282 }
1283 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001284 }
drh7ed97b92010-01-20 13:07:21 +00001285 lock.l_type = F_RDLCK;
1286 lock.l_whence = SEEK_SET;
1287 lock.l_start = SHARED_FIRST;
1288 lock.l_len = divSize;
1289 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001290 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001291 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1292 if( IS_LOCK_ERROR(rc) ){
1293 pFile->lastErrno = tErrno;
1294 }
1295 goto end_unlock;
1296 }
1297 lock.l_type = F_UNLCK;
1298 lock.l_whence = SEEK_SET;
1299 lock.l_start = SHARED_FIRST+divSize;
1300 lock.l_len = SHARED_SIZE-divSize;
1301 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001302 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001303 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1304 if( IS_LOCK_ERROR(rc) ){
1305 pFile->lastErrno = tErrno;
1306 }
1307 goto end_unlock;
1308 }
1309 }else{
1310 lock.l_type = F_RDLCK;
1311 lock.l_whence = SEEK_SET;
1312 lock.l_start = SHARED_FIRST;
1313 lock.l_len = SHARED_SIZE;
1314 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001315 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001316 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1317 if( IS_LOCK_ERROR(rc) ){
1318 pFile->lastErrno = tErrno;
1319 }
1320 goto end_unlock;
1321 }
drh9c105bb2004-10-02 20:38:28 +00001322 }
1323 }
drhbbd42a62004-05-22 17:41:58 +00001324 lock.l_type = F_UNLCK;
1325 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001326 lock.l_start = PENDING_BYTE;
1327 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001328 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001329 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001330 }else{
drh0c2694b2009-09-03 16:23:44 +00001331 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001332 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1333 if( IS_LOCK_ERROR(rc) ){
1334 pFile->lastErrno = tErrno;
1335 }
drhcd731cf2009-03-28 23:23:02 +00001336 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001337 }
drhbbd42a62004-05-22 17:41:58 +00001338 }
drh308c2a52010-05-14 11:30:18 +00001339 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001340 /* Decrement the shared lock counter. Release the lock using an
1341 ** OS call only when all threads in this same process have released
1342 ** the lock.
1343 */
drh8af6c222010-05-14 12:43:01 +00001344 pInode->nShared--;
1345 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001346 lock.l_type = F_UNLCK;
1347 lock.l_whence = SEEK_SET;
1348 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001349 SimulateIOErrorBenign(1);
1350 SimulateIOError( h=(-1) )
1351 SimulateIOErrorBenign(0);
1352 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001353 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001354 }else{
drh0c2694b2009-09-03 16:23:44 +00001355 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001356 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001357 if( IS_LOCK_ERROR(rc) ){
1358 pFile->lastErrno = tErrno;
1359 }
drh8af6c222010-05-14 12:43:01 +00001360 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001361 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001362 }
drha6abd042004-06-09 17:37:22 +00001363 }
1364
drhbbd42a62004-05-22 17:41:58 +00001365 /* Decrement the count of locks against this same file. When the
1366 ** count reaches zero, close any other file descriptors whose close
1367 ** was deferred because of outstanding locks.
1368 */
drh8af6c222010-05-14 12:43:01 +00001369 pInode->nLock--;
1370 assert( pInode->nLock>=0 );
1371 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001372 int rc2 = closePendingFds(pFile);
1373 if( rc==SQLITE_OK ){
1374 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001375 }
drhbbd42a62004-05-22 17:41:58 +00001376 }
1377 }
aswift5b1a2562008-08-22 00:22:35 +00001378
1379end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001380 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001381 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001382 return rc;
drhbbd42a62004-05-22 17:41:58 +00001383}
1384
1385/*
drh308c2a52010-05-14 11:30:18 +00001386** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001387** must be either NO_LOCK or SHARED_LOCK.
1388**
1389** If the locking level of the file descriptor is already at or below
1390** the requested locking level, this routine is a no-op.
1391*/
drh308c2a52010-05-14 11:30:18 +00001392static int unixUnlock(sqlite3_file *id, int eFileLock){
1393 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001394}
1395
1396/*
danielk1977e339d652008-06-28 11:23:00 +00001397** This function performs the parts of the "close file" operation
1398** common to all locking schemes. It closes the directory and file
1399** handles, if they are valid, and sets all fields of the unixFile
1400** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001401**
1402** It is *not* necessary to hold the mutex when this routine is called,
1403** even on VxWorks. A mutex will be acquired on VxWorks by the
1404** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001405*/
1406static int closeUnixFile(sqlite3_file *id){
1407 unixFile *pFile = (unixFile*)id;
1408 if( pFile ){
1409 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001410 int err = close(pFile->dirfd);
1411 if( err ){
1412 pFile->lastErrno = errno;
1413 return SQLITE_IOERR_DIR_CLOSE;
1414 }else{
1415 pFile->dirfd=-1;
1416 }
danielk1977e339d652008-06-28 11:23:00 +00001417 }
1418 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001419 int err = close(pFile->h);
1420 if( err ){
1421 pFile->lastErrno = errno;
1422 return SQLITE_IOERR_CLOSE;
1423 }
danielk1977e339d652008-06-28 11:23:00 +00001424 }
drh6c7d5c52008-11-21 20:32:33 +00001425#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001426 if( pFile->pId ){
1427 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001428 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001429 }
drh107886a2008-11-21 22:21:50 +00001430 vxworksReleaseFileId(pFile->pId);
1431 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001432 }
1433#endif
drhff59a112010-05-14 20:15:51 +00001434 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001435 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001436 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001437 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001438 }
1439 return SQLITE_OK;
1440}
1441
1442/*
danielk1977e3026632004-06-22 11:29:02 +00001443** Close a file.
1444*/
danielk197762079062007-08-15 17:08:46 +00001445static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001446 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001447 if( id ){
1448 unixFile *pFile = (unixFile *)id;
1449 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001450 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001451 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001452 /* If there are outstanding locks, do not actually close the file just
1453 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001454 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001455 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001456 */
dan08da86a2009-08-21 17:18:03 +00001457 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001458 }
danb0ac3e32010-06-16 10:55:42 +00001459 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001460 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001461 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001462 }
aswiftaebf4132008-11-21 00:10:35 +00001463 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001464}
1465
drh734c9862008-11-28 15:37:20 +00001466/************** End of the posix advisory lock implementation *****************
1467******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001468
drh734c9862008-11-28 15:37:20 +00001469/******************************************************************************
1470****************************** No-op Locking **********************************
1471**
1472** Of the various locking implementations available, this is by far the
1473** simplest: locking is ignored. No attempt is made to lock the database
1474** file for reading or writing.
1475**
1476** This locking mode is appropriate for use on read-only databases
1477** (ex: databases that are burned into CD-ROM, for example.) It can
1478** also be used if the application employs some external mechanism to
1479** prevent simultaneous access of the same database by two or more
1480** database connections. But there is a serious risk of database
1481** corruption if this locking mode is used in situations where multiple
1482** database connections are accessing the same database file at the same
1483** time and one or more of those connections are writing.
1484*/
drhbfe66312006-10-03 17:40:40 +00001485
drh734c9862008-11-28 15:37:20 +00001486static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1487 UNUSED_PARAMETER(NotUsed);
1488 *pResOut = 0;
1489 return SQLITE_OK;
1490}
drh734c9862008-11-28 15:37:20 +00001491static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1492 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1493 return SQLITE_OK;
1494}
drh734c9862008-11-28 15:37:20 +00001495static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1496 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1497 return SQLITE_OK;
1498}
1499
1500/*
drh9b35ea62008-11-29 02:20:26 +00001501** Close the file.
drh734c9862008-11-28 15:37:20 +00001502*/
1503static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001504 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001505}
1506
1507/******************* End of the no-op lock implementation *********************
1508******************************************************************************/
1509
1510/******************************************************************************
1511************************* Begin dot-file Locking ******************************
1512**
drh0c2694b2009-09-03 16:23:44 +00001513** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001514** files in order to control access to the database. This works on just
1515** about every filesystem imaginable. But there are serious downsides:
1516**
1517** (1) There is zero concurrency. A single reader blocks all other
1518** connections from reading or writing the database.
1519**
1520** (2) An application crash or power loss can leave stale lock files
1521** sitting around that need to be cleared manually.
1522**
1523** Nevertheless, a dotlock is an appropriate locking mode for use if no
1524** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001525**
1526** Dotfile locking works by creating a file in the same directory as the
1527** database and with the same name but with a ".lock" extension added.
1528** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1529** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001530*/
1531
1532/*
1533** The file suffix added to the data base filename in order to create the
1534** lock file.
1535*/
1536#define DOTLOCK_SUFFIX ".lock"
1537
drh7708e972008-11-29 00:56:52 +00001538/*
1539** This routine checks if there is a RESERVED lock held on the specified
1540** file by this or any other process. If such a lock is held, set *pResOut
1541** to a non-zero value otherwise *pResOut is set to zero. The return value
1542** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1543**
1544** In dotfile locking, either a lock exists or it does not. So in this
1545** variation of CheckReservedLock(), *pResOut is set to true if any lock
1546** is held on the file and false if the file is unlocked.
1547*/
drh734c9862008-11-28 15:37:20 +00001548static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1549 int rc = SQLITE_OK;
1550 int reserved = 0;
1551 unixFile *pFile = (unixFile*)id;
1552
1553 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1554
1555 assert( pFile );
1556
1557 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001558 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001559 /* Either this connection or some other connection in the same process
1560 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001561 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001562 }else{
1563 /* The lock is held if and only if the lockfile exists */
1564 const char *zLockFile = (const char*)pFile->lockingContext;
1565 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001566 }
drh308c2a52010-05-14 11:30:18 +00001567 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001568 *pResOut = reserved;
1569 return rc;
1570}
1571
drh7708e972008-11-29 00:56:52 +00001572/*
drh308c2a52010-05-14 11:30:18 +00001573** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001574** of the following:
1575**
1576** (1) SHARED_LOCK
1577** (2) RESERVED_LOCK
1578** (3) PENDING_LOCK
1579** (4) EXCLUSIVE_LOCK
1580**
1581** Sometimes when requesting one lock state, additional lock states
1582** are inserted in between. The locking might fail on one of the later
1583** transitions leaving the lock state different from what it started but
1584** still short of its goal. The following chart shows the allowed
1585** transitions and the inserted intermediate states:
1586**
1587** UNLOCKED -> SHARED
1588** SHARED -> RESERVED
1589** SHARED -> (PENDING) -> EXCLUSIVE
1590** RESERVED -> (PENDING) -> EXCLUSIVE
1591** PENDING -> EXCLUSIVE
1592**
1593** This routine will only increase a lock. Use the sqlite3OsUnlock()
1594** routine to lower a locking level.
1595**
1596** With dotfile locking, we really only support state (4): EXCLUSIVE.
1597** But we track the other locking levels internally.
1598*/
drh308c2a52010-05-14 11:30:18 +00001599static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001600 unixFile *pFile = (unixFile*)id;
1601 int fd;
1602 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001603 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001604
drh7708e972008-11-29 00:56:52 +00001605
1606 /* If we have any lock, then the lock file already exists. All we have
1607 ** to do is adjust our internal record of the lock level.
1608 */
drh308c2a52010-05-14 11:30:18 +00001609 if( pFile->eFileLock > NO_LOCK ){
1610 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001611#if !OS_VXWORKS
1612 /* Always update the timestamp on the old file */
1613 utimes(zLockFile, NULL);
1614#endif
drh7708e972008-11-29 00:56:52 +00001615 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001616 }
1617
1618 /* grab an exclusive lock */
1619 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1620 if( fd<0 ){
1621 /* failed to open/create the file, someone else may have stolen the lock */
1622 int tErrno = errno;
1623 if( EEXIST == tErrno ){
1624 rc = SQLITE_BUSY;
1625 } else {
1626 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1627 if( IS_LOCK_ERROR(rc) ){
1628 pFile->lastErrno = tErrno;
1629 }
1630 }
drh7708e972008-11-29 00:56:52 +00001631 return rc;
drh734c9862008-11-28 15:37:20 +00001632 }
1633 if( close(fd) ){
1634 pFile->lastErrno = errno;
1635 rc = SQLITE_IOERR_CLOSE;
1636 }
1637
1638 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001639 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001640 return rc;
1641}
1642
drh7708e972008-11-29 00:56:52 +00001643/*
drh308c2a52010-05-14 11:30:18 +00001644** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001645** must be either NO_LOCK or SHARED_LOCK.
1646**
1647** If the locking level of the file descriptor is already at or below
1648** the requested locking level, this routine is a no-op.
1649**
1650** When the locking level reaches NO_LOCK, delete the lock file.
1651*/
drh308c2a52010-05-14 11:30:18 +00001652static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001653 unixFile *pFile = (unixFile*)id;
1654 char *zLockFile = (char *)pFile->lockingContext;
1655
1656 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001657 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1658 pFile->eFileLock, getpid()));
1659 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001660
1661 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001662 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001663 return SQLITE_OK;
1664 }
drh7708e972008-11-29 00:56:52 +00001665
1666 /* To downgrade to shared, simply update our internal notion of the
1667 ** lock state. No need to mess with the file on disk.
1668 */
drh308c2a52010-05-14 11:30:18 +00001669 if( eFileLock==SHARED_LOCK ){
1670 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001671 return SQLITE_OK;
1672 }
1673
drh7708e972008-11-29 00:56:52 +00001674 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001675 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001676 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001677 int rc = 0;
1678 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001679 if( ENOENT != tErrno ){
1680 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1681 }
1682 if( IS_LOCK_ERROR(rc) ){
1683 pFile->lastErrno = tErrno;
1684 }
1685 return rc;
1686 }
drh308c2a52010-05-14 11:30:18 +00001687 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001688 return SQLITE_OK;
1689}
1690
1691/*
drh9b35ea62008-11-29 02:20:26 +00001692** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001693*/
1694static int dotlockClose(sqlite3_file *id) {
1695 int rc;
1696 if( id ){
1697 unixFile *pFile = (unixFile*)id;
1698 dotlockUnlock(id, NO_LOCK);
1699 sqlite3_free(pFile->lockingContext);
1700 }
drh734c9862008-11-28 15:37:20 +00001701 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001702 return rc;
1703}
1704/****************** End of the dot-file lock implementation *******************
1705******************************************************************************/
1706
1707/******************************************************************************
1708************************** Begin flock Locking ********************************
1709**
1710** Use the flock() system call to do file locking.
1711**
drh6b9d6dd2008-12-03 19:34:47 +00001712** flock() locking is like dot-file locking in that the various
1713** fine-grain locking levels supported by SQLite are collapsed into
1714** a single exclusive lock. In other words, SHARED, RESERVED, and
1715** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1716** still works when you do this, but concurrency is reduced since
1717** only a single process can be reading the database at a time.
1718**
drh734c9862008-11-28 15:37:20 +00001719** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1720** compiling for VXWORKS.
1721*/
1722#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001723
drh6b9d6dd2008-12-03 19:34:47 +00001724/*
1725** This routine checks if there is a RESERVED lock held on the specified
1726** file by this or any other process. If such a lock is held, set *pResOut
1727** to a non-zero value otherwise *pResOut is set to zero. The return value
1728** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1729*/
drh734c9862008-11-28 15:37:20 +00001730static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1731 int rc = SQLITE_OK;
1732 int reserved = 0;
1733 unixFile *pFile = (unixFile*)id;
1734
1735 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1736
1737 assert( pFile );
1738
1739 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001740 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001741 reserved = 1;
1742 }
1743
1744 /* Otherwise see if some other process holds it. */
1745 if( !reserved ){
1746 /* attempt to get the lock */
1747 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1748 if( !lrc ){
1749 /* got the lock, unlock it */
1750 lrc = flock(pFile->h, LOCK_UN);
1751 if ( lrc ) {
1752 int tErrno = errno;
1753 /* unlock failed with an error */
1754 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1755 if( IS_LOCK_ERROR(lrc) ){
1756 pFile->lastErrno = tErrno;
1757 rc = lrc;
1758 }
1759 }
1760 } else {
1761 int tErrno = errno;
1762 reserved = 1;
1763 /* someone else might have it reserved */
1764 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1765 if( IS_LOCK_ERROR(lrc) ){
1766 pFile->lastErrno = tErrno;
1767 rc = lrc;
1768 }
1769 }
1770 }
drh308c2a52010-05-14 11:30:18 +00001771 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001772
1773#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1774 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1775 rc = SQLITE_OK;
1776 reserved=1;
1777 }
1778#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1779 *pResOut = reserved;
1780 return rc;
1781}
1782
drh6b9d6dd2008-12-03 19:34:47 +00001783/*
drh308c2a52010-05-14 11:30:18 +00001784** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001785** of the following:
1786**
1787** (1) SHARED_LOCK
1788** (2) RESERVED_LOCK
1789** (3) PENDING_LOCK
1790** (4) EXCLUSIVE_LOCK
1791**
1792** Sometimes when requesting one lock state, additional lock states
1793** are inserted in between. The locking might fail on one of the later
1794** transitions leaving the lock state different from what it started but
1795** still short of its goal. The following chart shows the allowed
1796** transitions and the inserted intermediate states:
1797**
1798** UNLOCKED -> SHARED
1799** SHARED -> RESERVED
1800** SHARED -> (PENDING) -> EXCLUSIVE
1801** RESERVED -> (PENDING) -> EXCLUSIVE
1802** PENDING -> EXCLUSIVE
1803**
1804** flock() only really support EXCLUSIVE locks. We track intermediate
1805** lock states in the sqlite3_file structure, but all locks SHARED or
1806** above are really EXCLUSIVE locks and exclude all other processes from
1807** access the file.
1808**
1809** This routine will only increase a lock. Use the sqlite3OsUnlock()
1810** routine to lower a locking level.
1811*/
drh308c2a52010-05-14 11:30:18 +00001812static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001813 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001814 unixFile *pFile = (unixFile*)id;
1815
1816 assert( pFile );
1817
1818 /* if we already have a lock, it is exclusive.
1819 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001820 if (pFile->eFileLock > NO_LOCK) {
1821 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001822 return SQLITE_OK;
1823 }
1824
1825 /* grab an exclusive lock */
1826
1827 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1828 int tErrno = errno;
1829 /* didn't get, must be busy */
1830 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1831 if( IS_LOCK_ERROR(rc) ){
1832 pFile->lastErrno = tErrno;
1833 }
1834 } else {
1835 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001836 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001837 }
drh308c2a52010-05-14 11:30:18 +00001838 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1839 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001840#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1841 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1842 rc = SQLITE_BUSY;
1843 }
1844#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1845 return rc;
1846}
1847
drh6b9d6dd2008-12-03 19:34:47 +00001848
1849/*
drh308c2a52010-05-14 11:30:18 +00001850** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001851** must be either NO_LOCK or SHARED_LOCK.
1852**
1853** If the locking level of the file descriptor is already at or below
1854** the requested locking level, this routine is a no-op.
1855*/
drh308c2a52010-05-14 11:30:18 +00001856static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001857 unixFile *pFile = (unixFile*)id;
1858
1859 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001860 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1861 pFile->eFileLock, getpid()));
1862 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001863
1864 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001865 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001866 return SQLITE_OK;
1867 }
1868
1869 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001870 if (eFileLock==SHARED_LOCK) {
1871 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001872 return SQLITE_OK;
1873 }
1874
1875 /* no, really, unlock. */
1876 int rc = flock(pFile->h, LOCK_UN);
1877 if (rc) {
1878 int r, tErrno = errno;
1879 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1880 if( IS_LOCK_ERROR(r) ){
1881 pFile->lastErrno = tErrno;
1882 }
1883#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1884 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1885 r = SQLITE_BUSY;
1886 }
1887#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1888
1889 return r;
1890 } else {
drh308c2a52010-05-14 11:30:18 +00001891 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001892 return SQLITE_OK;
1893 }
1894}
1895
1896/*
1897** Close a file.
1898*/
1899static int flockClose(sqlite3_file *id) {
1900 if( id ){
1901 flockUnlock(id, NO_LOCK);
1902 }
1903 return closeUnixFile(id);
1904}
1905
1906#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1907
1908/******************* End of the flock lock implementation *********************
1909******************************************************************************/
1910
1911/******************************************************************************
1912************************ Begin Named Semaphore Locking ************************
1913**
1914** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00001915**
1916** Semaphore locking is like dot-lock and flock in that it really only
1917** supports EXCLUSIVE locking. Only a single process can read or write
1918** the database file at a time. This reduces potential concurrency, but
1919** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00001920*/
1921#if OS_VXWORKS
1922
drh6b9d6dd2008-12-03 19:34:47 +00001923/*
1924** This routine checks if there is a RESERVED lock held on the specified
1925** file by this or any other process. If such a lock is held, set *pResOut
1926** to a non-zero value otherwise *pResOut is set to zero. The return value
1927** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1928*/
drh734c9862008-11-28 15:37:20 +00001929static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1930 int rc = SQLITE_OK;
1931 int reserved = 0;
1932 unixFile *pFile = (unixFile*)id;
1933
1934 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1935
1936 assert( pFile );
1937
1938 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001939 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001940 reserved = 1;
1941 }
1942
1943 /* Otherwise see if some other process holds it. */
1944 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00001945 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001946 struct stat statBuf;
1947
1948 if( sem_trywait(pSem)==-1 ){
1949 int tErrno = errno;
1950 if( EAGAIN != tErrno ){
1951 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1952 pFile->lastErrno = tErrno;
1953 } else {
1954 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00001955 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00001956 }
1957 }else{
1958 /* we could have it if we want it */
1959 sem_post(pSem);
1960 }
1961 }
drh308c2a52010-05-14 11:30:18 +00001962 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001963
1964 *pResOut = reserved;
1965 return rc;
1966}
1967
drh6b9d6dd2008-12-03 19:34:47 +00001968/*
drh308c2a52010-05-14 11:30:18 +00001969** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001970** of the following:
1971**
1972** (1) SHARED_LOCK
1973** (2) RESERVED_LOCK
1974** (3) PENDING_LOCK
1975** (4) EXCLUSIVE_LOCK
1976**
1977** Sometimes when requesting one lock state, additional lock states
1978** are inserted in between. The locking might fail on one of the later
1979** transitions leaving the lock state different from what it started but
1980** still short of its goal. The following chart shows the allowed
1981** transitions and the inserted intermediate states:
1982**
1983** UNLOCKED -> SHARED
1984** SHARED -> RESERVED
1985** SHARED -> (PENDING) -> EXCLUSIVE
1986** RESERVED -> (PENDING) -> EXCLUSIVE
1987** PENDING -> EXCLUSIVE
1988**
1989** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
1990** lock states in the sqlite3_file structure, but all locks SHARED or
1991** above are really EXCLUSIVE locks and exclude all other processes from
1992** access the file.
1993**
1994** This routine will only increase a lock. Use the sqlite3OsUnlock()
1995** routine to lower a locking level.
1996*/
drh308c2a52010-05-14 11:30:18 +00001997static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001998 unixFile *pFile = (unixFile*)id;
1999 int fd;
drh8af6c222010-05-14 12:43:01 +00002000 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002001 int rc = SQLITE_OK;
2002
2003 /* if we already have a lock, it is exclusive.
2004 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002005 if (pFile->eFileLock > NO_LOCK) {
2006 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002007 rc = SQLITE_OK;
2008 goto sem_end_lock;
2009 }
2010
2011 /* lock semaphore now but bail out when already locked. */
2012 if( sem_trywait(pSem)==-1 ){
2013 rc = SQLITE_BUSY;
2014 goto sem_end_lock;
2015 }
2016
2017 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002018 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002019
2020 sem_end_lock:
2021 return rc;
2022}
2023
drh6b9d6dd2008-12-03 19:34:47 +00002024/*
drh308c2a52010-05-14 11:30:18 +00002025** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002026** must be either NO_LOCK or SHARED_LOCK.
2027**
2028** If the locking level of the file descriptor is already at or below
2029** the requested locking level, this routine is a no-op.
2030*/
drh308c2a52010-05-14 11:30:18 +00002031static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002032 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002033 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002034
2035 assert( pFile );
2036 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002037 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2038 pFile->eFileLock, getpid()));
2039 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002040
2041 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002042 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002043 return SQLITE_OK;
2044 }
2045
2046 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002047 if (eFileLock==SHARED_LOCK) {
2048 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002049 return SQLITE_OK;
2050 }
2051
2052 /* no, really unlock. */
2053 if ( sem_post(pSem)==-1 ) {
2054 int rc, tErrno = errno;
2055 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2056 if( IS_LOCK_ERROR(rc) ){
2057 pFile->lastErrno = tErrno;
2058 }
2059 return rc;
2060 }
drh308c2a52010-05-14 11:30:18 +00002061 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002062 return SQLITE_OK;
2063}
2064
2065/*
2066 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002067 */
drh734c9862008-11-28 15:37:20 +00002068static int semClose(sqlite3_file *id) {
2069 if( id ){
2070 unixFile *pFile = (unixFile*)id;
2071 semUnlock(id, NO_LOCK);
2072 assert( pFile );
2073 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002074 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002075 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002076 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002077 }
2078 return SQLITE_OK;
2079}
2080
2081#endif /* OS_VXWORKS */
2082/*
2083** Named semaphore locking is only available on VxWorks.
2084**
2085*************** End of the named semaphore lock implementation ****************
2086******************************************************************************/
2087
2088
2089/******************************************************************************
2090*************************** Begin AFP Locking *********************************
2091**
2092** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2093** on Apple Macintosh computers - both OS9 and OSX.
2094**
2095** Third-party implementations of AFP are available. But this code here
2096** only works on OSX.
2097*/
2098
drhd2cb50b2009-01-09 21:41:17 +00002099#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002100/*
2101** The afpLockingContext structure contains all afp lock specific state
2102*/
drhbfe66312006-10-03 17:40:40 +00002103typedef struct afpLockingContext afpLockingContext;
2104struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002105 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002106 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002107};
2108
2109struct ByteRangeLockPB2
2110{
2111 unsigned long long offset; /* offset to first byte to lock */
2112 unsigned long long length; /* nbr of bytes to lock */
2113 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2114 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2115 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2116 int fd; /* file desc to assoc this lock with */
2117};
2118
drhfd131da2007-08-07 17:13:03 +00002119#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002120
drh6b9d6dd2008-12-03 19:34:47 +00002121/*
2122** This is a utility for setting or clearing a bit-range lock on an
2123** AFP filesystem.
2124**
2125** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2126*/
2127static int afpSetLock(
2128 const char *path, /* Name of the file to be locked or unlocked */
2129 unixFile *pFile, /* Open file descriptor on path */
2130 unsigned long long offset, /* First byte to be locked */
2131 unsigned long long length, /* Number of bytes to lock */
2132 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002133){
drh6b9d6dd2008-12-03 19:34:47 +00002134 struct ByteRangeLockPB2 pb;
2135 int err;
drhbfe66312006-10-03 17:40:40 +00002136
2137 pb.unLockFlag = setLockFlag ? 0 : 1;
2138 pb.startEndFlag = 0;
2139 pb.offset = offset;
2140 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002141 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002142
drh308c2a52010-05-14 11:30:18 +00002143 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002144 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002145 offset, length));
drhbfe66312006-10-03 17:40:40 +00002146 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2147 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002148 int rc;
2149 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002150 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2151 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002152#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2153 rc = SQLITE_BUSY;
2154#else
drh734c9862008-11-28 15:37:20 +00002155 rc = sqliteErrorFromPosixError(tErrno,
2156 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002157#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002158 if( IS_LOCK_ERROR(rc) ){
2159 pFile->lastErrno = tErrno;
2160 }
2161 return rc;
drhbfe66312006-10-03 17:40:40 +00002162 } else {
aswift5b1a2562008-08-22 00:22:35 +00002163 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002164 }
2165}
2166
drh6b9d6dd2008-12-03 19:34:47 +00002167/*
2168** This routine checks if there is a RESERVED lock held on the specified
2169** file by this or any other process. If such a lock is held, set *pResOut
2170** to a non-zero value otherwise *pResOut is set to zero. The return value
2171** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2172*/
danielk1977e339d652008-06-28 11:23:00 +00002173static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002174 int rc = SQLITE_OK;
2175 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002176 unixFile *pFile = (unixFile*)id;
2177
aswift5b1a2562008-08-22 00:22:35 +00002178 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2179
2180 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002181 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002182 if( context->reserved ){
2183 *pResOut = 1;
2184 return SQLITE_OK;
2185 }
drh8af6c222010-05-14 12:43:01 +00002186 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002187
2188 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002189 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002190 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002191 }
2192
2193 /* Otherwise see if some other process holds it.
2194 */
aswift5b1a2562008-08-22 00:22:35 +00002195 if( !reserved ){
2196 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002197 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002198 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002199 /* if we succeeded in taking the reserved lock, unlock it to restore
2200 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002201 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002202 } else {
2203 /* if we failed to get the lock then someone else must have it */
2204 reserved = 1;
2205 }
2206 if( IS_LOCK_ERROR(lrc) ){
2207 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002208 }
2209 }
drhbfe66312006-10-03 17:40:40 +00002210
drh7ed97b92010-01-20 13:07:21 +00002211 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002212 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002213
2214 *pResOut = reserved;
2215 return rc;
drhbfe66312006-10-03 17:40:40 +00002216}
2217
drh6b9d6dd2008-12-03 19:34:47 +00002218/*
drh308c2a52010-05-14 11:30:18 +00002219** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002220** of the following:
2221**
2222** (1) SHARED_LOCK
2223** (2) RESERVED_LOCK
2224** (3) PENDING_LOCK
2225** (4) EXCLUSIVE_LOCK
2226**
2227** Sometimes when requesting one lock state, additional lock states
2228** are inserted in between. The locking might fail on one of the later
2229** transitions leaving the lock state different from what it started but
2230** still short of its goal. The following chart shows the allowed
2231** transitions and the inserted intermediate states:
2232**
2233** UNLOCKED -> SHARED
2234** SHARED -> RESERVED
2235** SHARED -> (PENDING) -> EXCLUSIVE
2236** RESERVED -> (PENDING) -> EXCLUSIVE
2237** PENDING -> EXCLUSIVE
2238**
2239** This routine will only increase a lock. Use the sqlite3OsUnlock()
2240** routine to lower a locking level.
2241*/
drh308c2a52010-05-14 11:30:18 +00002242static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002243 int rc = SQLITE_OK;
2244 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002245 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002246 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002247
2248 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002249 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2250 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002251 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002252
drhbfe66312006-10-03 17:40:40 +00002253 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002254 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002255 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002256 */
drh308c2a52010-05-14 11:30:18 +00002257 if( pFile->eFileLock>=eFileLock ){
2258 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2259 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002260 return SQLITE_OK;
2261 }
2262
2263 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002264 ** (1) We never move from unlocked to anything higher than shared lock.
2265 ** (2) SQLite never explicitly requests a pendig lock.
2266 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002267 */
drh308c2a52010-05-14 11:30:18 +00002268 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2269 assert( eFileLock!=PENDING_LOCK );
2270 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002271
drh8af6c222010-05-14 12:43:01 +00002272 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002273 */
drh6c7d5c52008-11-21 20:32:33 +00002274 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002275 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002276
2277 /* If some thread using this PID has a lock via a different unixFile*
2278 ** handle that precludes the requested lock, return BUSY.
2279 */
drh8af6c222010-05-14 12:43:01 +00002280 if( (pFile->eFileLock!=pInode->eFileLock &&
2281 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002282 ){
2283 rc = SQLITE_BUSY;
2284 goto afp_end_lock;
2285 }
2286
2287 /* If a SHARED lock is requested, and some thread using this PID already
2288 ** has a SHARED or RESERVED lock, then increment reference counts and
2289 ** return SQLITE_OK.
2290 */
drh308c2a52010-05-14 11:30:18 +00002291 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002292 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002293 assert( eFileLock==SHARED_LOCK );
2294 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002295 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002296 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002297 pInode->nShared++;
2298 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002299 goto afp_end_lock;
2300 }
drhbfe66312006-10-03 17:40:40 +00002301
2302 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002303 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2304 ** be released.
2305 */
drh308c2a52010-05-14 11:30:18 +00002306 if( eFileLock==SHARED_LOCK
2307 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002308 ){
2309 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002310 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002311 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002312 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002313 goto afp_end_lock;
2314 }
2315 }
2316
2317 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002318 ** operating system calls for the specified lock.
2319 */
drh308c2a52010-05-14 11:30:18 +00002320 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002321 int lrc1, lrc2, lrc1Errno;
2322 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002323
drh8af6c222010-05-14 12:43:01 +00002324 assert( pInode->nShared==0 );
2325 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002326
2327 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002328 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002329 /* note that the quality of the randomness doesn't matter that much */
2330 lk = random();
drh8af6c222010-05-14 12:43:01 +00002331 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002332 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002333 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002334 if( IS_LOCK_ERROR(lrc1) ){
2335 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002336 }
aswift5b1a2562008-08-22 00:22:35 +00002337 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002338 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002339
aswift5b1a2562008-08-22 00:22:35 +00002340 if( IS_LOCK_ERROR(lrc1) ) {
2341 pFile->lastErrno = lrc1Errno;
2342 rc = lrc1;
2343 goto afp_end_lock;
2344 } else if( IS_LOCK_ERROR(lrc2) ){
2345 rc = lrc2;
2346 goto afp_end_lock;
2347 } else if( lrc1 != SQLITE_OK ) {
2348 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002349 } else {
drh308c2a52010-05-14 11:30:18 +00002350 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002351 pInode->nLock++;
2352 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002353 }
drh8af6c222010-05-14 12:43:01 +00002354 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002355 /* We are trying for an exclusive lock but another thread in this
2356 ** same process is still holding a shared lock. */
2357 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002358 }else{
2359 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2360 ** assumed that there is a SHARED or greater lock on the file
2361 ** already.
2362 */
2363 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002364 assert( 0!=pFile->eFileLock );
2365 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002366 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002367 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002368 if( !failed ){
2369 context->reserved = 1;
2370 }
drhbfe66312006-10-03 17:40:40 +00002371 }
drh308c2a52010-05-14 11:30:18 +00002372 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002373 /* Acquire an EXCLUSIVE lock */
2374
2375 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002376 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002377 */
drh6b9d6dd2008-12-03 19:34:47 +00002378 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002379 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002380 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002381 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002382 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002383 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002384 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002385 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002386 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2387 ** a critical I/O error
2388 */
2389 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2390 SQLITE_IOERR_LOCK;
2391 goto afp_end_lock;
2392 }
2393 }else{
aswift5b1a2562008-08-22 00:22:35 +00002394 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002395 }
2396 }
aswift5b1a2562008-08-22 00:22:35 +00002397 if( failed ){
2398 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002399 }
2400 }
2401
2402 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002403 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002404 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002405 }else if( eFileLock==EXCLUSIVE_LOCK ){
2406 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002407 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002408 }
2409
2410afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002411 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002412 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2413 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002414 return rc;
2415}
2416
2417/*
drh308c2a52010-05-14 11:30:18 +00002418** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002419** must be either NO_LOCK or SHARED_LOCK.
2420**
2421** If the locking level of the file descriptor is already at or below
2422** the requested locking level, this routine is a no-op.
2423*/
drh308c2a52010-05-14 11:30:18 +00002424static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002425 int rc = SQLITE_OK;
2426 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002427 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002428 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2429 int skipShared = 0;
2430#ifdef SQLITE_TEST
2431 int h = pFile->h;
2432#endif
drhbfe66312006-10-03 17:40:40 +00002433
2434 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002435 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002436 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002437 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002438
drh308c2a52010-05-14 11:30:18 +00002439 assert( eFileLock<=SHARED_LOCK );
2440 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002441 return SQLITE_OK;
2442 }
drh6c7d5c52008-11-21 20:32:33 +00002443 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002444 pInode = pFile->pInode;
2445 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002446 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002447 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002448 SimulateIOErrorBenign(1);
2449 SimulateIOError( h=(-1) )
2450 SimulateIOErrorBenign(0);
2451
2452#ifndef NDEBUG
2453 /* When reducing a lock such that other processes can start
2454 ** reading the database file again, make sure that the
2455 ** transaction counter was updated if any part of the database
2456 ** file changed. If the transaction counter is not updated,
2457 ** other connections to the same file might not realize that
2458 ** the file has changed and hence might not know to flush their
2459 ** cache. The use of a stale cache can lead to database corruption.
2460 */
2461 assert( pFile->inNormalWrite==0
2462 || pFile->dbUpdate==0
2463 || pFile->transCntrChng==1 );
2464 pFile->inNormalWrite = 0;
2465#endif
aswiftaebf4132008-11-21 00:10:35 +00002466
drh308c2a52010-05-14 11:30:18 +00002467 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002468 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002469 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002470 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002471 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002472 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2473 } else {
2474 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002475 }
2476 }
drh308c2a52010-05-14 11:30:18 +00002477 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002478 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002479 }
drh308c2a52010-05-14 11:30:18 +00002480 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002481 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2482 if( !rc ){
2483 context->reserved = 0;
2484 }
aswiftaebf4132008-11-21 00:10:35 +00002485 }
drh8af6c222010-05-14 12:43:01 +00002486 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2487 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002488 }
aswiftaebf4132008-11-21 00:10:35 +00002489 }
drh308c2a52010-05-14 11:30:18 +00002490 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002491
drh7ed97b92010-01-20 13:07:21 +00002492 /* Decrement the shared lock counter. Release the lock using an
2493 ** OS call only when all threads in this same process have released
2494 ** the lock.
2495 */
drh8af6c222010-05-14 12:43:01 +00002496 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2497 pInode->nShared--;
2498 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002499 SimulateIOErrorBenign(1);
2500 SimulateIOError( h=(-1) )
2501 SimulateIOErrorBenign(0);
2502 if( !skipShared ){
2503 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2504 }
2505 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002506 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002507 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002508 }
2509 }
2510 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002511 pInode->nLock--;
2512 assert( pInode->nLock>=0 );
2513 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002514 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002515 }
2516 }
drhbfe66312006-10-03 17:40:40 +00002517 }
drh7ed97b92010-01-20 13:07:21 +00002518
drh6c7d5c52008-11-21 20:32:33 +00002519 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002520 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002521 return rc;
2522}
2523
2524/*
drh339eb0b2008-03-07 15:34:11 +00002525** Close a file & cleanup AFP specific locking context
2526*/
danielk1977e339d652008-06-28 11:23:00 +00002527static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002528 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002529 if( id ){
2530 unixFile *pFile = (unixFile*)id;
2531 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002532 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002533 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002534 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002535 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002536 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002537 ** the last lock is cleared.
2538 */
dan08da86a2009-08-21 17:18:03 +00002539 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002540 }
danb0ac3e32010-06-16 10:55:42 +00002541 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002542 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002543 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002544 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002545 }
drh7ed97b92010-01-20 13:07:21 +00002546 return rc;
drhbfe66312006-10-03 17:40:40 +00002547}
2548
drhd2cb50b2009-01-09 21:41:17 +00002549#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002550/*
2551** The code above is the AFP lock implementation. The code is specific
2552** to MacOSX and does not work on other unix platforms. No alternative
2553** is available. If you don't compile for a mac, then the "unix-afp"
2554** VFS is not available.
2555**
2556********************* End of the AFP lock implementation **********************
2557******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002558
drh7ed97b92010-01-20 13:07:21 +00002559/******************************************************************************
2560*************************** Begin NFS Locking ********************************/
2561
2562#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2563/*
drh308c2a52010-05-14 11:30:18 +00002564 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002565 ** must be either NO_LOCK or SHARED_LOCK.
2566 **
2567 ** If the locking level of the file descriptor is already at or below
2568 ** the requested locking level, this routine is a no-op.
2569 */
drh308c2a52010-05-14 11:30:18 +00002570static int nfsUnlock(sqlite3_file *id, int eFileLock){
2571 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002572}
2573
2574#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2575/*
2576** The code above is the NFS lock implementation. The code is specific
2577** to MacOSX and does not work on other unix platforms. No alternative
2578** is available.
2579**
2580********************* End of the NFS lock implementation **********************
2581******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002582
2583/******************************************************************************
2584**************** Non-locking sqlite3_file methods *****************************
2585**
2586** The next division contains implementations for all methods of the
2587** sqlite3_file object other than the locking methods. The locking
2588** methods were defined in divisions above (one locking method per
2589** division). Those methods that are common to all locking modes
2590** are gather together into this division.
2591*/
drhbfe66312006-10-03 17:40:40 +00002592
2593/*
drh734c9862008-11-28 15:37:20 +00002594** Seek to the offset passed as the second argument, then read cnt
2595** bytes into pBuf. Return the number of bytes actually read.
2596**
2597** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2598** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2599** one system to another. Since SQLite does not define USE_PREAD
2600** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2601** See tickets #2741 and #2681.
2602**
2603** To avoid stomping the errno value on a failed read the lastErrno value
2604** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002605*/
drh734c9862008-11-28 15:37:20 +00002606static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2607 int got;
drh7ed97b92010-01-20 13:07:21 +00002608#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002609 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002610#endif
drh734c9862008-11-28 15:37:20 +00002611 TIMER_START;
2612#if defined(USE_PREAD)
2613 got = pread(id->h, pBuf, cnt, offset);
2614 SimulateIOError( got = -1 );
2615#elif defined(USE_PREAD64)
2616 got = pread64(id->h, pBuf, cnt, offset);
2617 SimulateIOError( got = -1 );
2618#else
2619 newOffset = lseek(id->h, offset, SEEK_SET);
2620 SimulateIOError( newOffset-- );
2621 if( newOffset!=offset ){
2622 if( newOffset == -1 ){
2623 ((unixFile*)id)->lastErrno = errno;
2624 }else{
2625 ((unixFile*)id)->lastErrno = 0;
2626 }
2627 return -1;
2628 }
2629 got = read(id->h, pBuf, cnt);
2630#endif
2631 TIMER_END;
2632 if( got<0 ){
2633 ((unixFile*)id)->lastErrno = errno;
2634 }
drh308c2a52010-05-14 11:30:18 +00002635 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002636 return got;
drhbfe66312006-10-03 17:40:40 +00002637}
2638
2639/*
drh734c9862008-11-28 15:37:20 +00002640** Read data from a file into a buffer. Return SQLITE_OK if all
2641** bytes were read successfully and SQLITE_IOERR if anything goes
2642** wrong.
drh339eb0b2008-03-07 15:34:11 +00002643*/
drh734c9862008-11-28 15:37:20 +00002644static int unixRead(
2645 sqlite3_file *id,
2646 void *pBuf,
2647 int amt,
2648 sqlite3_int64 offset
2649){
dan08da86a2009-08-21 17:18:03 +00002650 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002651 int got;
2652 assert( id );
drh08c6d442009-02-09 17:34:07 +00002653
dan08da86a2009-08-21 17:18:03 +00002654 /* If this is a database file (not a journal, master-journal or temp
2655 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002656#if 0
dane946c392009-08-22 11:39:46 +00002657 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002658 || offset>=PENDING_BYTE+512
2659 || offset+amt<=PENDING_BYTE
2660 );
dan7c246102010-04-12 19:00:29 +00002661#endif
drh08c6d442009-02-09 17:34:07 +00002662
dan08da86a2009-08-21 17:18:03 +00002663 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002664 if( got==amt ){
2665 return SQLITE_OK;
2666 }else if( got<0 ){
2667 /* lastErrno set by seekAndRead */
2668 return SQLITE_IOERR_READ;
2669 }else{
dan08da86a2009-08-21 17:18:03 +00002670 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002671 /* Unread parts of the buffer must be zero-filled */
2672 memset(&((char*)pBuf)[got], 0, amt-got);
2673 return SQLITE_IOERR_SHORT_READ;
2674 }
2675}
2676
2677/*
2678** Seek to the offset in id->offset then read cnt bytes into pBuf.
2679** Return the number of bytes actually read. Update the offset.
2680**
2681** To avoid stomping the errno value on a failed write the lastErrno value
2682** is set before returning.
2683*/
2684static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2685 int got;
drh7ed97b92010-01-20 13:07:21 +00002686#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002687 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002688#endif
drh734c9862008-11-28 15:37:20 +00002689 TIMER_START;
2690#if defined(USE_PREAD)
2691 got = pwrite(id->h, pBuf, cnt, offset);
2692#elif defined(USE_PREAD64)
2693 got = pwrite64(id->h, pBuf, cnt, offset);
2694#else
2695 newOffset = lseek(id->h, offset, SEEK_SET);
2696 if( newOffset!=offset ){
2697 if( newOffset == -1 ){
2698 ((unixFile*)id)->lastErrno = errno;
2699 }else{
2700 ((unixFile*)id)->lastErrno = 0;
2701 }
2702 return -1;
2703 }
2704 got = write(id->h, pBuf, cnt);
2705#endif
2706 TIMER_END;
2707 if( got<0 ){
2708 ((unixFile*)id)->lastErrno = errno;
2709 }
2710
drh308c2a52010-05-14 11:30:18 +00002711 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002712 return got;
2713}
2714
2715
2716/*
2717** Write data from a buffer into a file. Return SQLITE_OK on success
2718** or some other error code on failure.
2719*/
2720static int unixWrite(
2721 sqlite3_file *id,
2722 const void *pBuf,
2723 int amt,
2724 sqlite3_int64 offset
2725){
dan08da86a2009-08-21 17:18:03 +00002726 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002727 int wrote = 0;
2728 assert( id );
2729 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002730
dan08da86a2009-08-21 17:18:03 +00002731 /* If this is a database file (not a journal, master-journal or temp
2732 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002733#if 0
dane946c392009-08-22 11:39:46 +00002734 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002735 || offset>=PENDING_BYTE+512
2736 || offset+amt<=PENDING_BYTE
2737 );
dan7c246102010-04-12 19:00:29 +00002738#endif
drh08c6d442009-02-09 17:34:07 +00002739
drh8f941bc2009-01-14 23:03:40 +00002740#ifndef NDEBUG
2741 /* If we are doing a normal write to a database file (as opposed to
2742 ** doing a hot-journal rollback or a write to some file other than a
2743 ** normal database file) then record the fact that the database
2744 ** has changed. If the transaction counter is modified, record that
2745 ** fact too.
2746 */
dan08da86a2009-08-21 17:18:03 +00002747 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002748 pFile->dbUpdate = 1; /* The database has been modified */
2749 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002750 int rc;
drh8f941bc2009-01-14 23:03:40 +00002751 char oldCntr[4];
2752 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002753 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002754 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002755 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002756 pFile->transCntrChng = 1; /* The transaction counter has changed */
2757 }
2758 }
2759 }
2760#endif
2761
dan08da86a2009-08-21 17:18:03 +00002762 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002763 amt -= wrote;
2764 offset += wrote;
2765 pBuf = &((char*)pBuf)[wrote];
2766 }
2767 SimulateIOError(( wrote=(-1), amt=1 ));
2768 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002769
drh734c9862008-11-28 15:37:20 +00002770 if( amt>0 ){
2771 if( wrote<0 ){
2772 /* lastErrno set by seekAndWrite */
2773 return SQLITE_IOERR_WRITE;
2774 }else{
dan08da86a2009-08-21 17:18:03 +00002775 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002776 return SQLITE_FULL;
2777 }
2778 }
dan6e09d692010-07-27 18:34:15 +00002779
drh734c9862008-11-28 15:37:20 +00002780 return SQLITE_OK;
2781}
2782
2783#ifdef SQLITE_TEST
2784/*
2785** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002786** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002787*/
2788int sqlite3_sync_count = 0;
2789int sqlite3_fullsync_count = 0;
2790#endif
2791
2792/*
drh89240432009-03-25 01:06:01 +00002793** We do not trust systems to provide a working fdatasync(). Some do.
2794** Others do no. To be safe, we will stick with the (slower) fsync().
2795** If you know that your system does support fdatasync() correctly,
2796** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002797*/
drh89240432009-03-25 01:06:01 +00002798#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002799# define fdatasync fsync
2800#endif
2801
2802/*
2803** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2804** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2805** only available on Mac OS X. But that could change.
2806*/
2807#ifdef F_FULLFSYNC
2808# define HAVE_FULLFSYNC 1
2809#else
2810# define HAVE_FULLFSYNC 0
2811#endif
2812
2813
2814/*
2815** The fsync() system call does not work as advertised on many
2816** unix systems. The following procedure is an attempt to make
2817** it work better.
2818**
2819** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2820** for testing when we want to run through the test suite quickly.
2821** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2822** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2823** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002824**
2825** SQLite sets the dataOnly flag if the size of the file is unchanged.
2826** The idea behind dataOnly is that it should only write the file content
2827** to disk, not the inode. We only set dataOnly if the file size is
2828** unchanged since the file size is part of the inode. However,
2829** Ted Ts'o tells us that fdatasync() will also write the inode if the
2830** file size has changed. The only real difference between fdatasync()
2831** and fsync(), Ted tells us, is that fdatasync() will not flush the
2832** inode if the mtime or owner or other inode attributes have changed.
2833** We only care about the file size, not the other file attributes, so
2834** as far as SQLite is concerned, an fdatasync() is always adequate.
2835** So, we always use fdatasync() if it is available, regardless of
2836** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002837*/
2838static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002839 int rc;
drh734c9862008-11-28 15:37:20 +00002840
2841 /* The following "ifdef/elif/else/" block has the same structure as
2842 ** the one below. It is replicated here solely to avoid cluttering
2843 ** up the real code with the UNUSED_PARAMETER() macros.
2844 */
2845#ifdef SQLITE_NO_SYNC
2846 UNUSED_PARAMETER(fd);
2847 UNUSED_PARAMETER(fullSync);
2848 UNUSED_PARAMETER(dataOnly);
2849#elif HAVE_FULLFSYNC
2850 UNUSED_PARAMETER(dataOnly);
2851#else
2852 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002853 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002854#endif
2855
2856 /* Record the number of times that we do a normal fsync() and
2857 ** FULLSYNC. This is used during testing to verify that this procedure
2858 ** gets called with the correct arguments.
2859 */
2860#ifdef SQLITE_TEST
2861 if( fullSync ) sqlite3_fullsync_count++;
2862 sqlite3_sync_count++;
2863#endif
2864
2865 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2866 ** no-op
2867 */
2868#ifdef SQLITE_NO_SYNC
2869 rc = SQLITE_OK;
2870#elif HAVE_FULLFSYNC
2871 if( fullSync ){
2872 rc = fcntl(fd, F_FULLFSYNC, 0);
2873 }else{
2874 rc = 1;
2875 }
2876 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002877 ** It shouldn't be possible for fullfsync to fail on the local
2878 ** file system (on OSX), so failure indicates that FULLFSYNC
2879 ** isn't supported for this file system. So, attempt an fsync
2880 ** and (for now) ignore the overhead of a superfluous fcntl call.
2881 ** It'd be better to detect fullfsync support once and avoid
2882 ** the fcntl call every time sync is called.
2883 */
drh734c9862008-11-28 15:37:20 +00002884 if( rc ) rc = fsync(fd);
2885
drh7ed97b92010-01-20 13:07:21 +00002886#elif defined(__APPLE__)
2887 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2888 ** so currently we default to the macro that redefines fdatasync to fsync
2889 */
2890 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002891#else
drh0b647ff2009-03-21 14:41:04 +00002892 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002893#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002894 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002895 rc = fsync(fd);
2896 }
drh0b647ff2009-03-21 14:41:04 +00002897#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002898#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2899
2900 if( OS_VXWORKS && rc!= -1 ){
2901 rc = 0;
2902 }
chw97185482008-11-17 08:05:31 +00002903 return rc;
drhbfe66312006-10-03 17:40:40 +00002904}
2905
drh734c9862008-11-28 15:37:20 +00002906/*
2907** Make sure all writes to a particular file are committed to disk.
2908**
2909** If dataOnly==0 then both the file itself and its metadata (file
2910** size, access time, etc) are synced. If dataOnly!=0 then only the
2911** file data is synced.
2912**
2913** Under Unix, also make sure that the directory entry for the file
2914** has been created by fsync-ing the directory that contains the file.
2915** If we do not do this and we encounter a power failure, the directory
2916** entry for the journal might not exist after we reboot. The next
2917** SQLite to access the file will not know that the journal exists (because
2918** the directory entry for the journal was never created) and the transaction
2919** will not roll back - possibly leading to database corruption.
2920*/
2921static int unixSync(sqlite3_file *id, int flags){
2922 int rc;
2923 unixFile *pFile = (unixFile*)id;
2924
2925 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2926 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2927
2928 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2929 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2930 || (flags&0x0F)==SQLITE_SYNC_FULL
2931 );
2932
2933 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2934 ** line is to test that doing so does not cause any problems.
2935 */
2936 SimulateDiskfullError( return SQLITE_FULL );
2937
2938 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002939 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00002940 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2941 SimulateIOError( rc=1 );
2942 if( rc ){
2943 pFile->lastErrno = errno;
2944 return SQLITE_IOERR_FSYNC;
2945 }
2946 if( pFile->dirfd>=0 ){
2947 int err;
drh308c2a52010-05-14 11:30:18 +00002948 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2949 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00002950#ifndef SQLITE_DISABLE_DIRSYNC
2951 /* The directory sync is only attempted if full_fsync is
2952 ** turned off or unavailable. If a full_fsync occurred above,
2953 ** then the directory sync is superfluous.
2954 */
2955 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2956 /*
2957 ** We have received multiple reports of fsync() returning
2958 ** errors when applied to directories on certain file systems.
2959 ** A failed directory sync is not a big deal. So it seems
2960 ** better to ignore the error. Ticket #1657
2961 */
2962 /* pFile->lastErrno = errno; */
2963 /* return SQLITE_IOERR; */
2964 }
2965#endif
2966 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2967 if( err==0 ){ /* directory when we are done */
2968 pFile->dirfd = -1;
2969 }else{
2970 pFile->lastErrno = errno;
2971 rc = SQLITE_IOERR_DIR_CLOSE;
2972 }
2973 }
2974 return rc;
2975}
2976
2977/*
2978** Truncate an open file to a specified size
2979*/
2980static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00002981 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002982 int rc;
dan6e09d692010-07-27 18:34:15 +00002983 assert( pFile );
drh734c9862008-11-28 15:37:20 +00002984 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00002985
2986 /* If the user has configured a chunk-size for this file, truncate the
2987 ** file so that it consists of an integer number of chunks (i.e. the
2988 ** actual file size after the operation may be larger than the requested
2989 ** size).
2990 */
2991 if( pFile->szChunk ){
2992 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2993 }
2994
2995 rc = ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00002996 if( rc ){
dan6e09d692010-07-27 18:34:15 +00002997 pFile->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00002998 return SQLITE_IOERR_TRUNCATE;
2999 }else{
drh3313b142009-11-06 04:13:18 +00003000#ifndef NDEBUG
3001 /* If we are doing a normal write to a database file (as opposed to
3002 ** doing a hot-journal rollback or a write to some file other than a
3003 ** normal database file) and we truncate the file to zero length,
3004 ** that effectively updates the change counter. This might happen
3005 ** when restoring a database using the backup API from a zero-length
3006 ** source.
3007 */
dan6e09d692010-07-27 18:34:15 +00003008 if( pFile->inNormalWrite && nByte==0 ){
3009 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003010 }
3011#endif
3012
drh734c9862008-11-28 15:37:20 +00003013 return SQLITE_OK;
3014 }
3015}
3016
3017/*
3018** Determine the current size of a file in bytes
3019*/
3020static int unixFileSize(sqlite3_file *id, i64 *pSize){
3021 int rc;
3022 struct stat buf;
3023 assert( id );
3024 rc = fstat(((unixFile*)id)->h, &buf);
3025 SimulateIOError( rc=1 );
3026 if( rc!=0 ){
3027 ((unixFile*)id)->lastErrno = errno;
3028 return SQLITE_IOERR_FSTAT;
3029 }
3030 *pSize = buf.st_size;
3031
drh8af6c222010-05-14 12:43:01 +00003032 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003033 ** writes a single byte into that file in order to work around a bug
3034 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3035 ** layers, we need to report this file size as zero even though it is
3036 ** really 1. Ticket #3260.
3037 */
3038 if( *pSize==1 ) *pSize = 0;
3039
3040
3041 return SQLITE_OK;
3042}
3043
drhd2cb50b2009-01-09 21:41:17 +00003044#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003045/*
3046** Handler for proxy-locking file-control verbs. Defined below in the
3047** proxying locking division.
3048*/
3049static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003050#endif
drh715ff302008-12-03 22:32:44 +00003051
dan502019c2010-07-28 14:26:17 +00003052/*
3053** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3054** file-control operation.
3055**
3056** If the user has configured a chunk-size for this file, it could be
3057** that the file needs to be extended at this point. Otherwise, the
3058** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3059*/
3060static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3061 if( pFile->szChunk ){
3062 i64 nSize; /* Required file size */
3063 struct stat buf; /* Used to hold return values of fstat() */
3064
3065 if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
3066
3067 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3068 if( nSize>(i64)buf.st_size ){
3069#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3070 if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
3071 return SQLITE_IOERR_WRITE;
3072 }
3073#else
3074 /* If the OS does not have posix_fallocate(), fake it. First use
3075 ** ftruncate() to set the file size, then write a single byte to
3076 ** the last byte in each block within the extended region. This
3077 ** is the same technique used by glibc to implement posix_fallocate()
3078 ** on systems that do not have a real fallocate() system call.
3079 */
3080 int nBlk = buf.st_blksize; /* File-system block size */
3081 i64 iWrite; /* Next offset to write to */
3082 int nWrite; /* Return value from seekAndWrite() */
3083
3084 if( ftruncate(pFile->h, nSize) ){
3085 pFile->lastErrno = errno;
3086 return SQLITE_IOERR_TRUNCATE;
3087 }
3088 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3089 do {
3090 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3091 iWrite += nBlk;
3092 } while( nWrite==1 && iWrite<nSize );
3093 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3094#endif
3095 }
3096 }
3097
3098 return SQLITE_OK;
3099}
danielk1977ad94b582007-08-20 06:44:22 +00003100
danielk1977e3026632004-06-22 11:29:02 +00003101/*
drh9e33c2c2007-08-31 18:34:59 +00003102** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003103*/
drhcc6bb3e2007-08-31 16:11:35 +00003104static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003105 switch( op ){
3106 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003107 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003108 return SQLITE_OK;
3109 }
drh7708e972008-11-29 00:56:52 +00003110 case SQLITE_LAST_ERRNO: {
3111 *(int*)pArg = ((unixFile*)id)->lastErrno;
3112 return SQLITE_OK;
3113 }
dan6e09d692010-07-27 18:34:15 +00003114 case SQLITE_FCNTL_CHUNK_SIZE: {
3115 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003116 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003117 }
drh9ff27ec2010-05-19 19:26:05 +00003118 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003119 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003120 }
drh8f941bc2009-01-14 23:03:40 +00003121#ifndef NDEBUG
3122 /* The pager calls this method to signal that it has done
3123 ** a rollback and that the database is therefore unchanged and
3124 ** it hence it is OK for the transaction change counter to be
3125 ** unchanged.
3126 */
3127 case SQLITE_FCNTL_DB_UNCHANGED: {
3128 ((unixFile*)id)->dbUpdate = 0;
3129 return SQLITE_OK;
3130 }
3131#endif
drhd2cb50b2009-01-09 21:41:17 +00003132#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003133 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003134 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003135 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003136 }
drhd2cb50b2009-01-09 21:41:17 +00003137#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003138 case SQLITE_FCNTL_SYNC_OMITTED: {
3139 return SQLITE_OK; /* A no-op */
3140 }
drh9e33c2c2007-08-31 18:34:59 +00003141 }
drh0b52b7d2011-01-26 19:46:22 +00003142 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003143}
3144
3145/*
danielk1977a3d4c882007-03-23 10:08:38 +00003146** Return the sector size in bytes of the underlying block device for
3147** the specified file. This is almost always 512 bytes, but may be
3148** larger for some devices.
3149**
3150** SQLite code assumes this function cannot fail. It also assumes that
3151** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003152** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003153** same for both.
3154*/
danielk1977397d65f2008-11-19 11:35:39 +00003155static int unixSectorSize(sqlite3_file *NotUsed){
3156 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003157 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003158}
3159
danielk197790949c22007-08-17 16:50:38 +00003160/*
danielk1977397d65f2008-11-19 11:35:39 +00003161** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003162*/
danielk1977397d65f2008-11-19 11:35:39 +00003163static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3164 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003165 return 0;
3166}
3167
drhd9e5c4f2010-05-12 18:01:39 +00003168#ifndef SQLITE_OMIT_WAL
3169
3170
3171/*
drhd91c68f2010-05-14 14:52:25 +00003172** Object used to represent an shared memory buffer.
3173**
3174** When multiple threads all reference the same wal-index, each thread
3175** has its own unixShm object, but they all point to a single instance
3176** of this unixShmNode object. In other words, each wal-index is opened
3177** only once per process.
3178**
3179** Each unixShmNode object is connected to a single unixInodeInfo object.
3180** We could coalesce this object into unixInodeInfo, but that would mean
3181** every open file that does not use shared memory (in other words, most
3182** open files) would have to carry around this extra information. So
3183** the unixInodeInfo object contains a pointer to this unixShmNode object
3184** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003185**
3186** unixMutexHeld() must be true when creating or destroying
3187** this object or while reading or writing the following fields:
3188**
3189** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003190**
3191** The following fields are read-only after the object is created:
3192**
3193** fid
3194** zFilename
3195**
drhd91c68f2010-05-14 14:52:25 +00003196** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003197** unixMutexHeld() is true when reading or writing any other field
3198** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003199*/
drhd91c68f2010-05-14 14:52:25 +00003200struct unixShmNode {
3201 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003202 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003203 char *zFilename; /* Name of the mmapped file */
3204 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003205 int szRegion; /* Size of shared-memory regions */
3206 int nRegion; /* Size of array apRegion */
3207 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003208 int nRef; /* Number of unixShm objects pointing to this */
3209 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003210#ifdef SQLITE_DEBUG
3211 u8 exclMask; /* Mask of exclusive locks held */
3212 u8 sharedMask; /* Mask of shared locks held */
3213 u8 nextShmId; /* Next available unixShm.id value */
3214#endif
3215};
3216
3217/*
drhd9e5c4f2010-05-12 18:01:39 +00003218** Structure used internally by this VFS to record the state of an
3219** open shared memory connection.
3220**
drhd91c68f2010-05-14 14:52:25 +00003221** The following fields are initialized when this object is created and
3222** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003223**
drhd91c68f2010-05-14 14:52:25 +00003224** unixShm.pFile
3225** unixShm.id
3226**
3227** All other fields are read/write. The unixShm.pFile->mutex must be held
3228** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003229*/
3230struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003231 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3232 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003233 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003234 u16 sharedMask; /* Mask of shared locks held */
3235 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003236#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003237 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003238#endif
3239};
3240
3241/*
drhd9e5c4f2010-05-12 18:01:39 +00003242** Constants used for locking
3243*/
drhbd9676c2010-06-23 17:58:38 +00003244#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003245#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003246
drhd9e5c4f2010-05-12 18:01:39 +00003247/*
drh73b64e42010-05-30 19:55:15 +00003248** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003249**
3250** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3251** otherwise.
3252*/
3253static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003254 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3255 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003256 int ofst, /* First byte of the locking range */
3257 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003258){
3259 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003260 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003261
drhd91c68f2010-05-14 14:52:25 +00003262 /* Access to the unixShmNode object is serialized by the caller */
3263 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003264
drh73b64e42010-05-30 19:55:15 +00003265 /* Shared locks never span more than one byte */
3266 assert( n==1 || lockType!=F_RDLCK );
3267
3268 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003269 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003270
drhd9e5c4f2010-05-12 18:01:39 +00003271 /* Initialize the locking parameters */
3272 memset(&f, 0, sizeof(f));
3273 f.l_type = lockType;
3274 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003275 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003276 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003277
drh73b64e42010-05-30 19:55:15 +00003278 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003279 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3280
3281 /* Update the global lock state and do debug tracing */
3282#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003283 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003284 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003285 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003286 if( rc==SQLITE_OK ){
3287 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003288 OSTRACE(("unlock %d ok", ofst));
3289 pShmNode->exclMask &= ~mask;
3290 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003291 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003292 OSTRACE(("read-lock %d ok", ofst));
3293 pShmNode->exclMask &= ~mask;
3294 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003295 }else{
3296 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003297 OSTRACE(("write-lock %d ok", ofst));
3298 pShmNode->exclMask |= mask;
3299 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003300 }
3301 }else{
3302 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003303 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003304 }else if( lockType==F_RDLCK ){
3305 OSTRACE(("read-lock failed"));
3306 }else{
3307 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003308 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003309 }
3310 }
drh20e1f082010-05-31 16:10:12 +00003311 OSTRACE((" - afterwards %03x,%03x\n",
3312 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003313 }
drhd9e5c4f2010-05-12 18:01:39 +00003314#endif
3315
3316 return rc;
3317}
3318
drhd9e5c4f2010-05-12 18:01:39 +00003319
3320/*
drhd91c68f2010-05-14 14:52:25 +00003321** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003322**
3323** This is not a VFS shared-memory method; it is a utility function called
3324** by VFS shared-memory methods.
3325*/
drhd91c68f2010-05-14 14:52:25 +00003326static void unixShmPurge(unixFile *pFd){
3327 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003328 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003329 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003330 int i;
drhd91c68f2010-05-14 14:52:25 +00003331 assert( p->pInode==pFd->pInode );
3332 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003333 for(i=0; i<p->nRegion; i++){
3334 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003335 }
dan18801912010-06-14 14:07:50 +00003336 sqlite3_free(p->apRegion);
drhd91c68f2010-05-14 14:52:25 +00003337 if( p->h>=0 ) close(p->h);
3338 p->pInode->pShmNode = 0;
3339 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003340 }
3341}
3342
3343/*
danda9fe0c2010-07-13 18:44:03 +00003344** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003345** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003346**
drh7234c6d2010-06-19 15:10:09 +00003347** The file used to implement shared-memory is in the same directory
3348** as the open database file and has the same name as the open database
3349** file with the "-shm" suffix added. For example, if the database file
3350** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003351** for shared memory will be called "/home/user1/config.db-shm".
3352**
3353** Another approach to is to use files in /dev/shm or /dev/tmp or an
3354** some other tmpfs mount. But if a file in a different directory
3355** from the database file is used, then differing access permissions
3356** or a chroot() might cause two different processes on the same
3357** database to end up using different files for shared memory -
3358** meaning that their memory would not really be shared - resulting
3359** in database corruption. Nevertheless, this tmpfs file usage
3360** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3361** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3362** option results in an incompatible build of SQLite; builds of SQLite
3363** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3364** same database file at the same time, database corruption will likely
3365** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3366** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003367**
3368** When opening a new shared-memory file, if no other instances of that
3369** file are currently open, in this process or in other processes, then
3370** the file must be truncated to zero length or have its header cleared.
3371*/
danda9fe0c2010-07-13 18:44:03 +00003372static int unixOpenSharedMemory(unixFile *pDbFd){
3373 struct unixShm *p = 0; /* The connection to be opened */
3374 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3375 int rc; /* Result code */
3376 unixInodeInfo *pInode; /* The inode of fd */
3377 char *zShmFilename; /* Name of the file used for SHM */
3378 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003379
danda9fe0c2010-07-13 18:44:03 +00003380 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003381 p = sqlite3_malloc( sizeof(*p) );
3382 if( p==0 ) return SQLITE_NOMEM;
3383 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003384 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003385
danda9fe0c2010-07-13 18:44:03 +00003386 /* Check to see if a unixShmNode object already exists. Reuse an existing
3387 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003388 */
3389 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003390 pInode = pDbFd->pInode;
3391 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003392 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003393 struct stat sStat; /* fstat() info for database file */
3394
3395 /* Call fstat() to figure out the permissions on the database file. If
3396 ** a new *-shm file is created, an attempt will be made to create it
3397 ** with the same permissions. The actual permissions the file is created
3398 ** with are subject to the current umask setting.
3399 */
3400 if( fstat(pDbFd->h, &sStat) ){
3401 rc = SQLITE_IOERR_FSTAT;
3402 goto shm_open_err;
3403 }
3404
drha4ced192010-07-15 18:32:40 +00003405#ifdef SQLITE_SHM_DIRECTORY
3406 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3407#else
drh7234c6d2010-06-19 15:10:09 +00003408 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003409#endif
drh7234c6d2010-06-19 15:10:09 +00003410 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003411 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003412 rc = SQLITE_NOMEM;
3413 goto shm_open_err;
3414 }
drhd91c68f2010-05-14 14:52:25 +00003415 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003416 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003417#ifdef SQLITE_SHM_DIRECTORY
3418 sqlite3_snprintf(nShmFilename, zShmFilename,
3419 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3420 (u32)sStat.st_ino, (u32)sStat.st_dev);
3421#else
drh7234c6d2010-06-19 15:10:09 +00003422 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003423#endif
drhd91c68f2010-05-14 14:52:25 +00003424 pShmNode->h = -1;
3425 pDbFd->pInode->pShmNode = pShmNode;
3426 pShmNode->pInode = pDbFd->pInode;
3427 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3428 if( pShmNode->mutex==0 ){
3429 rc = SQLITE_NOMEM;
3430 goto shm_open_err;
3431 }
drhd9e5c4f2010-05-12 18:01:39 +00003432
danddb0ac42010-07-14 14:48:58 +00003433 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003434 if( pShmNode->h<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003435 rc = SQLITE_CANTOPEN_BKPT;
3436 goto shm_open_err;
3437 }
3438
drhd9e5c4f2010-05-12 18:01:39 +00003439 /* Check to see if another process is holding the dead-man switch.
3440 ** If not, truncate the file to zero length.
3441 */
drhd91c68f2010-05-14 14:52:25 +00003442 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003443 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhd91c68f2010-05-14 14:52:25 +00003444 if( ftruncate(pShmNode->h, 0) ){
drhaab4c022010-06-02 14:45:51 +00003445 rc = SQLITE_IOERR_SHMOPEN;
drhd9e5c4f2010-05-12 18:01:39 +00003446 }
3447 }
3448 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003449 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003450 }
3451 if( rc ) goto shm_open_err;
3452 }
3453
drhd91c68f2010-05-14 14:52:25 +00003454 /* Make the new connection a child of the unixShmNode */
3455 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003456#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003457 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003458#endif
drhd91c68f2010-05-14 14:52:25 +00003459 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003460 pDbFd->pShm = p;
3461 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003462
3463 /* The reference count on pShmNode has already been incremented under
3464 ** the cover of the unixEnterMutex() mutex and the pointer from the
3465 ** new (struct unixShm) object to the pShmNode has been set. All that is
3466 ** left to do is to link the new object into the linked list starting
3467 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3468 ** mutex.
3469 */
3470 sqlite3_mutex_enter(pShmNode->mutex);
3471 p->pNext = pShmNode->pFirst;
3472 pShmNode->pFirst = p;
3473 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003474 return SQLITE_OK;
3475
3476 /* Jump here on any error */
3477shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003478 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003479 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003480 unixLeaveMutex();
3481 return rc;
3482}
3483
3484/*
danda9fe0c2010-07-13 18:44:03 +00003485** This function is called to obtain a pointer to region iRegion of the
3486** shared-memory associated with the database file fd. Shared-memory regions
3487** are numbered starting from zero. Each shared-memory region is szRegion
3488** bytes in size.
3489**
3490** If an error occurs, an error code is returned and *pp is set to NULL.
3491**
3492** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3493** region has not been allocated (by any client, including one running in a
3494** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3495** bExtend is non-zero and the requested shared-memory region has not yet
3496** been allocated, it is allocated by this function.
3497**
3498** If the shared-memory region has already been allocated or is allocated by
3499** this call as described above, then it is mapped into this processes
3500** address space (if it is not already), *pp is set to point to the mapped
3501** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003502*/
danda9fe0c2010-07-13 18:44:03 +00003503static int unixShmMap(
3504 sqlite3_file *fd, /* Handle open on database file */
3505 int iRegion, /* Region to retrieve */
3506 int szRegion, /* Size of regions */
3507 int bExtend, /* True to extend file if necessary */
3508 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003509){
danda9fe0c2010-07-13 18:44:03 +00003510 unixFile *pDbFd = (unixFile*)fd;
3511 unixShm *p;
3512 unixShmNode *pShmNode;
3513 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003514
danda9fe0c2010-07-13 18:44:03 +00003515 /* If the shared-memory file has not yet been opened, open it now. */
3516 if( pDbFd->pShm==0 ){
3517 rc = unixOpenSharedMemory(pDbFd);
3518 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003519 }
drhd9e5c4f2010-05-12 18:01:39 +00003520
danda9fe0c2010-07-13 18:44:03 +00003521 p = pDbFd->pShm;
3522 pShmNode = p->pShmNode;
3523 sqlite3_mutex_enter(pShmNode->mutex);
3524 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3525
3526 if( pShmNode->nRegion<=iRegion ){
3527 char **apNew; /* New apRegion[] array */
3528 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3529 struct stat sStat; /* Used by fstat() */
3530
3531 pShmNode->szRegion = szRegion;
3532
3533 /* The requested region is not mapped into this processes address space.
3534 ** Check to see if it has been allocated (i.e. if the wal-index file is
3535 ** large enough to contain the requested region).
3536 */
3537 if( fstat(pShmNode->h, &sStat) ){
3538 rc = SQLITE_IOERR_SHMSIZE;
3539 goto shmpage_out;
3540 }
3541
3542 if( sStat.st_size<nByte ){
3543 /* The requested memory region does not exist. If bExtend is set to
3544 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3545 **
3546 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3547 ** the requested memory region.
3548 */
3549 if( !bExtend ) goto shmpage_out;
3550 if( ftruncate(pShmNode->h, nByte) ){
3551 rc = SQLITE_IOERR_SHMSIZE;
3552 goto shmpage_out;
3553 }
3554 }
3555
3556 /* Map the requested memory region into this processes address space. */
3557 apNew = (char **)sqlite3_realloc(
3558 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3559 );
3560 if( !apNew ){
3561 rc = SQLITE_IOERR_NOMEM;
3562 goto shmpage_out;
3563 }
3564 pShmNode->apRegion = apNew;
3565 while(pShmNode->nRegion<=iRegion){
3566 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003567 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003568 );
3569 if( pMem==MAP_FAILED ){
3570 rc = SQLITE_IOERR;
3571 goto shmpage_out;
3572 }
3573 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3574 pShmNode->nRegion++;
3575 }
3576 }
3577
3578shmpage_out:
3579 if( pShmNode->nRegion>iRegion ){
3580 *pp = pShmNode->apRegion[iRegion];
3581 }else{
3582 *pp = 0;
3583 }
3584 sqlite3_mutex_leave(pShmNode->mutex);
3585 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003586}
3587
3588/*
drhd9e5c4f2010-05-12 18:01:39 +00003589** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003590**
3591** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3592** different here than in posix. In xShmLock(), one can go from unlocked
3593** to shared and back or from unlocked to exclusive and back. But one may
3594** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003595*/
3596static int unixShmLock(
3597 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003598 int ofst, /* First lock to acquire or release */
3599 int n, /* Number of locks to acquire or release */
3600 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003601){
drh73b64e42010-05-30 19:55:15 +00003602 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3603 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3604 unixShm *pX; /* For looping over all siblings */
3605 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3606 int rc = SQLITE_OK; /* Result code */
3607 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003608
drhd91c68f2010-05-14 14:52:25 +00003609 assert( pShmNode==pDbFd->pInode->pShmNode );
3610 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003611 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003612 assert( n>=1 );
3613 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3614 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3615 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3616 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3617 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003618
drhc99597c2010-05-31 01:41:15 +00003619 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003620 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003621 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003622 if( flags & SQLITE_SHM_UNLOCK ){
3623 u16 allMask = 0; /* Mask of locks held by siblings */
3624
3625 /* See if any siblings hold this same lock */
3626 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3627 if( pX==p ) continue;
3628 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3629 allMask |= pX->sharedMask;
3630 }
3631
3632 /* Unlock the system-level locks */
3633 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003634 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003635 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003636 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003637 }
drh73b64e42010-05-30 19:55:15 +00003638
3639 /* Undo the local locks */
3640 if( rc==SQLITE_OK ){
3641 p->exclMask &= ~mask;
3642 p->sharedMask &= ~mask;
3643 }
3644 }else if( flags & SQLITE_SHM_SHARED ){
3645 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3646
3647 /* Find out which shared locks are already held by sibling connections.
3648 ** If any sibling already holds an exclusive lock, go ahead and return
3649 ** SQLITE_BUSY.
3650 */
3651 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003652 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003653 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003654 break;
3655 }
3656 allShared |= pX->sharedMask;
3657 }
3658
3659 /* Get shared locks at the system level, if necessary */
3660 if( rc==SQLITE_OK ){
3661 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003662 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003663 }else{
drh73b64e42010-05-30 19:55:15 +00003664 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003665 }
drhd9e5c4f2010-05-12 18:01:39 +00003666 }
drh73b64e42010-05-30 19:55:15 +00003667
3668 /* Get the local shared locks */
3669 if( rc==SQLITE_OK ){
3670 p->sharedMask |= mask;
3671 }
3672 }else{
3673 /* Make sure no sibling connections hold locks that will block this
3674 ** lock. If any do, return SQLITE_BUSY right away.
3675 */
3676 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003677 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3678 rc = SQLITE_BUSY;
3679 break;
3680 }
3681 }
3682
3683 /* Get the exclusive locks at the system level. Then if successful
3684 ** also mark the local connection as being locked.
3685 */
3686 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003687 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003688 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003689 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003690 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003691 }
drhd9e5c4f2010-05-12 18:01:39 +00003692 }
3693 }
drhd91c68f2010-05-14 14:52:25 +00003694 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003695 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3696 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003697 return rc;
3698}
3699
drh286a2882010-05-20 23:51:06 +00003700/*
3701** Implement a memory barrier or memory fence on shared memory.
3702**
3703** All loads and stores begun before the barrier must complete before
3704** any load or store begun after the barrier.
3705*/
3706static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003707 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003708){
drhff828942010-06-26 21:34:06 +00003709 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003710 unixEnterMutex();
3711 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003712}
3713
dan18801912010-06-14 14:07:50 +00003714/*
danda9fe0c2010-07-13 18:44:03 +00003715** Close a connection to shared-memory. Delete the underlying
3716** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003717**
3718** If there is no shared memory associated with the connection then this
3719** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003720*/
danda9fe0c2010-07-13 18:44:03 +00003721static int unixShmUnmap(
3722 sqlite3_file *fd, /* The underlying database file */
3723 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003724){
danda9fe0c2010-07-13 18:44:03 +00003725 unixShm *p; /* The connection to be closed */
3726 unixShmNode *pShmNode; /* The underlying shared-memory file */
3727 unixShm **pp; /* For looping over sibling connections */
3728 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003729
danda9fe0c2010-07-13 18:44:03 +00003730 pDbFd = (unixFile*)fd;
3731 p = pDbFd->pShm;
3732 if( p==0 ) return SQLITE_OK;
3733 pShmNode = p->pShmNode;
3734
3735 assert( pShmNode==pDbFd->pInode->pShmNode );
3736 assert( pShmNode->pInode==pDbFd->pInode );
3737
3738 /* Remove connection p from the set of connections associated
3739 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003740 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003741 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3742 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003743
danda9fe0c2010-07-13 18:44:03 +00003744 /* Free the connection p */
3745 sqlite3_free(p);
3746 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003747 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003748
3749 /* If pShmNode->nRef has reached 0, then close the underlying
3750 ** shared-memory file, too */
3751 unixEnterMutex();
3752 assert( pShmNode->nRef>0 );
3753 pShmNode->nRef--;
3754 if( pShmNode->nRef==0 ){
3755 if( deleteFlag ) unlink(pShmNode->zFilename);
3756 unixShmPurge(pDbFd);
3757 }
3758 unixLeaveMutex();
3759
3760 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003761}
drh286a2882010-05-20 23:51:06 +00003762
danda9fe0c2010-07-13 18:44:03 +00003763
drhd9e5c4f2010-05-12 18:01:39 +00003764#else
drh6b017cc2010-06-14 18:01:46 +00003765# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003766# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003767# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003768# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003769#endif /* #ifndef SQLITE_OMIT_WAL */
3770
drh734c9862008-11-28 15:37:20 +00003771/*
3772** Here ends the implementation of all sqlite3_file methods.
3773**
3774********************** End sqlite3_file Methods *******************************
3775******************************************************************************/
3776
3777/*
drh6b9d6dd2008-12-03 19:34:47 +00003778** This division contains definitions of sqlite3_io_methods objects that
3779** implement various file locking strategies. It also contains definitions
3780** of "finder" functions. A finder-function is used to locate the appropriate
3781** sqlite3_io_methods object for a particular database file. The pAppData
3782** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3783** the correct finder-function for that VFS.
3784**
3785** Most finder functions return a pointer to a fixed sqlite3_io_methods
3786** object. The only interesting finder-function is autolockIoFinder, which
3787** looks at the filesystem type and tries to guess the best locking
3788** strategy from that.
3789**
drh1875f7a2008-12-08 18:19:17 +00003790** For finder-funtion F, two objects are created:
3791**
3792** (1) The real finder-function named "FImpt()".
3793**
dane946c392009-08-22 11:39:46 +00003794** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003795**
3796**
3797** A pointer to the F pointer is used as the pAppData value for VFS
3798** objects. We have to do this instead of letting pAppData point
3799** directly at the finder-function since C90 rules prevent a void*
3800** from be cast into a function pointer.
3801**
drh6b9d6dd2008-12-03 19:34:47 +00003802**
drh7708e972008-11-29 00:56:52 +00003803** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003804**
drh7708e972008-11-29 00:56:52 +00003805** * A constant sqlite3_io_methods object call METHOD that has locking
3806** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3807**
3808** * An I/O method finder function called FINDER that returns a pointer
3809** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003810*/
drhd9e5c4f2010-05-12 18:01:39 +00003811#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003812static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003813 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003814 CLOSE, /* xClose */ \
3815 unixRead, /* xRead */ \
3816 unixWrite, /* xWrite */ \
3817 unixTruncate, /* xTruncate */ \
3818 unixSync, /* xSync */ \
3819 unixFileSize, /* xFileSize */ \
3820 LOCK, /* xLock */ \
3821 UNLOCK, /* xUnlock */ \
3822 CKLOCK, /* xCheckReservedLock */ \
3823 unixFileControl, /* xFileControl */ \
3824 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003825 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003826 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00003827 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003828 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00003829 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00003830}; \
drh0c2694b2009-09-03 16:23:44 +00003831static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3832 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003833 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003834} \
drh0c2694b2009-09-03 16:23:44 +00003835static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003836 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003837
3838/*
3839** Here are all of the sqlite3_io_methods objects for each of the
3840** locking strategies. Functions that return pointers to these methods
3841** are also created.
3842*/
3843IOMETHODS(
3844 posixIoFinder, /* Finder function name */
3845 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003846 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00003847 unixClose, /* xClose method */
3848 unixLock, /* xLock method */
3849 unixUnlock, /* xUnlock method */
3850 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003851)
drh7708e972008-11-29 00:56:52 +00003852IOMETHODS(
3853 nolockIoFinder, /* Finder function name */
3854 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003855 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003856 nolockClose, /* xClose method */
3857 nolockLock, /* xLock method */
3858 nolockUnlock, /* xUnlock method */
3859 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003860)
drh7708e972008-11-29 00:56:52 +00003861IOMETHODS(
3862 dotlockIoFinder, /* Finder function name */
3863 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003864 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003865 dotlockClose, /* xClose method */
3866 dotlockLock, /* xLock method */
3867 dotlockUnlock, /* xUnlock method */
3868 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003869)
drh7708e972008-11-29 00:56:52 +00003870
chw78a13182009-04-07 05:35:03 +00003871#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003872IOMETHODS(
3873 flockIoFinder, /* Finder function name */
3874 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003875 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003876 flockClose, /* xClose method */
3877 flockLock, /* xLock method */
3878 flockUnlock, /* xUnlock method */
3879 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003880)
drh7708e972008-11-29 00:56:52 +00003881#endif
3882
drh6c7d5c52008-11-21 20:32:33 +00003883#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003884IOMETHODS(
3885 semIoFinder, /* Finder function name */
3886 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003887 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003888 semClose, /* xClose method */
3889 semLock, /* xLock method */
3890 semUnlock, /* xUnlock method */
3891 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003892)
aswiftaebf4132008-11-21 00:10:35 +00003893#endif
drh7708e972008-11-29 00:56:52 +00003894
drhd2cb50b2009-01-09 21:41:17 +00003895#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003896IOMETHODS(
3897 afpIoFinder, /* Finder function name */
3898 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003899 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003900 afpClose, /* xClose method */
3901 afpLock, /* xLock method */
3902 afpUnlock, /* xUnlock method */
3903 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003904)
drh715ff302008-12-03 22:32:44 +00003905#endif
3906
3907/*
3908** The proxy locking method is a "super-method" in the sense that it
3909** opens secondary file descriptors for the conch and lock files and
3910** it uses proxy, dot-file, AFP, and flock() locking methods on those
3911** secondary files. For this reason, the division that implements
3912** proxy locking is located much further down in the file. But we need
3913** to go ahead and define the sqlite3_io_methods and finder function
3914** for proxy locking here. So we forward declare the I/O methods.
3915*/
drhd2cb50b2009-01-09 21:41:17 +00003916#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003917static int proxyClose(sqlite3_file*);
3918static int proxyLock(sqlite3_file*, int);
3919static int proxyUnlock(sqlite3_file*, int);
3920static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003921IOMETHODS(
3922 proxyIoFinder, /* Finder function name */
3923 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003924 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003925 proxyClose, /* xClose method */
3926 proxyLock, /* xLock method */
3927 proxyUnlock, /* xUnlock method */
3928 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003929)
aswiftaebf4132008-11-21 00:10:35 +00003930#endif
drh7708e972008-11-29 00:56:52 +00003931
drh7ed97b92010-01-20 13:07:21 +00003932/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3933#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3934IOMETHODS(
3935 nfsIoFinder, /* Finder function name */
3936 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003937 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00003938 unixClose, /* xClose method */
3939 unixLock, /* xLock method */
3940 nfsUnlock, /* xUnlock method */
3941 unixCheckReservedLock /* xCheckReservedLock method */
3942)
3943#endif
drh7708e972008-11-29 00:56:52 +00003944
drhd2cb50b2009-01-09 21:41:17 +00003945#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003946/*
drh6b9d6dd2008-12-03 19:34:47 +00003947** This "finder" function attempts to determine the best locking strategy
3948** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003949** object that implements that strategy.
3950**
3951** This is for MacOSX only.
3952*/
drh1875f7a2008-12-08 18:19:17 +00003953static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003954 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003955 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003956){
3957 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003958 const char *zFilesystem; /* Filesystem type name */
3959 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003960 } aMap[] = {
3961 { "hfs", &posixIoMethods },
3962 { "ufs", &posixIoMethods },
3963 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003964 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003965 { "webdav", &nolockIoMethods },
3966 { 0, 0 }
3967 };
3968 int i;
3969 struct statfs fsInfo;
3970 struct flock lockInfo;
3971
3972 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003973 /* If filePath==NULL that means we are dealing with a transient file
3974 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003975 return &nolockIoMethods;
3976 }
3977 if( statfs(filePath, &fsInfo) != -1 ){
3978 if( fsInfo.f_flags & MNT_RDONLY ){
3979 return &nolockIoMethods;
3980 }
3981 for(i=0; aMap[i].zFilesystem; i++){
3982 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3983 return aMap[i].pMethods;
3984 }
3985 }
3986 }
3987
3988 /* Default case. Handles, amongst others, "nfs".
3989 ** Test byte-range lock using fcntl(). If the call succeeds,
3990 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003991 */
drh7708e972008-11-29 00:56:52 +00003992 lockInfo.l_len = 1;
3993 lockInfo.l_start = 0;
3994 lockInfo.l_whence = SEEK_SET;
3995 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003996 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003997 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3998 return &nfsIoMethods;
3999 } else {
4000 return &posixIoMethods;
4001 }
drh7708e972008-11-29 00:56:52 +00004002 }else{
4003 return &dotlockIoMethods;
4004 }
4005}
drh0c2694b2009-09-03 16:23:44 +00004006static const sqlite3_io_methods
4007 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004008
drhd2cb50b2009-01-09 21:41:17 +00004009#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004010
chw78a13182009-04-07 05:35:03 +00004011#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4012/*
4013** This "finder" function attempts to determine the best locking strategy
4014** for the database file "filePath". It then returns the sqlite3_io_methods
4015** object that implements that strategy.
4016**
4017** This is for VXWorks only.
4018*/
4019static const sqlite3_io_methods *autolockIoFinderImpl(
4020 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004021 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004022){
4023 struct flock lockInfo;
4024
4025 if( !filePath ){
4026 /* If filePath==NULL that means we are dealing with a transient file
4027 ** that does not need to be locked. */
4028 return &nolockIoMethods;
4029 }
4030
4031 /* Test if fcntl() is supported and use POSIX style locks.
4032 ** Otherwise fall back to the named semaphore method.
4033 */
4034 lockInfo.l_len = 1;
4035 lockInfo.l_start = 0;
4036 lockInfo.l_whence = SEEK_SET;
4037 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004038 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004039 return &posixIoMethods;
4040 }else{
4041 return &semIoMethods;
4042 }
4043}
drh0c2694b2009-09-03 16:23:44 +00004044static const sqlite3_io_methods
4045 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004046
4047#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4048
drh7708e972008-11-29 00:56:52 +00004049/*
4050** An abstract type for a pointer to a IO method finder function:
4051*/
drh0c2694b2009-09-03 16:23:44 +00004052typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004053
aswiftaebf4132008-11-21 00:10:35 +00004054
drh734c9862008-11-28 15:37:20 +00004055/****************************************************************************
4056**************************** sqlite3_vfs methods ****************************
4057**
4058** This division contains the implementation of methods on the
4059** sqlite3_vfs object.
4060*/
4061
danielk1977a3d4c882007-03-23 10:08:38 +00004062/*
danielk1977e339d652008-06-28 11:23:00 +00004063** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004064*/
4065static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004066 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004067 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004068 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004069 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004070 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004071 int noLock, /* Omit locking if true */
4072 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004073){
drh7708e972008-11-29 00:56:52 +00004074 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004075 unixFile *pNew = (unixFile *)pId;
4076 int rc = SQLITE_OK;
4077
drh8af6c222010-05-14 12:43:01 +00004078 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004079
dane946c392009-08-22 11:39:46 +00004080 /* Parameter isDelete is only used on vxworks. Express this explicitly
4081 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004082 */
drh7708e972008-11-29 00:56:52 +00004083 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004084
dan00157392010-10-05 11:33:15 +00004085 /* Usually the path zFilename should not be a relative pathname. The
4086 ** exception is when opening the proxy "conch" file in builds that
4087 ** include the special Apple locking styles.
4088 */
dan00157392010-10-05 11:33:15 +00004089#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004090 assert( zFilename==0 || zFilename[0]=='/'
4091 || pVfs->pAppData==(void*)&autolockIoFinder );
4092#else
4093 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004094#endif
dan00157392010-10-05 11:33:15 +00004095
drh308c2a52010-05-14 11:30:18 +00004096 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004097 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004098 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004099 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004100 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004101
drh6c7d5c52008-11-21 20:32:33 +00004102#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004103 pNew->pId = vxworksFindFileId(zFilename);
4104 if( pNew->pId==0 ){
4105 noLock = 1;
4106 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004107 }
4108#endif
4109
drhda0e7682008-07-30 15:27:54 +00004110 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004111 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004112 }else{
drh0c2694b2009-09-03 16:23:44 +00004113 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004114#if SQLITE_ENABLE_LOCKING_STYLE
4115 /* Cache zFilename in the locking context (AFP and dotlock override) for
4116 ** proxyLock activation is possible (remote proxy is based on db name)
4117 ** zFilename remains valid until file is closed, to support */
4118 pNew->lockingContext = (void*)zFilename;
4119#endif
drhda0e7682008-07-30 15:27:54 +00004120 }
danielk1977e339d652008-06-28 11:23:00 +00004121
drh7ed97b92010-01-20 13:07:21 +00004122 if( pLockingStyle == &posixIoMethods
4123#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4124 || pLockingStyle == &nfsIoMethods
4125#endif
4126 ){
drh7708e972008-11-29 00:56:52 +00004127 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004128 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004129 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004130 /* If an error occured in findInodeInfo(), close the file descriptor
4131 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004132 ** in two scenarios:
4133 **
4134 ** (a) A call to fstat() failed.
4135 ** (b) A malloc failed.
4136 **
4137 ** Scenario (b) may only occur if the process is holding no other
4138 ** file descriptors open on the same file. If there were other file
4139 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004140 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004141 ** handle h - as it is guaranteed that no posix locks will be released
4142 ** by doing so.
4143 **
4144 ** If scenario (a) caused the error then things are not so safe. The
4145 ** implicit assumption here is that if fstat() fails, things are in
4146 ** such bad shape that dropping a lock or two doesn't matter much.
4147 */
4148 close(h);
4149 h = -1;
4150 }
drh7708e972008-11-29 00:56:52 +00004151 unixLeaveMutex();
4152 }
danielk1977e339d652008-06-28 11:23:00 +00004153
drhd2cb50b2009-01-09 21:41:17 +00004154#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004155 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004156 /* AFP locking uses the file path so it needs to be included in
4157 ** the afpLockingContext.
4158 */
4159 afpLockingContext *pCtx;
4160 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4161 if( pCtx==0 ){
4162 rc = SQLITE_NOMEM;
4163 }else{
4164 /* NB: zFilename exists and remains valid until the file is closed
4165 ** according to requirement F11141. So we do not need to make a
4166 ** copy of the filename. */
4167 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004168 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004169 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004170 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004171 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004172 if( rc!=SQLITE_OK ){
4173 sqlite3_free(pNew->lockingContext);
4174 close(h);
4175 h = -1;
4176 }
drh7708e972008-11-29 00:56:52 +00004177 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004178 }
drh7708e972008-11-29 00:56:52 +00004179 }
4180#endif
danielk1977e339d652008-06-28 11:23:00 +00004181
drh7708e972008-11-29 00:56:52 +00004182 else if( pLockingStyle == &dotlockIoMethods ){
4183 /* Dotfile locking uses the file path so it needs to be included in
4184 ** the dotlockLockingContext
4185 */
4186 char *zLockFile;
4187 int nFilename;
drhea678832008-12-10 19:26:22 +00004188 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004189 zLockFile = (char *)sqlite3_malloc(nFilename);
4190 if( zLockFile==0 ){
4191 rc = SQLITE_NOMEM;
4192 }else{
4193 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004194 }
drh7708e972008-11-29 00:56:52 +00004195 pNew->lockingContext = zLockFile;
4196 }
danielk1977e339d652008-06-28 11:23:00 +00004197
drh6c7d5c52008-11-21 20:32:33 +00004198#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004199 else if( pLockingStyle == &semIoMethods ){
4200 /* Named semaphore locking uses the file path so it needs to be
4201 ** included in the semLockingContext
4202 */
4203 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004204 rc = findInodeInfo(pNew, &pNew->pInode);
4205 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4206 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004207 int n;
drh2238dcc2009-08-27 17:56:20 +00004208 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004209 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004210 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004211 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004212 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4213 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004214 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004215 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004216 }
chw97185482008-11-17 08:05:31 +00004217 }
drh7708e972008-11-29 00:56:52 +00004218 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004219 }
drh7708e972008-11-29 00:56:52 +00004220#endif
aswift5b1a2562008-08-22 00:22:35 +00004221
4222 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004223#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004224 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004225 if( h>=0 ) close(h);
4226 h = -1;
chw97185482008-11-17 08:05:31 +00004227 unlink(zFilename);
4228 isDelete = 0;
4229 }
4230 pNew->isDelete = isDelete;
4231#endif
danielk1977e339d652008-06-28 11:23:00 +00004232 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004233 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004234 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004235 }else{
drh7708e972008-11-29 00:56:52 +00004236 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004237 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004238 }
danielk1977e339d652008-06-28 11:23:00 +00004239 return rc;
drh054889e2005-11-30 03:20:31 +00004240}
drh9c06c952005-11-26 00:25:00 +00004241
danielk1977ad94b582007-08-20 06:44:22 +00004242/*
4243** Open a file descriptor to the directory containing file zFilename.
4244** If successful, *pFd is set to the opened file descriptor and
4245** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4246** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4247** value.
4248**
4249** If SQLITE_OK is returned, the caller is responsible for closing
4250** the file descriptor *pFd using close().
4251*/
danielk1977fee2d252007-08-18 10:59:19 +00004252static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004253 int ii;
drh777b17a2007-09-20 10:02:54 +00004254 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004255 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004256
drh153c62c2007-08-24 03:51:33 +00004257 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004258 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004259 if( ii>0 ){
4260 zDirname[ii] = '\0';
4261 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004262 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004263#ifdef FD_CLOEXEC
4264 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4265#endif
drh308c2a52010-05-14 11:30:18 +00004266 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004267 }
4268 }
danielk1977fee2d252007-08-18 10:59:19 +00004269 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004270 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004271}
4272
danielk1977b4b47412007-08-17 15:53:36 +00004273/*
drh8b3cf822010-06-01 21:02:51 +00004274** Return the name of a directory in which to put temporary files.
4275** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004276*/
drh7234c6d2010-06-19 15:10:09 +00004277static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004278 static const char *azDirs[] = {
4279 0,
aswiftaebf4132008-11-21 00:10:35 +00004280 0,
danielk197717b90b52008-06-06 11:11:25 +00004281 "/var/tmp",
4282 "/usr/tmp",
4283 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004284 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004285 };
drh8b3cf822010-06-01 21:02:51 +00004286 unsigned int i;
4287 struct stat buf;
4288 const char *zDir = 0;
4289
4290 azDirs[0] = sqlite3_temp_directory;
4291 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004292 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004293 if( zDir==0 ) continue;
4294 if( stat(zDir, &buf) ) continue;
4295 if( !S_ISDIR(buf.st_mode) ) continue;
drh7234c6d2010-06-19 15:10:09 +00004296 if( access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004297 break;
4298 }
4299 return zDir;
4300}
4301
4302/*
4303** Create a temporary file name in zBuf. zBuf must be allocated
4304** by the calling process and must be big enough to hold at least
4305** pVfs->mxPathname bytes.
4306*/
4307static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004308 static const unsigned char zChars[] =
4309 "abcdefghijklmnopqrstuvwxyz"
4310 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4311 "0123456789";
drh41022642008-11-21 00:24:42 +00004312 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004313 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004314
4315 /* It's odd to simulate an io-error here, but really this is just
4316 ** using the io-error infrastructure to test that SQLite handles this
4317 ** function failing.
4318 */
4319 SimulateIOError( return SQLITE_IOERR );
4320
drh7234c6d2010-06-19 15:10:09 +00004321 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004322 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004323
4324 /* Check that the output buffer is large enough for the temporary file
4325 ** name. If it is not, return SQLITE_ERROR.
4326 */
danielk197700e13612008-11-17 19:18:54 +00004327 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004328 return SQLITE_ERROR;
4329 }
4330
4331 do{
4332 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004333 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004334 sqlite3_randomness(15, &zBuf[j]);
4335 for(i=0; i<15; i++, j++){
4336 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4337 }
4338 zBuf[j] = 0;
4339 }while( access(zBuf,0)==0 );
4340 return SQLITE_OK;
4341}
4342
drhd2cb50b2009-01-09 21:41:17 +00004343#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004344/*
4345** Routine to transform a unixFile into a proxy-locking unixFile.
4346** Implementation in the proxy-lock division, but used by unixOpen()
4347** if SQLITE_PREFER_PROXY_LOCKING is defined.
4348*/
4349static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004350#endif
drhc66d5b62008-12-03 22:48:32 +00004351
dan08da86a2009-08-21 17:18:03 +00004352/*
4353** Search for an unused file descriptor that was opened on the database
4354** file (not a journal or master-journal file) identified by pathname
4355** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4356** argument to this function.
4357**
4358** Such a file descriptor may exist if a database connection was closed
4359** but the associated file descriptor could not be closed because some
4360** other file descriptor open on the same file is holding a file-lock.
4361** Refer to comments in the unixClose() function and the lengthy comment
4362** describing "Posix Advisory Locking" at the start of this file for
4363** further details. Also, ticket #4018.
4364**
4365** If a suitable file descriptor is found, then it is returned. If no
4366** such file descriptor is located, -1 is returned.
4367*/
dane946c392009-08-22 11:39:46 +00004368static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4369 UnixUnusedFd *pUnused = 0;
4370
4371 /* Do not search for an unused file descriptor on vxworks. Not because
4372 ** vxworks would not benefit from the change (it might, we're not sure),
4373 ** but because no way to test it is currently available. It is better
4374 ** not to risk breaking vxworks support for the sake of such an obscure
4375 ** feature. */
4376#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004377 struct stat sStat; /* Results of stat() call */
4378
4379 /* A stat() call may fail for various reasons. If this happens, it is
4380 ** almost certain that an open() call on the same path will also fail.
4381 ** For this reason, if an error occurs in the stat() call here, it is
4382 ** ignored and -1 is returned. The caller will try to open a new file
4383 ** descriptor on the same path, fail, and return an error to SQLite.
4384 **
4385 ** Even if a subsequent open() call does succeed, the consequences of
4386 ** not searching for a resusable file descriptor are not dire. */
4387 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004388 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004389
4390 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004391 pInode = inodeList;
4392 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4393 || pInode->fileId.ino!=sStat.st_ino) ){
4394 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004395 }
drh8af6c222010-05-14 12:43:01 +00004396 if( pInode ){
dane946c392009-08-22 11:39:46 +00004397 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004398 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004399 pUnused = *pp;
4400 if( pUnused ){
4401 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004402 }
4403 }
4404 unixLeaveMutex();
4405 }
dane946c392009-08-22 11:39:46 +00004406#endif /* if !OS_VXWORKS */
4407 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004408}
danielk197717b90b52008-06-06 11:11:25 +00004409
4410/*
danddb0ac42010-07-14 14:48:58 +00004411** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004412** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004413** and a value suitable for passing as the third argument to open(2) is
4414** written to *pMode. If an IO error occurs, an SQLite error code is
4415** returned and the value of *pMode is not modified.
4416**
4417** If the file being opened is a temporary file, it is always created with
4418** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004419** is a database or master journal file, it is created with the permissions
4420** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004421**
drh8ab58662010-07-15 18:38:39 +00004422** Finally, if the file being opened is a WAL or regular journal file, then
4423** this function queries the file-system for the permissions on the
4424** corresponding database file and sets *pMode to this value. Whenever
4425** possible, WAL and journal files are created using the same permissions
4426** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004427*/
4428static int findCreateFileMode(
4429 const char *zPath, /* Path of file (possibly) being created */
4430 int flags, /* Flags passed as 4th argument to xOpen() */
4431 mode_t *pMode /* OUT: Permissions to open file with */
4432){
4433 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004434 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004435 char zDb[MAX_PATHNAME+1]; /* Database file path */
4436 int nDb; /* Number of valid bytes in zDb */
4437 struct stat sStat; /* Output of stat() on database file */
4438
dana0c989d2010-11-05 18:07:37 +00004439 /* zPath is a path to a WAL or journal file. The following block derives
4440 ** the path to the associated database file from zPath. This block handles
4441 ** the following naming conventions:
4442 **
4443 ** "<path to db>-journal"
4444 ** "<path to db>-wal"
4445 ** "<path to db>-journal-NNNN"
4446 ** "<path to db>-wal-NNNN"
4447 **
4448 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4449 ** used by the test_multiplex.c module.
4450 */
4451 nDb = sqlite3Strlen30(zPath) - 1;
4452 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4453 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004454 memcpy(zDb, zPath, nDb);
4455 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004456
danddb0ac42010-07-14 14:48:58 +00004457 if( 0==stat(zDb, &sStat) ){
4458 *pMode = sStat.st_mode & 0777;
4459 }else{
4460 rc = SQLITE_IOERR_FSTAT;
4461 }
4462 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4463 *pMode = 0600;
4464 }else{
4465 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4466 }
4467 return rc;
4468}
4469
4470/*
danielk1977ad94b582007-08-20 06:44:22 +00004471** Open the file zPath.
4472**
danielk1977b4b47412007-08-17 15:53:36 +00004473** Previously, the SQLite OS layer used three functions in place of this
4474** one:
4475**
4476** sqlite3OsOpenReadWrite();
4477** sqlite3OsOpenReadOnly();
4478** sqlite3OsOpenExclusive();
4479**
4480** These calls correspond to the following combinations of flags:
4481**
4482** ReadWrite() -> (READWRITE | CREATE)
4483** ReadOnly() -> (READONLY)
4484** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4485**
4486** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4487** true, the file was configured to be automatically deleted when the
4488** file handle closed. To achieve the same effect using this new
4489** interface, add the DELETEONCLOSE flag to those specified above for
4490** OpenExclusive().
4491*/
4492static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004493 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4494 const char *zPath, /* Pathname of file to be opened */
4495 sqlite3_file *pFile, /* The file descriptor to be filled in */
4496 int flags, /* Input flags to control the opening */
4497 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004498){
dan08da86a2009-08-21 17:18:03 +00004499 unixFile *p = (unixFile *)pFile;
4500 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004501 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004502 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004503 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004504 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004505 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004506
4507 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4508 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4509 int isCreate = (flags & SQLITE_OPEN_CREATE);
4510 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4511 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004512#if SQLITE_ENABLE_LOCKING_STYLE
4513 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4514#endif
danielk1977b4b47412007-08-17 15:53:36 +00004515
danielk1977fee2d252007-08-18 10:59:19 +00004516 /* If creating a master or main-file journal, this function will open
4517 ** a file-descriptor on the directory too. The first time unixSync()
4518 ** is called the directory file descriptor will be fsync()ed and close()d.
4519 */
danddb0ac42010-07-14 14:48:58 +00004520 int isOpenDirectory = (isCreate && (
4521 eType==SQLITE_OPEN_MASTER_JOURNAL
4522 || eType==SQLITE_OPEN_MAIN_JOURNAL
4523 || eType==SQLITE_OPEN_WAL
4524 ));
danielk1977fee2d252007-08-18 10:59:19 +00004525
danielk197717b90b52008-06-06 11:11:25 +00004526 /* If argument zPath is a NULL pointer, this function is required to open
4527 ** a temporary file. Use this buffer to store the file name in.
4528 */
4529 char zTmpname[MAX_PATHNAME+1];
4530 const char *zName = zPath;
4531
danielk1977fee2d252007-08-18 10:59:19 +00004532 /* Check the following statements are true:
4533 **
4534 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4535 ** (b) if CREATE is set, then READWRITE must also be set, and
4536 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004537 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004538 */
danielk1977b4b47412007-08-17 15:53:36 +00004539 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004540 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004541 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004542 assert(isDelete==0 || isCreate);
4543
danddb0ac42010-07-14 14:48:58 +00004544 /* The main DB, main journal, WAL file and master journal are never
4545 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004546 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4547 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4548 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004549 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004550
danielk1977fee2d252007-08-18 10:59:19 +00004551 /* Assert that the upper layer has set one of the "file-type" flags. */
4552 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4553 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4554 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004555 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004556 );
4557
dan08da86a2009-08-21 17:18:03 +00004558 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004559
dan08da86a2009-08-21 17:18:03 +00004560 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004561 UnixUnusedFd *pUnused;
4562 pUnused = findReusableFd(zName, flags);
4563 if( pUnused ){
4564 fd = pUnused->fd;
4565 }else{
dan6aa657f2009-08-24 18:57:58 +00004566 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004567 if( !pUnused ){
4568 return SQLITE_NOMEM;
4569 }
4570 }
4571 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004572 }else if( !zName ){
4573 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004574 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004575 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004576 if( rc!=SQLITE_OK ){
4577 return rc;
4578 }
4579 zName = zTmpname;
4580 }
4581
dan08da86a2009-08-21 17:18:03 +00004582 /* Determine the value of the flags parameter passed to POSIX function
4583 ** open(). These must be calculated even if open() is not called, as
4584 ** they may be stored as part of the file handle and used by the
4585 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004586 if( isReadonly ) openFlags |= O_RDONLY;
4587 if( isReadWrite ) openFlags |= O_RDWR;
4588 if( isCreate ) openFlags |= O_CREAT;
4589 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4590 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004591
danielk1977b4b47412007-08-17 15:53:36 +00004592 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004593 mode_t openMode; /* Permissions to create file with */
4594 rc = findCreateFileMode(zName, flags, &openMode);
4595 if( rc!=SQLITE_OK ){
4596 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004597 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004598 return rc;
4599 }
dane946c392009-08-22 11:39:46 +00004600 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004601 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004602 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4603 /* Failed to open the file for read/write access. Try read-only. */
4604 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004605 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004606 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004607 openFlags |= O_RDONLY;
4608 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004609 }
4610 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004611 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004612 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004613 }
danielk1977b4b47412007-08-17 15:53:36 +00004614 }
dan08da86a2009-08-21 17:18:03 +00004615 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004616 if( pOutFlags ){
4617 *pOutFlags = flags;
4618 }
4619
dane946c392009-08-22 11:39:46 +00004620 if( p->pUnused ){
4621 p->pUnused->fd = fd;
4622 p->pUnused->flags = flags;
4623 }
4624
danielk1977b4b47412007-08-17 15:53:36 +00004625 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004626#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004627 zPath = zName;
4628#else
danielk197717b90b52008-06-06 11:11:25 +00004629 unlink(zName);
chw97185482008-11-17 08:05:31 +00004630#endif
danielk1977b4b47412007-08-17 15:53:36 +00004631 }
drh41022642008-11-21 00:24:42 +00004632#if SQLITE_ENABLE_LOCKING_STYLE
4633 else{
dan08da86a2009-08-21 17:18:03 +00004634 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004635 }
4636#endif
4637
danielk1977fee2d252007-08-18 10:59:19 +00004638 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004639 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004640 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004641 /* It is safe to close fd at this point, because it is guaranteed not
4642 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004643 ** it would not be safe to close as this would release any locks held
4644 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004645 assert( eType!=SQLITE_OPEN_MAIN_DB );
4646 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004647 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004648 }
4649 }
danielk1977e339d652008-06-28 11:23:00 +00004650
4651#ifdef FD_CLOEXEC
4652 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4653#endif
4654
drhda0e7682008-07-30 15:27:54 +00004655 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004656
drh7ed97b92010-01-20 13:07:21 +00004657
4658#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4659 struct statfs fsInfo;
4660 if( fstatfs(fd, &fsInfo) == -1 ){
4661 ((unixFile*)pFile)->lastErrno = errno;
4662 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4663 close(fd); /* silently leak if fail, in error */
4664 return SQLITE_IOERR_ACCESS;
4665 }
4666 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4667 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4668 }
4669#endif
4670
4671#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004672#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004673 isAutoProxy = 1;
4674#endif
4675 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004676 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4677 int useProxy = 0;
4678
dan08da86a2009-08-21 17:18:03 +00004679 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4680 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004681 if( envforce!=NULL ){
4682 useProxy = atoi(envforce)>0;
4683 }else{
4684 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004685 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004686 /* In theory, the close(fd) call is sub-optimal. If the file opened
4687 ** with fd is a database file, and there are other connections open
4688 ** on that file that are currently holding advisory locks on it,
4689 ** then the call to close() will cancel those locks. In practice,
4690 ** we're assuming that statfs() doesn't fail very often. At least
4691 ** not while other file descriptors opened by the same process on
4692 ** the same file are working. */
4693 p->lastErrno = errno;
4694 if( dirfd>=0 ){
4695 close(dirfd); /* silently leak if fail, in error */
4696 }
aswiftaebf4132008-11-21 00:10:35 +00004697 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004698 rc = SQLITE_IOERR_ACCESS;
4699 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004700 }
4701 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4702 }
4703 if( useProxy ){
4704 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4705 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004706 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004707 if( rc!=SQLITE_OK ){
4708 /* Use unixClose to clean up the resources added in fillInUnixFile
4709 ** and clear all the structure's references. Specifically,
4710 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4711 */
4712 unixClose(pFile);
4713 return rc;
4714 }
aswiftaebf4132008-11-21 00:10:35 +00004715 }
dane946c392009-08-22 11:39:46 +00004716 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004717 }
4718 }
4719#endif
4720
dane946c392009-08-22 11:39:46 +00004721 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4722open_finished:
4723 if( rc!=SQLITE_OK ){
4724 sqlite3_free(p->pUnused);
4725 }
4726 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004727}
4728
dane946c392009-08-22 11:39:46 +00004729
danielk1977b4b47412007-08-17 15:53:36 +00004730/*
danielk1977fee2d252007-08-18 10:59:19 +00004731** Delete the file at zPath. If the dirSync argument is true, fsync()
4732** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004733*/
drh6b9d6dd2008-12-03 19:34:47 +00004734static int unixDelete(
4735 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4736 const char *zPath, /* Name of file to be deleted */
4737 int dirSync /* If true, fsync() directory after deleting file */
4738){
danielk1977fee2d252007-08-18 10:59:19 +00004739 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004740 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004741 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004742 if( unlink(zPath)==(-1) && errno!=ENOENT ){
4743 return SQLITE_IOERR_DELETE;
4744 }
danielk1977d39fa702008-10-16 13:27:40 +00004745#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004746 if( dirSync ){
4747 int fd;
4748 rc = openDirectory(zPath, &fd);
4749 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004750#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004751 if( fsync(fd)==-1 )
4752#else
4753 if( fsync(fd) )
4754#endif
4755 {
danielk1977fee2d252007-08-18 10:59:19 +00004756 rc = SQLITE_IOERR_DIR_FSYNC;
4757 }
aswiftaebf4132008-11-21 00:10:35 +00004758 if( close(fd)&&!rc ){
4759 rc = SQLITE_IOERR_DIR_CLOSE;
4760 }
danielk1977fee2d252007-08-18 10:59:19 +00004761 }
4762 }
danielk1977d138dd82008-10-15 16:02:48 +00004763#endif
danielk1977fee2d252007-08-18 10:59:19 +00004764 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004765}
4766
danielk197790949c22007-08-17 16:50:38 +00004767/*
4768** Test the existance of or access permissions of file zPath. The
4769** test performed depends on the value of flags:
4770**
4771** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4772** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4773** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4774**
4775** Otherwise return 0.
4776*/
danielk1977861f7452008-06-05 11:39:11 +00004777static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004778 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4779 const char *zPath, /* Path of the file to examine */
4780 int flags, /* What do we want to learn about the zPath file? */
4781 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004782){
rse25c0d1a2007-09-20 08:38:14 +00004783 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004784 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004785 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004786 switch( flags ){
4787 case SQLITE_ACCESS_EXISTS:
4788 amode = F_OK;
4789 break;
4790 case SQLITE_ACCESS_READWRITE:
4791 amode = W_OK|R_OK;
4792 break;
drh50d3f902007-08-27 21:10:36 +00004793 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004794 amode = R_OK;
4795 break;
4796
4797 default:
4798 assert(!"Invalid flags argument");
4799 }
danielk1977861f7452008-06-05 11:39:11 +00004800 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004801 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4802 struct stat buf;
4803 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4804 *pResOut = 0;
4805 }
4806 }
danielk1977861f7452008-06-05 11:39:11 +00004807 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004808}
4809
danielk1977b4b47412007-08-17 15:53:36 +00004810
4811/*
4812** Turn a relative pathname into a full pathname. The relative path
4813** is stored as a nul-terminated string in the buffer pointed to by
4814** zPath.
4815**
4816** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4817** (in this case, MAX_PATHNAME bytes). The full-path is written to
4818** this buffer before returning.
4819*/
danielk1977adfb9b02007-09-17 07:02:56 +00004820static int unixFullPathname(
4821 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4822 const char *zPath, /* Possibly relative input path */
4823 int nOut, /* Size of output buffer in bytes */
4824 char *zOut /* Output buffer */
4825){
danielk1977843e65f2007-09-01 16:16:15 +00004826
4827 /* It's odd to simulate an io-error here, but really this is just
4828 ** using the io-error infrastructure to test that SQLite handles this
4829 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004830 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004831 */
4832 SimulateIOError( return SQLITE_ERROR );
4833
drh153c62c2007-08-24 03:51:33 +00004834 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004835 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004836
drh3c7f2dc2007-12-06 13:26:20 +00004837 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004838 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004839 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004840 }else{
4841 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004842 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004843 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004844 }
drhea678832008-12-10 19:26:22 +00004845 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004846 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004847 }
4848 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004849}
4850
drh0ccebe72005-06-07 22:22:50 +00004851
drh761df872006-12-21 01:29:22 +00004852#ifndef SQLITE_OMIT_LOAD_EXTENSION
4853/*
4854** Interfaces for opening a shared library, finding entry points
4855** within the shared library, and closing the shared library.
4856*/
4857#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004858static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4859 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004860 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4861}
danielk197795c8a542007-09-01 06:51:27 +00004862
4863/*
4864** SQLite calls this function immediately after a call to unixDlSym() or
4865** unixDlOpen() fails (returns a null pointer). If a more detailed error
4866** message is available, it is written to zBufOut. If no error message
4867** is available, zBufOut is left unmodified and SQLite uses a default
4868** error message.
4869*/
danielk1977397d65f2008-11-19 11:35:39 +00004870static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00004871 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004872 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004873 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004874 zErr = dlerror();
4875 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004876 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004877 }
drh6c7d5c52008-11-21 20:32:33 +00004878 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004879}
drh1875f7a2008-12-08 18:19:17 +00004880static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4881 /*
4882 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4883 ** cast into a pointer to a function. And yet the library dlsym() routine
4884 ** returns a void* which is really a pointer to a function. So how do we
4885 ** use dlsym() with -pedantic-errors?
4886 **
4887 ** Variable x below is defined to be a pointer to a function taking
4888 ** parameters void* and const char* and returning a pointer to a function.
4889 ** We initialize x by assigning it a pointer to the dlsym() function.
4890 ** (That assignment requires a cast.) Then we call the function that
4891 ** x points to.
4892 **
4893 ** This work-around is unlikely to work correctly on any system where
4894 ** you really cannot cast a function pointer into void*. But then, on the
4895 ** other hand, dlsym() will not work on such a system either, so we have
4896 ** not really lost anything.
4897 */
4898 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004899 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004900 x = (void(*(*)(void*,const char*))(void))dlsym;
4901 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004902}
danielk1977397d65f2008-11-19 11:35:39 +00004903static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4904 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004905 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004906}
danielk1977b4b47412007-08-17 15:53:36 +00004907#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4908 #define unixDlOpen 0
4909 #define unixDlError 0
4910 #define unixDlSym 0
4911 #define unixDlClose 0
4912#endif
4913
4914/*
danielk197790949c22007-08-17 16:50:38 +00004915** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004916*/
danielk1977397d65f2008-11-19 11:35:39 +00004917static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4918 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004919 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004920
drhbbd42a62004-05-22 17:41:58 +00004921 /* We have to initialize zBuf to prevent valgrind from reporting
4922 ** errors. The reports issued by valgrind are incorrect - we would
4923 ** prefer that the randomness be increased by making use of the
4924 ** uninitialized space in zBuf - but valgrind errors tend to worry
4925 ** some users. Rather than argue, it seems easier just to initialize
4926 ** the whole array and silence valgrind, even if that means less randomness
4927 ** in the random seed.
4928 **
4929 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004930 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004931 ** tests repeatable.
4932 */
danielk1977b4b47412007-08-17 15:53:36 +00004933 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004934#if !defined(SQLITE_TEST)
4935 {
drh842b8642005-01-21 17:53:17 +00004936 int pid, fd;
4937 fd = open("/dev/urandom", O_RDONLY);
4938 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004939 time_t t;
4940 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004941 memcpy(zBuf, &t, sizeof(t));
4942 pid = getpid();
4943 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004944 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004945 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004946 }else{
drh72cbd072008-10-14 17:58:38 +00004947 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004948 close(fd);
4949 }
drhbbd42a62004-05-22 17:41:58 +00004950 }
4951#endif
drh72cbd072008-10-14 17:58:38 +00004952 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004953}
4954
danielk1977b4b47412007-08-17 15:53:36 +00004955
drhbbd42a62004-05-22 17:41:58 +00004956/*
4957** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004958** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004959** The return value is the number of microseconds of sleep actually
4960** requested from the underlying operating system, a number which
4961** might be greater than or equal to the argument, but not less
4962** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004963*/
danielk1977397d65f2008-11-19 11:35:39 +00004964static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004965#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004966 struct timespec sp;
4967
4968 sp.tv_sec = microseconds / 1000000;
4969 sp.tv_nsec = (microseconds % 1000000) * 1000;
4970 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004971 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004972 return microseconds;
4973#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004974 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004975 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004976 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004977#else
danielk1977b4b47412007-08-17 15:53:36 +00004978 int seconds = (microseconds+999999)/1000000;
4979 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004980 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004981 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004982#endif
drh88f474a2006-01-02 20:00:12 +00004983}
4984
4985/*
drh6b9d6dd2008-12-03 19:34:47 +00004986** The following variable, if set to a non-zero value, is interpreted as
4987** the number of seconds since 1970 and is used to set the result of
4988** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004989*/
4990#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004991int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004992#endif
4993
4994/*
drhb7e8ea22010-05-03 14:32:30 +00004995** Find the current time (in Universal Coordinated Time). Write into *piNow
4996** the current time and date as a Julian Day number times 86_400_000. In
4997** other words, write into *piNow the number of milliseconds since the Julian
4998** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4999** proleptic Gregorian calendar.
5000**
5001** On success, return 0. Return 1 if the time and date cannot be found.
5002*/
5003static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5004 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5005#if defined(NO_GETTOD)
5006 time_t t;
5007 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005008 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005009#elif OS_VXWORKS
5010 struct timespec sNow;
5011 clock_gettime(CLOCK_REALTIME, &sNow);
5012 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5013#else
5014 struct timeval sNow;
5015 gettimeofday(&sNow, 0);
5016 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5017#endif
5018
5019#ifdef SQLITE_TEST
5020 if( sqlite3_current_time ){
5021 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5022 }
5023#endif
5024 UNUSED_PARAMETER(NotUsed);
5025 return 0;
5026}
5027
5028/*
drhbbd42a62004-05-22 17:41:58 +00005029** Find the current time (in Universal Coordinated Time). Write the
5030** current time and date as a Julian Day number into *prNow and
5031** return 0. Return 1 if the time and date cannot be found.
5032*/
danielk1977397d65f2008-11-19 11:35:39 +00005033static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005034 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005035 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005036 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005037 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005038 return 0;
5039}
danielk1977b4b47412007-08-17 15:53:36 +00005040
drh6b9d6dd2008-12-03 19:34:47 +00005041/*
5042** We added the xGetLastError() method with the intention of providing
5043** better low-level error messages when operating-system problems come up
5044** during SQLite operation. But so far, none of that has been implemented
5045** in the core. So this routine is never called. For now, it is merely
5046** a place-holder.
5047*/
danielk1977397d65f2008-11-19 11:35:39 +00005048static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5049 UNUSED_PARAMETER(NotUsed);
5050 UNUSED_PARAMETER(NotUsed2);
5051 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005052 return 0;
5053}
5054
drhf2424c52010-04-26 00:04:55 +00005055
5056/*
drh734c9862008-11-28 15:37:20 +00005057************************ End of sqlite3_vfs methods ***************************
5058******************************************************************************/
5059
drh715ff302008-12-03 22:32:44 +00005060/******************************************************************************
5061************************** Begin Proxy Locking ********************************
5062**
5063** Proxy locking is a "uber-locking-method" in this sense: It uses the
5064** other locking methods on secondary lock files. Proxy locking is a
5065** meta-layer over top of the primitive locking implemented above. For
5066** this reason, the division that implements of proxy locking is deferred
5067** until late in the file (here) after all of the other I/O methods have
5068** been defined - so that the primitive locking methods are available
5069** as services to help with the implementation of proxy locking.
5070**
5071****
5072**
5073** The default locking schemes in SQLite use byte-range locks on the
5074** database file to coordinate safe, concurrent access by multiple readers
5075** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5076** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5077** as POSIX read & write locks over fixed set of locations (via fsctl),
5078** on AFP and SMB only exclusive byte-range locks are available via fsctl
5079** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5080** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5081** address in the shared range is taken for a SHARED lock, the entire
5082** shared range is taken for an EXCLUSIVE lock):
5083**
5084** PENDING_BYTE 0x40000000
5085** RESERVED_BYTE 0x40000001
5086** SHARED_RANGE 0x40000002 -> 0x40000200
5087**
5088** This works well on the local file system, but shows a nearly 100x
5089** slowdown in read performance on AFP because the AFP client disables
5090** the read cache when byte-range locks are present. Enabling the read
5091** cache exposes a cache coherency problem that is present on all OS X
5092** supported network file systems. NFS and AFP both observe the
5093** close-to-open semantics for ensuring cache coherency
5094** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5095** address the requirements for concurrent database access by multiple
5096** readers and writers
5097** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5098**
5099** To address the performance and cache coherency issues, proxy file locking
5100** changes the way database access is controlled by limiting access to a
5101** single host at a time and moving file locks off of the database file
5102** and onto a proxy file on the local file system.
5103**
5104**
5105** Using proxy locks
5106** -----------------
5107**
5108** C APIs
5109**
5110** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5111** <proxy_path> | ":auto:");
5112** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5113**
5114**
5115** SQL pragmas
5116**
5117** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5118** PRAGMA [database.]lock_proxy_file
5119**
5120** Specifying ":auto:" means that if there is a conch file with a matching
5121** host ID in it, the proxy path in the conch file will be used, otherwise
5122** a proxy path based on the user's temp dir
5123** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5124** actual proxy file name is generated from the name and path of the
5125** database file. For example:
5126**
5127** For database path "/Users/me/foo.db"
5128** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5129**
5130** Once a lock proxy is configured for a database connection, it can not
5131** be removed, however it may be switched to a different proxy path via
5132** the above APIs (assuming the conch file is not being held by another
5133** connection or process).
5134**
5135**
5136** How proxy locking works
5137** -----------------------
5138**
5139** Proxy file locking relies primarily on two new supporting files:
5140**
5141** * conch file to limit access to the database file to a single host
5142** at a time
5143**
5144** * proxy file to act as a proxy for the advisory locks normally
5145** taken on the database
5146**
5147** The conch file - to use a proxy file, sqlite must first "hold the conch"
5148** by taking an sqlite-style shared lock on the conch file, reading the
5149** contents and comparing the host's unique host ID (see below) and lock
5150** proxy path against the values stored in the conch. The conch file is
5151** stored in the same directory as the database file and the file name
5152** is patterned after the database file name as ".<databasename>-conch".
5153** If the conch file does not exist, or it's contents do not match the
5154** host ID and/or proxy path, then the lock is escalated to an exclusive
5155** lock and the conch file contents is updated with the host ID and proxy
5156** path and the lock is downgraded to a shared lock again. If the conch
5157** is held by another process (with a shared lock), the exclusive lock
5158** will fail and SQLITE_BUSY is returned.
5159**
5160** The proxy file - a single-byte file used for all advisory file locks
5161** normally taken on the database file. This allows for safe sharing
5162** of the database file for multiple readers and writers on the same
5163** host (the conch ensures that they all use the same local lock file).
5164**
drh715ff302008-12-03 22:32:44 +00005165** Requesting the lock proxy does not immediately take the conch, it is
5166** only taken when the first request to lock database file is made.
5167** This matches the semantics of the traditional locking behavior, where
5168** opening a connection to a database file does not take a lock on it.
5169** The shared lock and an open file descriptor are maintained until
5170** the connection to the database is closed.
5171**
5172** The proxy file and the lock file are never deleted so they only need
5173** to be created the first time they are used.
5174**
5175** Configuration options
5176** ---------------------
5177**
5178** SQLITE_PREFER_PROXY_LOCKING
5179**
5180** Database files accessed on non-local file systems are
5181** automatically configured for proxy locking, lock files are
5182** named automatically using the same logic as
5183** PRAGMA lock_proxy_file=":auto:"
5184**
5185** SQLITE_PROXY_DEBUG
5186**
5187** Enables the logging of error messages during host id file
5188** retrieval and creation
5189**
drh715ff302008-12-03 22:32:44 +00005190** LOCKPROXYDIR
5191**
5192** Overrides the default directory used for lock proxy files that
5193** are named automatically via the ":auto:" setting
5194**
5195** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5196**
5197** Permissions to use when creating a directory for storing the
5198** lock proxy files, only used when LOCKPROXYDIR is not set.
5199**
5200**
5201** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5202** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5203** force proxy locking to be used for every database file opened, and 0
5204** will force automatic proxy locking to be disabled for all database
5205** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5206** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5207*/
5208
5209/*
5210** Proxy locking is only available on MacOSX
5211*/
drhd2cb50b2009-01-09 21:41:17 +00005212#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005213
drh715ff302008-12-03 22:32:44 +00005214/*
5215** The proxyLockingContext has the path and file structures for the remote
5216** and local proxy files in it
5217*/
5218typedef struct proxyLockingContext proxyLockingContext;
5219struct proxyLockingContext {
5220 unixFile *conchFile; /* Open conch file */
5221 char *conchFilePath; /* Name of the conch file */
5222 unixFile *lockProxy; /* Open proxy lock file */
5223 char *lockProxyPath; /* Name of the proxy lock file */
5224 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005225 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005226 void *oldLockingContext; /* Original lockingcontext to restore on close */
5227 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5228};
5229
drh7ed97b92010-01-20 13:07:21 +00005230/*
5231** The proxy lock file path for the database at dbPath is written into lPath,
5232** which must point to valid, writable memory large enough for a maxLen length
5233** file path.
drh715ff302008-12-03 22:32:44 +00005234*/
drh715ff302008-12-03 22:32:44 +00005235static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5236 int len;
5237 int dbLen;
5238 int i;
5239
5240#ifdef LOCKPROXYDIR
5241 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5242#else
5243# ifdef _CS_DARWIN_USER_TEMP_DIR
5244 {
drh7ed97b92010-01-20 13:07:21 +00005245 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005246 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5247 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005248 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005249 }
drh7ed97b92010-01-20 13:07:21 +00005250 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005251 }
5252# else
5253 len = strlcpy(lPath, "/tmp/", maxLen);
5254# endif
5255#endif
5256
5257 if( lPath[len-1]!='/' ){
5258 len = strlcat(lPath, "/", maxLen);
5259 }
5260
5261 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005262 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005263 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005264 char c = dbPath[i];
5265 lPath[i+len] = (c=='/')?'_':c;
5266 }
5267 lPath[i+len]='\0';
5268 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005269 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005270 return SQLITE_OK;
5271}
5272
drh7ed97b92010-01-20 13:07:21 +00005273/*
5274 ** Creates the lock file and any missing directories in lockPath
5275 */
5276static int proxyCreateLockPath(const char *lockPath){
5277 int i, len;
5278 char buf[MAXPATHLEN];
5279 int start = 0;
5280
5281 assert(lockPath!=NULL);
5282 /* try to create all the intermediate directories */
5283 len = (int)strlen(lockPath);
5284 buf[0] = lockPath[0];
5285 for( i=1; i<len; i++ ){
5286 if( lockPath[i] == '/' && (i - start > 0) ){
5287 /* only mkdir if leaf dir != "." or "/" or ".." */
5288 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5289 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5290 buf[i]='\0';
5291 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5292 int err=errno;
5293 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005294 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005295 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005296 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005297 return err;
5298 }
5299 }
5300 }
5301 start=i+1;
5302 }
5303 buf[i] = lockPath[i];
5304 }
drh308c2a52010-05-14 11:30:18 +00005305 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005306 return 0;
5307}
5308
drh715ff302008-12-03 22:32:44 +00005309/*
5310** Create a new VFS file descriptor (stored in memory obtained from
5311** sqlite3_malloc) and open the file named "path" in the file descriptor.
5312**
5313** The caller is responsible not only for closing the file descriptor
5314** but also for freeing the memory associated with the file descriptor.
5315*/
drh7ed97b92010-01-20 13:07:21 +00005316static int proxyCreateUnixFile(
5317 const char *path, /* path for the new unixFile */
5318 unixFile **ppFile, /* unixFile created and returned by ref */
5319 int islockfile /* if non zero missing dirs will be created */
5320) {
5321 int fd = -1;
5322 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005323 unixFile *pNew;
5324 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005325 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005326 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005327 int terrno = 0;
5328 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005329
drh7ed97b92010-01-20 13:07:21 +00005330 /* 1. first try to open/create the file
5331 ** 2. if that fails, and this is a lock file (not-conch), try creating
5332 ** the parent directories and then try again.
5333 ** 3. if that fails, try to open the file read-only
5334 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5335 */
5336 pUnused = findReusableFd(path, openFlags);
5337 if( pUnused ){
5338 fd = pUnused->fd;
5339 }else{
5340 pUnused = sqlite3_malloc(sizeof(*pUnused));
5341 if( !pUnused ){
5342 return SQLITE_NOMEM;
5343 }
5344 }
5345 if( fd<0 ){
5346 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5347 terrno = errno;
5348 if( fd<0 && errno==ENOENT && islockfile ){
5349 if( proxyCreateLockPath(path) == SQLITE_OK ){
5350 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5351 }
5352 }
5353 }
5354 if( fd<0 ){
5355 openFlags = O_RDONLY;
5356 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5357 terrno = errno;
5358 }
5359 if( fd<0 ){
5360 if( islockfile ){
5361 return SQLITE_BUSY;
5362 }
5363 switch (terrno) {
5364 case EACCES:
5365 return SQLITE_PERM;
5366 case EIO:
5367 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5368 default:
drh9978c972010-02-23 17:36:32 +00005369 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005370 }
5371 }
5372
5373 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5374 if( pNew==NULL ){
5375 rc = SQLITE_NOMEM;
5376 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005377 }
5378 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005379 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005380 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005381 pUnused->fd = fd;
5382 pUnused->flags = openFlags;
5383 pNew->pUnused = pUnused;
5384
5385 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5386 if( rc==SQLITE_OK ){
5387 *ppFile = pNew;
5388 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005389 }
drh7ed97b92010-01-20 13:07:21 +00005390end_create_proxy:
5391 close(fd); /* silently leak fd if error, we're already in error */
5392 sqlite3_free(pNew);
5393 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005394 return rc;
5395}
5396
drh7ed97b92010-01-20 13:07:21 +00005397#ifdef SQLITE_TEST
5398/* simulate multiple hosts by creating unique hostid file paths */
5399int sqlite3_hostid_num = 0;
5400#endif
5401
5402#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5403
drh0ab216a2010-07-02 17:10:40 +00005404/* Not always defined in the headers as it ought to be */
5405extern int gethostuuid(uuid_t id, const struct timespec *wait);
5406
drh7ed97b92010-01-20 13:07:21 +00005407/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5408** bytes of writable memory.
5409*/
5410static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005411 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5412 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005413#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5414 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005415 {
5416 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5417 if( gethostuuid(pHostID, &timeout) ){
5418 int err = errno;
5419 if( pError ){
5420 *pError = err;
5421 }
5422 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005423 }
drh7ed97b92010-01-20 13:07:21 +00005424 }
drhe8b0c9b2010-09-25 14:13:17 +00005425#endif
drh7ed97b92010-01-20 13:07:21 +00005426#ifdef SQLITE_TEST
5427 /* simulate multiple hosts by creating unique hostid file paths */
5428 if( sqlite3_hostid_num != 0){
5429 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5430 }
5431#endif
5432
5433 return SQLITE_OK;
5434}
5435
5436/* The conch file contains the header, host id and lock file path
5437 */
5438#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5439#define PROXY_HEADERLEN 1 /* conch file header length */
5440#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5441#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5442
5443/*
5444** Takes an open conch file, copies the contents to a new path and then moves
5445** it back. The newly created file's file descriptor is assigned to the
5446** conch file structure and finally the original conch file descriptor is
5447** closed. Returns zero if successful.
5448*/
5449static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5450 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5451 unixFile *conchFile = pCtx->conchFile;
5452 char tPath[MAXPATHLEN];
5453 char buf[PROXY_MAXCONCHLEN];
5454 char *cPath = pCtx->conchFilePath;
5455 size_t readLen = 0;
5456 size_t pathLen = 0;
5457 char errmsg[64] = "";
5458 int fd = -1;
5459 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005460 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005461
5462 /* create a new path by replace the trailing '-conch' with '-break' */
5463 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5464 if( pathLen>MAXPATHLEN || pathLen<6 ||
5465 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005466 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005467 goto end_breaklock;
5468 }
5469 /* read the conch content */
5470 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5471 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005472 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005473 goto end_breaklock;
5474 }
5475 /* write it out to the temporary break file */
5476 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5477 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005478 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005479 goto end_breaklock;
5480 }
drh0ab216a2010-07-02 17:10:40 +00005481 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005482 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005483 goto end_breaklock;
5484 }
5485 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005486 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005487 goto end_breaklock;
5488 }
5489 rc = 0;
5490 fprintf(stderr, "broke stale lock on %s\n", cPath);
5491 close(conchFile->h);
5492 conchFile->h = fd;
5493 conchFile->openFlags = O_RDWR | O_CREAT;
5494
5495end_breaklock:
5496 if( rc ){
5497 if( fd>=0 ){
5498 unlink(tPath);
5499 close(fd);
5500 }
5501 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5502 }
5503 return rc;
5504}
5505
5506/* Take the requested lock on the conch file and break a stale lock if the
5507** host id matches.
5508*/
5509static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5510 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5511 unixFile *conchFile = pCtx->conchFile;
5512 int rc = SQLITE_OK;
5513 int nTries = 0;
5514 struct timespec conchModTime;
5515
5516 do {
5517 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5518 nTries ++;
5519 if( rc==SQLITE_BUSY ){
5520 /* If the lock failed (busy):
5521 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5522 * 2nd try: fail if the mod time changed or host id is different, wait
5523 * 10 sec and try again
5524 * 3rd try: break the lock unless the mod time has changed.
5525 */
5526 struct stat buf;
5527 if( fstat(conchFile->h, &buf) ){
5528 pFile->lastErrno = errno;
5529 return SQLITE_IOERR_LOCK;
5530 }
5531
5532 if( nTries==1 ){
5533 conchModTime = buf.st_mtimespec;
5534 usleep(500000); /* wait 0.5 sec and try the lock again*/
5535 continue;
5536 }
5537
5538 assert( nTries>1 );
5539 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5540 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5541 return SQLITE_BUSY;
5542 }
5543
5544 if( nTries==2 ){
5545 char tBuf[PROXY_MAXCONCHLEN];
5546 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5547 if( len<0 ){
5548 pFile->lastErrno = errno;
5549 return SQLITE_IOERR_LOCK;
5550 }
5551 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5552 /* don't break the lock if the host id doesn't match */
5553 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5554 return SQLITE_BUSY;
5555 }
5556 }else{
5557 /* don't break the lock on short read or a version mismatch */
5558 return SQLITE_BUSY;
5559 }
5560 usleep(10000000); /* wait 10 sec and try the lock again */
5561 continue;
5562 }
5563
5564 assert( nTries==3 );
5565 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5566 rc = SQLITE_OK;
5567 if( lockType==EXCLUSIVE_LOCK ){
5568 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5569 }
5570 if( !rc ){
5571 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5572 }
5573 }
5574 }
5575 } while( rc==SQLITE_BUSY && nTries<3 );
5576
5577 return rc;
5578}
5579
5580/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005581** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5582** lockPath means that the lockPath in the conch file will be used if the
5583** host IDs match, or a new lock path will be generated automatically
5584** and written to the conch file.
5585*/
5586static int proxyTakeConch(unixFile *pFile){
5587 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5588
drh7ed97b92010-01-20 13:07:21 +00005589 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005590 return SQLITE_OK;
5591 }else{
5592 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005593 uuid_t myHostID;
5594 int pError = 0;
5595 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005596 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005597 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005598 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005599 int createConch = 0;
5600 int hostIdMatch = 0;
5601 int readLen = 0;
5602 int tryOldLockPath = 0;
5603 int forceNewLockPath = 0;
5604
drh308c2a52010-05-14 11:30:18 +00005605 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5606 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005607
drh7ed97b92010-01-20 13:07:21 +00005608 rc = proxyGetHostID(myHostID, &pError);
5609 if( (rc&0xff)==SQLITE_IOERR ){
5610 pFile->lastErrno = pError;
5611 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005612 }
drh7ed97b92010-01-20 13:07:21 +00005613 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005614 if( rc!=SQLITE_OK ){
5615 goto end_takeconch;
5616 }
drh7ed97b92010-01-20 13:07:21 +00005617 /* read the existing conch file */
5618 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5619 if( readLen<0 ){
5620 /* I/O error: lastErrno set by seekAndRead */
5621 pFile->lastErrno = conchFile->lastErrno;
5622 rc = SQLITE_IOERR_READ;
5623 goto end_takeconch;
5624 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5625 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5626 /* a short read or version format mismatch means we need to create a new
5627 ** conch file.
5628 */
5629 createConch = 1;
5630 }
5631 /* if the host id matches and the lock path already exists in the conch
5632 ** we'll try to use the path there, if we can't open that path, we'll
5633 ** retry with a new auto-generated path
5634 */
5635 do { /* in case we need to try again for an :auto: named lock file */
5636
5637 if( !createConch && !forceNewLockPath ){
5638 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5639 PROXY_HOSTIDLEN);
5640 /* if the conch has data compare the contents */
5641 if( !pCtx->lockProxyPath ){
5642 /* for auto-named local lock file, just check the host ID and we'll
5643 ** use the local lock file path that's already in there
5644 */
5645 if( hostIdMatch ){
5646 size_t pathLen = (readLen - PROXY_PATHINDEX);
5647
5648 if( pathLen>=MAXPATHLEN ){
5649 pathLen=MAXPATHLEN-1;
5650 }
5651 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5652 lockPath[pathLen] = 0;
5653 tempLockPath = lockPath;
5654 tryOldLockPath = 1;
5655 /* create a copy of the lock path if the conch is taken */
5656 goto end_takeconch;
5657 }
5658 }else if( hostIdMatch
5659 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5660 readLen-PROXY_PATHINDEX)
5661 ){
5662 /* conch host and lock path match */
5663 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005664 }
drh7ed97b92010-01-20 13:07:21 +00005665 }
5666
5667 /* if the conch isn't writable and doesn't match, we can't take it */
5668 if( (conchFile->openFlags&O_RDWR) == 0 ){
5669 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005670 goto end_takeconch;
5671 }
drh7ed97b92010-01-20 13:07:21 +00005672
5673 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005674 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005675 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5676 tempLockPath = lockPath;
5677 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005678 }
drh7ed97b92010-01-20 13:07:21 +00005679
5680 /* update conch with host and path (this will fail if other process
5681 ** has a shared lock already), if the host id matches, use the big
5682 ** stick.
drh715ff302008-12-03 22:32:44 +00005683 */
drh7ed97b92010-01-20 13:07:21 +00005684 futimes(conchFile->h, NULL);
5685 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005686 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005687 /* We are trying for an exclusive lock but another thread in this
5688 ** same process is still holding a shared lock. */
5689 rc = SQLITE_BUSY;
5690 } else {
5691 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005692 }
drh715ff302008-12-03 22:32:44 +00005693 }else{
drh7ed97b92010-01-20 13:07:21 +00005694 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005695 }
drh7ed97b92010-01-20 13:07:21 +00005696 if( rc==SQLITE_OK ){
5697 char writeBuffer[PROXY_MAXCONCHLEN];
5698 int writeSize = 0;
5699
5700 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5701 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5702 if( pCtx->lockProxyPath!=NULL ){
5703 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5704 }else{
5705 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5706 }
5707 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5708 ftruncate(conchFile->h, writeSize);
5709 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5710 fsync(conchFile->h);
5711 /* If we created a new conch file (not just updated the contents of a
5712 ** valid conch file), try to match the permissions of the database
5713 */
5714 if( rc==SQLITE_OK && createConch ){
5715 struct stat buf;
5716 int err = fstat(pFile->h, &buf);
5717 if( err==0 ){
5718 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5719 S_IROTH|S_IWOTH);
5720 /* try to match the database file R/W permissions, ignore failure */
5721#ifndef SQLITE_PROXY_DEBUG
5722 fchmod(conchFile->h, cmode);
5723#else
5724 if( fchmod(conchFile->h, cmode)!=0 ){
5725 int code = errno;
5726 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5727 cmode, code, strerror(code));
5728 } else {
5729 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5730 }
5731 }else{
5732 int code = errno;
5733 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5734 err, code, strerror(code));
5735#endif
5736 }
drh715ff302008-12-03 22:32:44 +00005737 }
5738 }
drh7ed97b92010-01-20 13:07:21 +00005739 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5740
5741 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005742 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005743 if( rc==SQLITE_OK && pFile->openFlags ){
5744 if( pFile->h>=0 ){
5745#ifdef STRICT_CLOSE_ERROR
5746 if( close(pFile->h) ){
5747 pFile->lastErrno = errno;
5748 return SQLITE_IOERR_CLOSE;
5749 }
5750#else
5751 close(pFile->h); /* silently leak fd if fail */
5752#endif
5753 }
5754 pFile->h = -1;
5755 int fd = open(pCtx->dbPath, pFile->openFlags,
5756 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005757 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005758 if( fd>=0 ){
5759 pFile->h = fd;
5760 }else{
drh9978c972010-02-23 17:36:32 +00005761 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005762 during locking */
5763 }
5764 }
5765 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5766 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5767 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5768 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5769 /* we couldn't create the proxy lock file with the old lock file path
5770 ** so try again via auto-naming
5771 */
5772 forceNewLockPath = 1;
5773 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005774 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005775 }
5776 }
5777 if( rc==SQLITE_OK ){
5778 /* Need to make a copy of path if we extracted the value
5779 ** from the conch file or the path was allocated on the stack
5780 */
5781 if( tempLockPath ){
5782 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5783 if( !pCtx->lockProxyPath ){
5784 rc = SQLITE_NOMEM;
5785 }
5786 }
5787 }
5788 if( rc==SQLITE_OK ){
5789 pCtx->conchHeld = 1;
5790
5791 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5792 afpLockingContext *afpCtx;
5793 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5794 afpCtx->dbPath = pCtx->lockProxyPath;
5795 }
5796 } else {
5797 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5798 }
drh308c2a52010-05-14 11:30:18 +00005799 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5800 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005801 return rc;
drh308c2a52010-05-14 11:30:18 +00005802 } while (1); /* in case we need to retry the :auto: lock file -
5803 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005804 }
5805}
5806
5807/*
5808** If pFile holds a lock on a conch file, then release that lock.
5809*/
5810static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005811 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005812 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5813 unixFile *conchFile; /* Name of the conch file */
5814
5815 pCtx = (proxyLockingContext *)pFile->lockingContext;
5816 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005817 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005818 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005819 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005820 if( pCtx->conchHeld>0 ){
5821 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5822 }
drh715ff302008-12-03 22:32:44 +00005823 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005824 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5825 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005826 return rc;
5827}
5828
5829/*
5830** Given the name of a database file, compute the name of its conch file.
5831** Store the conch filename in memory obtained from sqlite3_malloc().
5832** Make *pConchPath point to the new name. Return SQLITE_OK on success
5833** or SQLITE_NOMEM if unable to obtain memory.
5834**
5835** The caller is responsible for ensuring that the allocated memory
5836** space is eventually freed.
5837**
5838** *pConchPath is set to NULL if a memory allocation error occurs.
5839*/
5840static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5841 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005842 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005843 char *conchPath; /* buffer in which to construct conch name */
5844
5845 /* Allocate space for the conch filename and initialize the name to
5846 ** the name of the original database file. */
5847 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5848 if( conchPath==0 ){
5849 return SQLITE_NOMEM;
5850 }
5851 memcpy(conchPath, dbPath, len+1);
5852
5853 /* now insert a "." before the last / character */
5854 for( i=(len-1); i>=0; i-- ){
5855 if( conchPath[i]=='/' ){
5856 i++;
5857 break;
5858 }
5859 }
5860 conchPath[i]='.';
5861 while ( i<len ){
5862 conchPath[i+1]=dbPath[i];
5863 i++;
5864 }
5865
5866 /* append the "-conch" suffix to the file */
5867 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005868 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005869
5870 return SQLITE_OK;
5871}
5872
5873
5874/* Takes a fully configured proxy locking-style unix file and switches
5875** the local lock file path
5876*/
5877static int switchLockProxyPath(unixFile *pFile, const char *path) {
5878 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5879 char *oldPath = pCtx->lockProxyPath;
5880 int rc = SQLITE_OK;
5881
drh308c2a52010-05-14 11:30:18 +00005882 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005883 return SQLITE_BUSY;
5884 }
5885
5886 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5887 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5888 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5889 return SQLITE_OK;
5890 }else{
5891 unixFile *lockProxy = pCtx->lockProxy;
5892 pCtx->lockProxy=NULL;
5893 pCtx->conchHeld = 0;
5894 if( lockProxy!=NULL ){
5895 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5896 if( rc ) return rc;
5897 sqlite3_free(lockProxy);
5898 }
5899 sqlite3_free(oldPath);
5900 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5901 }
5902
5903 return rc;
5904}
5905
5906/*
5907** pFile is a file that has been opened by a prior xOpen call. dbPath
5908** is a string buffer at least MAXPATHLEN+1 characters in size.
5909**
5910** This routine find the filename associated with pFile and writes it
5911** int dbPath.
5912*/
5913static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005914#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005915 if( pFile->pMethod == &afpIoMethods ){
5916 /* afp style keeps a reference to the db path in the filePath field
5917 ** of the struct */
drhea678832008-12-10 19:26:22 +00005918 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005919 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5920 } else
drh715ff302008-12-03 22:32:44 +00005921#endif
5922 if( pFile->pMethod == &dotlockIoMethods ){
5923 /* dot lock style uses the locking context to store the dot lock
5924 ** file path */
5925 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5926 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5927 }else{
5928 /* all other styles use the locking context to store the db file path */
5929 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005930 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005931 }
5932 return SQLITE_OK;
5933}
5934
5935/*
5936** Takes an already filled in unix file and alters it so all file locking
5937** will be performed on the local proxy lock file. The following fields
5938** are preserved in the locking context so that they can be restored and
5939** the unix structure properly cleaned up at close time:
5940** ->lockingContext
5941** ->pMethod
5942*/
5943static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5944 proxyLockingContext *pCtx;
5945 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5946 char *lockPath=NULL;
5947 int rc = SQLITE_OK;
5948
drh308c2a52010-05-14 11:30:18 +00005949 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005950 return SQLITE_BUSY;
5951 }
5952 proxyGetDbPathForUnixFile(pFile, dbPath);
5953 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5954 lockPath=NULL;
5955 }else{
5956 lockPath=(char *)path;
5957 }
5958
drh308c2a52010-05-14 11:30:18 +00005959 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5960 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005961
5962 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5963 if( pCtx==0 ){
5964 return SQLITE_NOMEM;
5965 }
5966 memset(pCtx, 0, sizeof(*pCtx));
5967
5968 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5969 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005970 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5971 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5972 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5973 ** (c) the file system is read-only, then enable no-locking access.
5974 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5975 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5976 */
5977 struct statfs fsInfo;
5978 struct stat conchInfo;
5979 int goLockless = 0;
5980
5981 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5982 int err = errno;
5983 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5984 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5985 }
5986 }
5987 if( goLockless ){
5988 pCtx->conchHeld = -1; /* read only FS/ lockless */
5989 rc = SQLITE_OK;
5990 }
5991 }
drh715ff302008-12-03 22:32:44 +00005992 }
5993 if( rc==SQLITE_OK && lockPath ){
5994 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5995 }
5996
5997 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005998 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5999 if( pCtx->dbPath==NULL ){
6000 rc = SQLITE_NOMEM;
6001 }
6002 }
6003 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006004 /* all memory is allocated, proxys are created and assigned,
6005 ** switch the locking context and pMethod then return.
6006 */
drh715ff302008-12-03 22:32:44 +00006007 pCtx->oldLockingContext = pFile->lockingContext;
6008 pFile->lockingContext = pCtx;
6009 pCtx->pOldMethod = pFile->pMethod;
6010 pFile->pMethod = &proxyIoMethods;
6011 }else{
6012 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006013 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006014 sqlite3_free(pCtx->conchFile);
6015 }
drhd56b1212010-08-11 06:14:15 +00006016 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006017 sqlite3_free(pCtx->conchFilePath);
6018 sqlite3_free(pCtx);
6019 }
drh308c2a52010-05-14 11:30:18 +00006020 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6021 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006022 return rc;
6023}
6024
6025
6026/*
6027** This routine handles sqlite3_file_control() calls that are specific
6028** to proxy locking.
6029*/
6030static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6031 switch( op ){
6032 case SQLITE_GET_LOCKPROXYFILE: {
6033 unixFile *pFile = (unixFile*)id;
6034 if( pFile->pMethod == &proxyIoMethods ){
6035 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6036 proxyTakeConch(pFile);
6037 if( pCtx->lockProxyPath ){
6038 *(const char **)pArg = pCtx->lockProxyPath;
6039 }else{
6040 *(const char **)pArg = ":auto: (not held)";
6041 }
6042 } else {
6043 *(const char **)pArg = NULL;
6044 }
6045 return SQLITE_OK;
6046 }
6047 case SQLITE_SET_LOCKPROXYFILE: {
6048 unixFile *pFile = (unixFile*)id;
6049 int rc = SQLITE_OK;
6050 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6051 if( pArg==NULL || (const char *)pArg==0 ){
6052 if( isProxyStyle ){
6053 /* turn off proxy locking - not supported */
6054 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6055 }else{
6056 /* turn off proxy locking - already off - NOOP */
6057 rc = SQLITE_OK;
6058 }
6059 }else{
6060 const char *proxyPath = (const char *)pArg;
6061 if( isProxyStyle ){
6062 proxyLockingContext *pCtx =
6063 (proxyLockingContext*)pFile->lockingContext;
6064 if( !strcmp(pArg, ":auto:")
6065 || (pCtx->lockProxyPath &&
6066 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6067 ){
6068 rc = SQLITE_OK;
6069 }else{
6070 rc = switchLockProxyPath(pFile, proxyPath);
6071 }
6072 }else{
6073 /* turn on proxy file locking */
6074 rc = proxyTransformUnixFile(pFile, proxyPath);
6075 }
6076 }
6077 return rc;
6078 }
6079 default: {
6080 assert( 0 ); /* The call assures that only valid opcodes are sent */
6081 }
6082 }
6083 /*NOTREACHED*/
6084 return SQLITE_ERROR;
6085}
6086
6087/*
6088** Within this division (the proxying locking implementation) the procedures
6089** above this point are all utilities. The lock-related methods of the
6090** proxy-locking sqlite3_io_method object follow.
6091*/
6092
6093
6094/*
6095** This routine checks if there is a RESERVED lock held on the specified
6096** file by this or any other process. If such a lock is held, set *pResOut
6097** to a non-zero value otherwise *pResOut is set to zero. The return value
6098** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6099*/
6100static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6101 unixFile *pFile = (unixFile*)id;
6102 int rc = proxyTakeConch(pFile);
6103 if( rc==SQLITE_OK ){
6104 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006105 if( pCtx->conchHeld>0 ){
6106 unixFile *proxy = pCtx->lockProxy;
6107 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6108 }else{ /* conchHeld < 0 is lockless */
6109 pResOut=0;
6110 }
drh715ff302008-12-03 22:32:44 +00006111 }
6112 return rc;
6113}
6114
6115/*
drh308c2a52010-05-14 11:30:18 +00006116** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006117** of the following:
6118**
6119** (1) SHARED_LOCK
6120** (2) RESERVED_LOCK
6121** (3) PENDING_LOCK
6122** (4) EXCLUSIVE_LOCK
6123**
6124** Sometimes when requesting one lock state, additional lock states
6125** are inserted in between. The locking might fail on one of the later
6126** transitions leaving the lock state different from what it started but
6127** still short of its goal. The following chart shows the allowed
6128** transitions and the inserted intermediate states:
6129**
6130** UNLOCKED -> SHARED
6131** SHARED -> RESERVED
6132** SHARED -> (PENDING) -> EXCLUSIVE
6133** RESERVED -> (PENDING) -> EXCLUSIVE
6134** PENDING -> EXCLUSIVE
6135**
6136** This routine will only increase a lock. Use the sqlite3OsUnlock()
6137** routine to lower a locking level.
6138*/
drh308c2a52010-05-14 11:30:18 +00006139static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006140 unixFile *pFile = (unixFile*)id;
6141 int rc = proxyTakeConch(pFile);
6142 if( rc==SQLITE_OK ){
6143 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006144 if( pCtx->conchHeld>0 ){
6145 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006146 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6147 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006148 }else{
6149 /* conchHeld < 0 is lockless */
6150 }
drh715ff302008-12-03 22:32:44 +00006151 }
6152 return rc;
6153}
6154
6155
6156/*
drh308c2a52010-05-14 11:30:18 +00006157** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006158** must be either NO_LOCK or SHARED_LOCK.
6159**
6160** If the locking level of the file descriptor is already at or below
6161** the requested locking level, this routine is a no-op.
6162*/
drh308c2a52010-05-14 11:30:18 +00006163static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006164 unixFile *pFile = (unixFile*)id;
6165 int rc = proxyTakeConch(pFile);
6166 if( rc==SQLITE_OK ){
6167 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006168 if( pCtx->conchHeld>0 ){
6169 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006170 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6171 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006172 }else{
6173 /* conchHeld < 0 is lockless */
6174 }
drh715ff302008-12-03 22:32:44 +00006175 }
6176 return rc;
6177}
6178
6179/*
6180** Close a file that uses proxy locks.
6181*/
6182static int proxyClose(sqlite3_file *id) {
6183 if( id ){
6184 unixFile *pFile = (unixFile*)id;
6185 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6186 unixFile *lockProxy = pCtx->lockProxy;
6187 unixFile *conchFile = pCtx->conchFile;
6188 int rc = SQLITE_OK;
6189
6190 if( lockProxy ){
6191 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6192 if( rc ) return rc;
6193 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6194 if( rc ) return rc;
6195 sqlite3_free(lockProxy);
6196 pCtx->lockProxy = 0;
6197 }
6198 if( conchFile ){
6199 if( pCtx->conchHeld ){
6200 rc = proxyReleaseConch(pFile);
6201 if( rc ) return rc;
6202 }
6203 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6204 if( rc ) return rc;
6205 sqlite3_free(conchFile);
6206 }
drhd56b1212010-08-11 06:14:15 +00006207 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006208 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006209 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006210 /* restore the original locking context and pMethod then close it */
6211 pFile->lockingContext = pCtx->oldLockingContext;
6212 pFile->pMethod = pCtx->pOldMethod;
6213 sqlite3_free(pCtx);
6214 return pFile->pMethod->xClose(id);
6215 }
6216 return SQLITE_OK;
6217}
6218
6219
6220
drhd2cb50b2009-01-09 21:41:17 +00006221#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006222/*
6223** The proxy locking style is intended for use with AFP filesystems.
6224** And since AFP is only supported on MacOSX, the proxy locking is also
6225** restricted to MacOSX.
6226**
6227**
6228******************* End of the proxy lock implementation **********************
6229******************************************************************************/
6230
drh734c9862008-11-28 15:37:20 +00006231/*
danielk1977e339d652008-06-28 11:23:00 +00006232** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006233**
6234** This routine registers all VFS implementations for unix-like operating
6235** systems. This routine, and the sqlite3_os_end() routine that follows,
6236** should be the only routines in this file that are visible from other
6237** files.
drh6b9d6dd2008-12-03 19:34:47 +00006238**
6239** This routine is called once during SQLite initialization and by a
6240** single thread. The memory allocation and mutex subsystems have not
6241** necessarily been initialized when this routine is called, and so they
6242** should not be used.
drh153c62c2007-08-24 03:51:33 +00006243*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006244int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006245 /*
6246 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006247 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6248 ** to the "finder" function. (pAppData is a pointer to a pointer because
6249 ** silly C90 rules prohibit a void* from being cast to a function pointer
6250 ** and so we have to go through the intermediate pointer to avoid problems
6251 ** when compiling with -pedantic-errors on GCC.)
6252 **
6253 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006254 ** finder-function. The finder-function returns a pointer to the
6255 ** sqlite_io_methods object that implements the desired locking
6256 ** behaviors. See the division above that contains the IOMETHODS
6257 ** macro for addition information on finder-functions.
6258 **
6259 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6260 ** object. But the "autolockIoFinder" available on MacOSX does a little
6261 ** more than that; it looks at the filesystem type that hosts the
6262 ** database file and tries to choose an locking method appropriate for
6263 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006264 */
drh7708e972008-11-29 00:56:52 +00006265 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006266 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006267 sizeof(unixFile), /* szOsFile */ \
6268 MAX_PATHNAME, /* mxPathname */ \
6269 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006270 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006271 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006272 unixOpen, /* xOpen */ \
6273 unixDelete, /* xDelete */ \
6274 unixAccess, /* xAccess */ \
6275 unixFullPathname, /* xFullPathname */ \
6276 unixDlOpen, /* xDlOpen */ \
6277 unixDlError, /* xDlError */ \
6278 unixDlSym, /* xDlSym */ \
6279 unixDlClose, /* xDlClose */ \
6280 unixRandomness, /* xRandomness */ \
6281 unixSleep, /* xSleep */ \
6282 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006283 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006284 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006285 }
6286
drh6b9d6dd2008-12-03 19:34:47 +00006287 /*
6288 ** All default VFSes for unix are contained in the following array.
6289 **
6290 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6291 ** by the SQLite core when the VFS is registered. So the following
6292 ** array cannot be const.
6293 */
danielk1977e339d652008-06-28 11:23:00 +00006294 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006295#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006296 UNIXVFS("unix", autolockIoFinder ),
6297#else
6298 UNIXVFS("unix", posixIoFinder ),
6299#endif
6300 UNIXVFS("unix-none", nolockIoFinder ),
6301 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006302#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006303 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006304#endif
6305#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006306 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006307#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006308 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006309#endif
chw78a13182009-04-07 05:35:03 +00006310#endif
drhd2cb50b2009-01-09 21:41:17 +00006311#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006312 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006313 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006314 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006315#endif
drh153c62c2007-08-24 03:51:33 +00006316 };
drh6b9d6dd2008-12-03 19:34:47 +00006317 unsigned int i; /* Loop counter */
6318
6319 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006320 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006321 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006322 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006323 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006324}
danielk1977e339d652008-06-28 11:23:00 +00006325
6326/*
drh6b9d6dd2008-12-03 19:34:47 +00006327** Shutdown the operating system interface.
6328**
6329** Some operating systems might need to do some cleanup in this routine,
6330** to release dynamically allocated objects. But not on unix.
6331** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006332*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006333int sqlite3_os_end(void){
6334 return SQLITE_OK;
6335}
drhdce8bdb2007-08-16 13:01:44 +00006336
danielk197729bafea2008-06-26 10:41:19 +00006337#endif /* SQLITE_OS_UNIX */