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