blob: 467409b198ec51416294dc5a58e6c6e686a40fb8 [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
2768 /* If the user has configured a chunk-size for this file, it could be
2769 ** that the file needs to be extended at this point.
2770 */
2771 if( pFile->szChunk && amt==0 ){
2772 i64 nSize; /* Required file size */
2773 struct stat buf; /* Used to hold return values of fstat() */
2774 int rc = fstat(pFile->h, &buf);
2775 if( rc!=0 ) return SQLITE_IOERR_FSTAT;
2776 nSize = ((offset+amt+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
2777 if( nSize>(i64)buf.st_size ){
2778#ifdef HAVE_POSIX_FALLOCATE
2779 if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
2780 return SQLITE_IOERR_WRITE;
2781 }
2782#else
2783 /* If the OS does not have posix_fallocate(), fake it. First use
2784 ** ftruncate() to set the file size, then write a single byte to
2785 ** the last byte in each block within the extended region.
2786 */
2787 int nBlk = buf.st_blksize; /* File-system block size */
2788 i64 iWrite; /* Next offset to write to */
2789
2790 if( ftruncate(pFile->h, nSize) ){
2791 pFile->lastErrno = errno;
2792 return SQLITE_IOERR_TRUNCATE;
2793 }
2794 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
2795 do {
2796 wrote = seekAndWrite(pFile, iWrite, "", 1);
2797 iWrite += nBlk;
2798 } while( wrote==1 && iWrite<nSize );
2799 if( wrote!=1 ) amt = 1;
2800#endif
2801 }
2802 }
2803
drh734c9862008-11-28 15:37:20 +00002804 if( amt>0 ){
2805 if( wrote<0 ){
2806 /* lastErrno set by seekAndWrite */
2807 return SQLITE_IOERR_WRITE;
2808 }else{
dan08da86a2009-08-21 17:18:03 +00002809 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002810 return SQLITE_FULL;
2811 }
2812 }
dan6e09d692010-07-27 18:34:15 +00002813
drh734c9862008-11-28 15:37:20 +00002814 return SQLITE_OK;
2815}
2816
2817#ifdef SQLITE_TEST
2818/*
2819** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002820** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002821*/
2822int sqlite3_sync_count = 0;
2823int sqlite3_fullsync_count = 0;
2824#endif
2825
2826/*
drh89240432009-03-25 01:06:01 +00002827** We do not trust systems to provide a working fdatasync(). Some do.
2828** Others do no. To be safe, we will stick with the (slower) fsync().
2829** If you know that your system does support fdatasync() correctly,
2830** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002831*/
drh89240432009-03-25 01:06:01 +00002832#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002833# define fdatasync fsync
2834#endif
2835
2836/*
2837** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2838** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2839** only available on Mac OS X. But that could change.
2840*/
2841#ifdef F_FULLFSYNC
2842# define HAVE_FULLFSYNC 1
2843#else
2844# define HAVE_FULLFSYNC 0
2845#endif
2846
2847
2848/*
2849** The fsync() system call does not work as advertised on many
2850** unix systems. The following procedure is an attempt to make
2851** it work better.
2852**
2853** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2854** for testing when we want to run through the test suite quickly.
2855** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2856** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2857** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002858**
2859** SQLite sets the dataOnly flag if the size of the file is unchanged.
2860** The idea behind dataOnly is that it should only write the file content
2861** to disk, not the inode. We only set dataOnly if the file size is
2862** unchanged since the file size is part of the inode. However,
2863** Ted Ts'o tells us that fdatasync() will also write the inode if the
2864** file size has changed. The only real difference between fdatasync()
2865** and fsync(), Ted tells us, is that fdatasync() will not flush the
2866** inode if the mtime or owner or other inode attributes have changed.
2867** We only care about the file size, not the other file attributes, so
2868** as far as SQLite is concerned, an fdatasync() is always adequate.
2869** So, we always use fdatasync() if it is available, regardless of
2870** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002871*/
2872static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002873 int rc;
drh734c9862008-11-28 15:37:20 +00002874
2875 /* The following "ifdef/elif/else/" block has the same structure as
2876 ** the one below. It is replicated here solely to avoid cluttering
2877 ** up the real code with the UNUSED_PARAMETER() macros.
2878 */
2879#ifdef SQLITE_NO_SYNC
2880 UNUSED_PARAMETER(fd);
2881 UNUSED_PARAMETER(fullSync);
2882 UNUSED_PARAMETER(dataOnly);
2883#elif HAVE_FULLFSYNC
2884 UNUSED_PARAMETER(dataOnly);
2885#else
2886 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002887 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002888#endif
2889
2890 /* Record the number of times that we do a normal fsync() and
2891 ** FULLSYNC. This is used during testing to verify that this procedure
2892 ** gets called with the correct arguments.
2893 */
2894#ifdef SQLITE_TEST
2895 if( fullSync ) sqlite3_fullsync_count++;
2896 sqlite3_sync_count++;
2897#endif
2898
2899 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2900 ** no-op
2901 */
2902#ifdef SQLITE_NO_SYNC
2903 rc = SQLITE_OK;
2904#elif HAVE_FULLFSYNC
2905 if( fullSync ){
2906 rc = fcntl(fd, F_FULLFSYNC, 0);
2907 }else{
2908 rc = 1;
2909 }
2910 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002911 ** It shouldn't be possible for fullfsync to fail on the local
2912 ** file system (on OSX), so failure indicates that FULLFSYNC
2913 ** isn't supported for this file system. So, attempt an fsync
2914 ** and (for now) ignore the overhead of a superfluous fcntl call.
2915 ** It'd be better to detect fullfsync support once and avoid
2916 ** the fcntl call every time sync is called.
2917 */
drh734c9862008-11-28 15:37:20 +00002918 if( rc ) rc = fsync(fd);
2919
drh7ed97b92010-01-20 13:07:21 +00002920#elif defined(__APPLE__)
2921 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2922 ** so currently we default to the macro that redefines fdatasync to fsync
2923 */
2924 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002925#else
drh0b647ff2009-03-21 14:41:04 +00002926 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002927#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002928 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002929 rc = fsync(fd);
2930 }
drh0b647ff2009-03-21 14:41:04 +00002931#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002932#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2933
2934 if( OS_VXWORKS && rc!= -1 ){
2935 rc = 0;
2936 }
chw97185482008-11-17 08:05:31 +00002937 return rc;
drhbfe66312006-10-03 17:40:40 +00002938}
2939
drh734c9862008-11-28 15:37:20 +00002940/*
2941** Make sure all writes to a particular file are committed to disk.
2942**
2943** If dataOnly==0 then both the file itself and its metadata (file
2944** size, access time, etc) are synced. If dataOnly!=0 then only the
2945** file data is synced.
2946**
2947** Under Unix, also make sure that the directory entry for the file
2948** has been created by fsync-ing the directory that contains the file.
2949** If we do not do this and we encounter a power failure, the directory
2950** entry for the journal might not exist after we reboot. The next
2951** SQLite to access the file will not know that the journal exists (because
2952** the directory entry for the journal was never created) and the transaction
2953** will not roll back - possibly leading to database corruption.
2954*/
2955static int unixSync(sqlite3_file *id, int flags){
2956 int rc;
2957 unixFile *pFile = (unixFile*)id;
2958
2959 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2960 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2961
2962 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2963 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2964 || (flags&0x0F)==SQLITE_SYNC_FULL
2965 );
2966
2967 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2968 ** line is to test that doing so does not cause any problems.
2969 */
2970 SimulateDiskfullError( return SQLITE_FULL );
2971
2972 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002973 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00002974 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2975 SimulateIOError( rc=1 );
2976 if( rc ){
2977 pFile->lastErrno = errno;
2978 return SQLITE_IOERR_FSYNC;
2979 }
2980 if( pFile->dirfd>=0 ){
2981 int err;
drh308c2a52010-05-14 11:30:18 +00002982 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2983 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00002984#ifndef SQLITE_DISABLE_DIRSYNC
2985 /* The directory sync is only attempted if full_fsync is
2986 ** turned off or unavailable. If a full_fsync occurred above,
2987 ** then the directory sync is superfluous.
2988 */
2989 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2990 /*
2991 ** We have received multiple reports of fsync() returning
2992 ** errors when applied to directories on certain file systems.
2993 ** A failed directory sync is not a big deal. So it seems
2994 ** better to ignore the error. Ticket #1657
2995 */
2996 /* pFile->lastErrno = errno; */
2997 /* return SQLITE_IOERR; */
2998 }
2999#endif
3000 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3001 if( err==0 ){ /* directory when we are done */
3002 pFile->dirfd = -1;
3003 }else{
3004 pFile->lastErrno = errno;
3005 rc = SQLITE_IOERR_DIR_CLOSE;
3006 }
3007 }
3008 return rc;
3009}
3010
3011/*
3012** Truncate an open file to a specified size
3013*/
3014static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003015 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003016 int rc;
dan6e09d692010-07-27 18:34:15 +00003017 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003018 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003019
3020 /* If the user has configured a chunk-size for this file, truncate the
3021 ** file so that it consists of an integer number of chunks (i.e. the
3022 ** actual file size after the operation may be larger than the requested
3023 ** size).
3024 */
3025 if( pFile->szChunk ){
3026 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3027 }
3028
3029 rc = ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003030 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003031 pFile->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00003032 return SQLITE_IOERR_TRUNCATE;
3033 }else{
drh3313b142009-11-06 04:13:18 +00003034#ifndef NDEBUG
3035 /* If we are doing a normal write to a database file (as opposed to
3036 ** doing a hot-journal rollback or a write to some file other than a
3037 ** normal database file) and we truncate the file to zero length,
3038 ** that effectively updates the change counter. This might happen
3039 ** when restoring a database using the backup API from a zero-length
3040 ** source.
3041 */
dan6e09d692010-07-27 18:34:15 +00003042 if( pFile->inNormalWrite && nByte==0 ){
3043 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003044 }
3045#endif
3046
drh734c9862008-11-28 15:37:20 +00003047 return SQLITE_OK;
3048 }
3049}
3050
3051/*
3052** Determine the current size of a file in bytes
3053*/
3054static int unixFileSize(sqlite3_file *id, i64 *pSize){
3055 int rc;
3056 struct stat buf;
3057 assert( id );
3058 rc = fstat(((unixFile*)id)->h, &buf);
3059 SimulateIOError( rc=1 );
3060 if( rc!=0 ){
3061 ((unixFile*)id)->lastErrno = errno;
3062 return SQLITE_IOERR_FSTAT;
3063 }
3064 *pSize = buf.st_size;
3065
drh8af6c222010-05-14 12:43:01 +00003066 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003067 ** writes a single byte into that file in order to work around a bug
3068 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3069 ** layers, we need to report this file size as zero even though it is
3070 ** really 1. Ticket #3260.
3071 */
3072 if( *pSize==1 ) *pSize = 0;
3073
3074
3075 return SQLITE_OK;
3076}
3077
drhd2cb50b2009-01-09 21:41:17 +00003078#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003079/*
3080** Handler for proxy-locking file-control verbs. Defined below in the
3081** proxying locking division.
3082*/
3083static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003084#endif
drh715ff302008-12-03 22:32:44 +00003085
danielk1977ad94b582007-08-20 06:44:22 +00003086
danielk1977e3026632004-06-22 11:29:02 +00003087/*
drh9e33c2c2007-08-31 18:34:59 +00003088** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003089*/
drhcc6bb3e2007-08-31 16:11:35 +00003090static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003091 switch( op ){
3092 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003093 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003094 return SQLITE_OK;
3095 }
drh7708e972008-11-29 00:56:52 +00003096 case SQLITE_LAST_ERRNO: {
3097 *(int*)pArg = ((unixFile*)id)->lastErrno;
3098 return SQLITE_OK;
3099 }
dan6e09d692010-07-27 18:34:15 +00003100 case SQLITE_FCNTL_CHUNK_SIZE: {
3101 ((unixFile*)id)->szChunk = *(int *)pArg;
3102 return SQLITE_OK;
3103 }
drh9ff27ec2010-05-19 19:26:05 +00003104 case SQLITE_FCNTL_SIZE_HINT: {
drhc5276692010-05-21 18:24:06 +00003105#if 0 /* No performance advantage seen on Linux */
drh9ff27ec2010-05-19 19:26:05 +00003106 sqlite3_int64 szFile = *(sqlite3_int64*)pArg;
3107 unixFile *pFile = (unixFile*)id;
3108 ftruncate(pFile->h, szFile);
drhc5276692010-05-21 18:24:06 +00003109#endif
drh9ff27ec2010-05-19 19:26:05 +00003110 return SQLITE_OK;
3111 }
drh8f941bc2009-01-14 23:03:40 +00003112#ifndef NDEBUG
3113 /* The pager calls this method to signal that it has done
3114 ** a rollback and that the database is therefore unchanged and
3115 ** it hence it is OK for the transaction change counter to be
3116 ** unchanged.
3117 */
3118 case SQLITE_FCNTL_DB_UNCHANGED: {
3119 ((unixFile*)id)->dbUpdate = 0;
3120 return SQLITE_OK;
3121 }
3122#endif
drhd2cb50b2009-01-09 21:41:17 +00003123#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003124 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003125 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003126 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003127 }
drhd2cb50b2009-01-09 21:41:17 +00003128#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003129 }
drhcc6bb3e2007-08-31 16:11:35 +00003130 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003131}
3132
3133/*
danielk1977a3d4c882007-03-23 10:08:38 +00003134** Return the sector size in bytes of the underlying block device for
3135** the specified file. This is almost always 512 bytes, but may be
3136** larger for some devices.
3137**
3138** SQLite code assumes this function cannot fail. It also assumes that
3139** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003140** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003141** same for both.
3142*/
danielk1977397d65f2008-11-19 11:35:39 +00003143static int unixSectorSize(sqlite3_file *NotUsed){
3144 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003145 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003146}
3147
danielk197790949c22007-08-17 16:50:38 +00003148/*
danielk1977397d65f2008-11-19 11:35:39 +00003149** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003150*/
danielk1977397d65f2008-11-19 11:35:39 +00003151static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3152 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003153 return 0;
3154}
3155
drhd9e5c4f2010-05-12 18:01:39 +00003156#ifndef SQLITE_OMIT_WAL
3157
3158
3159/*
drhd91c68f2010-05-14 14:52:25 +00003160** Object used to represent an shared memory buffer.
3161**
3162** When multiple threads all reference the same wal-index, each thread
3163** has its own unixShm object, but they all point to a single instance
3164** of this unixShmNode object. In other words, each wal-index is opened
3165** only once per process.
3166**
3167** Each unixShmNode object is connected to a single unixInodeInfo object.
3168** We could coalesce this object into unixInodeInfo, but that would mean
3169** every open file that does not use shared memory (in other words, most
3170** open files) would have to carry around this extra information. So
3171** the unixInodeInfo object contains a pointer to this unixShmNode object
3172** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003173**
3174** unixMutexHeld() must be true when creating or destroying
3175** this object or while reading or writing the following fields:
3176**
3177** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003178**
3179** The following fields are read-only after the object is created:
3180**
3181** fid
3182** zFilename
3183**
drhd91c68f2010-05-14 14:52:25 +00003184** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003185** unixMutexHeld() is true when reading or writing any other field
3186** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003187*/
drhd91c68f2010-05-14 14:52:25 +00003188struct unixShmNode {
3189 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003190 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003191 char *zFilename; /* Name of the mmapped file */
3192 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003193 int szRegion; /* Size of shared-memory regions */
3194 int nRegion; /* Size of array apRegion */
3195 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003196 int nRef; /* Number of unixShm objects pointing to this */
3197 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003198#ifdef SQLITE_DEBUG
3199 u8 exclMask; /* Mask of exclusive locks held */
3200 u8 sharedMask; /* Mask of shared locks held */
3201 u8 nextShmId; /* Next available unixShm.id value */
3202#endif
3203};
3204
3205/*
drhd9e5c4f2010-05-12 18:01:39 +00003206** Structure used internally by this VFS to record the state of an
3207** open shared memory connection.
3208**
drhd91c68f2010-05-14 14:52:25 +00003209** The following fields are initialized when this object is created and
3210** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003211**
drhd91c68f2010-05-14 14:52:25 +00003212** unixShm.pFile
3213** unixShm.id
3214**
3215** All other fields are read/write. The unixShm.pFile->mutex must be held
3216** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003217*/
3218struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003219 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3220 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003221 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003222 u16 sharedMask; /* Mask of shared locks held */
3223 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003224#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003225 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003226#endif
3227};
3228
3229/*
drhd9e5c4f2010-05-12 18:01:39 +00003230** Constants used for locking
3231*/
drhbd9676c2010-06-23 17:58:38 +00003232#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003233#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003234
drhd9e5c4f2010-05-12 18:01:39 +00003235/*
drh73b64e42010-05-30 19:55:15 +00003236** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003237**
3238** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3239** otherwise.
3240*/
3241static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003242 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3243 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003244 int ofst, /* First byte of the locking range */
3245 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003246){
3247 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003248 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003249
drhd91c68f2010-05-14 14:52:25 +00003250 /* Access to the unixShmNode object is serialized by the caller */
3251 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003252
drh73b64e42010-05-30 19:55:15 +00003253 /* Shared locks never span more than one byte */
3254 assert( n==1 || lockType!=F_RDLCK );
3255
3256 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003257 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003258
drhd9e5c4f2010-05-12 18:01:39 +00003259 /* Initialize the locking parameters */
3260 memset(&f, 0, sizeof(f));
3261 f.l_type = lockType;
3262 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003263 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003264 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003265
drh73b64e42010-05-30 19:55:15 +00003266 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003267 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3268
3269 /* Update the global lock state and do debug tracing */
3270#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003271 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003272 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003273 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003274 if( rc==SQLITE_OK ){
3275 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003276 OSTRACE(("unlock %d ok", ofst));
3277 pShmNode->exclMask &= ~mask;
3278 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003279 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003280 OSTRACE(("read-lock %d ok", ofst));
3281 pShmNode->exclMask &= ~mask;
3282 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003283 }else{
3284 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003285 OSTRACE(("write-lock %d ok", ofst));
3286 pShmNode->exclMask |= mask;
3287 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003288 }
3289 }else{
3290 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003291 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003292 }else if( lockType==F_RDLCK ){
3293 OSTRACE(("read-lock failed"));
3294 }else{
3295 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003296 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003297 }
3298 }
drh20e1f082010-05-31 16:10:12 +00003299 OSTRACE((" - afterwards %03x,%03x\n",
3300 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003301 }
drhd9e5c4f2010-05-12 18:01:39 +00003302#endif
3303
3304 return rc;
3305}
3306
drhd9e5c4f2010-05-12 18:01:39 +00003307
3308/*
drhd91c68f2010-05-14 14:52:25 +00003309** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003310**
3311** This is not a VFS shared-memory method; it is a utility function called
3312** by VFS shared-memory methods.
3313*/
drhd91c68f2010-05-14 14:52:25 +00003314static void unixShmPurge(unixFile *pFd){
3315 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003316 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003317 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003318 int i;
drhd91c68f2010-05-14 14:52:25 +00003319 assert( p->pInode==pFd->pInode );
3320 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003321 for(i=0; i<p->nRegion; i++){
3322 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003323 }
dan18801912010-06-14 14:07:50 +00003324 sqlite3_free(p->apRegion);
drhd91c68f2010-05-14 14:52:25 +00003325 if( p->h>=0 ) close(p->h);
3326 p->pInode->pShmNode = 0;
3327 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003328 }
3329}
3330
3331/*
danda9fe0c2010-07-13 18:44:03 +00003332** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003333** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003334**
drh7234c6d2010-06-19 15:10:09 +00003335** The file used to implement shared-memory is in the same directory
3336** as the open database file and has the same name as the open database
3337** file with the "-shm" suffix added. For example, if the database file
3338** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003339** for shared memory will be called "/home/user1/config.db-shm".
3340**
3341** Another approach to is to use files in /dev/shm or /dev/tmp or an
3342** some other tmpfs mount. But if a file in a different directory
3343** from the database file is used, then differing access permissions
3344** or a chroot() might cause two different processes on the same
3345** database to end up using different files for shared memory -
3346** meaning that their memory would not really be shared - resulting
3347** in database corruption. Nevertheless, this tmpfs file usage
3348** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3349** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3350** option results in an incompatible build of SQLite; builds of SQLite
3351** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3352** same database file at the same time, database corruption will likely
3353** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3354** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003355**
3356** When opening a new shared-memory file, if no other instances of that
3357** file are currently open, in this process or in other processes, then
3358** the file must be truncated to zero length or have its header cleared.
3359*/
danda9fe0c2010-07-13 18:44:03 +00003360static int unixOpenSharedMemory(unixFile *pDbFd){
3361 struct unixShm *p = 0; /* The connection to be opened */
3362 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3363 int rc; /* Result code */
3364 unixInodeInfo *pInode; /* The inode of fd */
3365 char *zShmFilename; /* Name of the file used for SHM */
3366 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003367
danda9fe0c2010-07-13 18:44:03 +00003368 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003369 p = sqlite3_malloc( sizeof(*p) );
3370 if( p==0 ) return SQLITE_NOMEM;
3371 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003372 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003373
danda9fe0c2010-07-13 18:44:03 +00003374 /* Check to see if a unixShmNode object already exists. Reuse an existing
3375 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003376 */
3377 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003378 pInode = pDbFd->pInode;
3379 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003380 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003381 struct stat sStat; /* fstat() info for database file */
3382
3383 /* Call fstat() to figure out the permissions on the database file. If
3384 ** a new *-shm file is created, an attempt will be made to create it
3385 ** with the same permissions. The actual permissions the file is created
3386 ** with are subject to the current umask setting.
3387 */
3388 if( fstat(pDbFd->h, &sStat) ){
3389 rc = SQLITE_IOERR_FSTAT;
3390 goto shm_open_err;
3391 }
3392
drha4ced192010-07-15 18:32:40 +00003393#ifdef SQLITE_SHM_DIRECTORY
3394 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3395#else
drh7234c6d2010-06-19 15:10:09 +00003396 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003397#endif
drh7234c6d2010-06-19 15:10:09 +00003398 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003399 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003400 rc = SQLITE_NOMEM;
3401 goto shm_open_err;
3402 }
drhd91c68f2010-05-14 14:52:25 +00003403 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003404 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003405#ifdef SQLITE_SHM_DIRECTORY
3406 sqlite3_snprintf(nShmFilename, zShmFilename,
3407 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3408 (u32)sStat.st_ino, (u32)sStat.st_dev);
3409#else
drh7234c6d2010-06-19 15:10:09 +00003410 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003411#endif
drhd91c68f2010-05-14 14:52:25 +00003412 pShmNode->h = -1;
3413 pDbFd->pInode->pShmNode = pShmNode;
3414 pShmNode->pInode = pDbFd->pInode;
3415 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3416 if( pShmNode->mutex==0 ){
3417 rc = SQLITE_NOMEM;
3418 goto shm_open_err;
3419 }
drhd9e5c4f2010-05-12 18:01:39 +00003420
danddb0ac42010-07-14 14:48:58 +00003421 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003422 if( pShmNode->h<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003423 rc = SQLITE_CANTOPEN_BKPT;
3424 goto shm_open_err;
3425 }
3426
drhd9e5c4f2010-05-12 18:01:39 +00003427 /* Check to see if another process is holding the dead-man switch.
3428 ** If not, truncate the file to zero length.
3429 */
drhd91c68f2010-05-14 14:52:25 +00003430 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003431 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhd91c68f2010-05-14 14:52:25 +00003432 if( ftruncate(pShmNode->h, 0) ){
drhaab4c022010-06-02 14:45:51 +00003433 rc = SQLITE_IOERR_SHMOPEN;
drhd9e5c4f2010-05-12 18:01:39 +00003434 }
3435 }
3436 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003437 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003438 }
3439 if( rc ) goto shm_open_err;
3440 }
3441
drhd91c68f2010-05-14 14:52:25 +00003442 /* Make the new connection a child of the unixShmNode */
3443 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003444#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003445 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003446#endif
drhd91c68f2010-05-14 14:52:25 +00003447 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003448 pDbFd->pShm = p;
3449 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003450
3451 /* The reference count on pShmNode has already been incremented under
3452 ** the cover of the unixEnterMutex() mutex and the pointer from the
3453 ** new (struct unixShm) object to the pShmNode has been set. All that is
3454 ** left to do is to link the new object into the linked list starting
3455 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3456 ** mutex.
3457 */
3458 sqlite3_mutex_enter(pShmNode->mutex);
3459 p->pNext = pShmNode->pFirst;
3460 pShmNode->pFirst = p;
3461 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003462 return SQLITE_OK;
3463
3464 /* Jump here on any error */
3465shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003466 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003467 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003468 unixLeaveMutex();
3469 return rc;
3470}
3471
3472/*
danda9fe0c2010-07-13 18:44:03 +00003473** This function is called to obtain a pointer to region iRegion of the
3474** shared-memory associated with the database file fd. Shared-memory regions
3475** are numbered starting from zero. Each shared-memory region is szRegion
3476** bytes in size.
3477**
3478** If an error occurs, an error code is returned and *pp is set to NULL.
3479**
3480** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3481** region has not been allocated (by any client, including one running in a
3482** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3483** bExtend is non-zero and the requested shared-memory region has not yet
3484** been allocated, it is allocated by this function.
3485**
3486** If the shared-memory region has already been allocated or is allocated by
3487** this call as described above, then it is mapped into this processes
3488** address space (if it is not already), *pp is set to point to the mapped
3489** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003490*/
danda9fe0c2010-07-13 18:44:03 +00003491static int unixShmMap(
3492 sqlite3_file *fd, /* Handle open on database file */
3493 int iRegion, /* Region to retrieve */
3494 int szRegion, /* Size of regions */
3495 int bExtend, /* True to extend file if necessary */
3496 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003497){
danda9fe0c2010-07-13 18:44:03 +00003498 unixFile *pDbFd = (unixFile*)fd;
3499 unixShm *p;
3500 unixShmNode *pShmNode;
3501 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003502
danda9fe0c2010-07-13 18:44:03 +00003503 /* If the shared-memory file has not yet been opened, open it now. */
3504 if( pDbFd->pShm==0 ){
3505 rc = unixOpenSharedMemory(pDbFd);
3506 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003507 }
drhd9e5c4f2010-05-12 18:01:39 +00003508
danda9fe0c2010-07-13 18:44:03 +00003509 p = pDbFd->pShm;
3510 pShmNode = p->pShmNode;
3511 sqlite3_mutex_enter(pShmNode->mutex);
3512 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3513
3514 if( pShmNode->nRegion<=iRegion ){
3515 char **apNew; /* New apRegion[] array */
3516 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3517 struct stat sStat; /* Used by fstat() */
3518
3519 pShmNode->szRegion = szRegion;
3520
3521 /* The requested region is not mapped into this processes address space.
3522 ** Check to see if it has been allocated (i.e. if the wal-index file is
3523 ** large enough to contain the requested region).
3524 */
3525 if( fstat(pShmNode->h, &sStat) ){
3526 rc = SQLITE_IOERR_SHMSIZE;
3527 goto shmpage_out;
3528 }
3529
3530 if( sStat.st_size<nByte ){
3531 /* The requested memory region does not exist. If bExtend is set to
3532 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3533 **
3534 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3535 ** the requested memory region.
3536 */
3537 if( !bExtend ) goto shmpage_out;
3538 if( ftruncate(pShmNode->h, nByte) ){
3539 rc = SQLITE_IOERR_SHMSIZE;
3540 goto shmpage_out;
3541 }
3542 }
3543
3544 /* Map the requested memory region into this processes address space. */
3545 apNew = (char **)sqlite3_realloc(
3546 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3547 );
3548 if( !apNew ){
3549 rc = SQLITE_IOERR_NOMEM;
3550 goto shmpage_out;
3551 }
3552 pShmNode->apRegion = apNew;
3553 while(pShmNode->nRegion<=iRegion){
3554 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3555 MAP_SHARED, pShmNode->h, iRegion*szRegion
3556 );
3557 if( pMem==MAP_FAILED ){
3558 rc = SQLITE_IOERR;
3559 goto shmpage_out;
3560 }
3561 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3562 pShmNode->nRegion++;
3563 }
3564 }
3565
3566shmpage_out:
3567 if( pShmNode->nRegion>iRegion ){
3568 *pp = pShmNode->apRegion[iRegion];
3569 }else{
3570 *pp = 0;
3571 }
3572 sqlite3_mutex_leave(pShmNode->mutex);
3573 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003574}
3575
3576/*
drhd9e5c4f2010-05-12 18:01:39 +00003577** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003578**
3579** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3580** different here than in posix. In xShmLock(), one can go from unlocked
3581** to shared and back or from unlocked to exclusive and back. But one may
3582** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003583*/
3584static int unixShmLock(
3585 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003586 int ofst, /* First lock to acquire or release */
3587 int n, /* Number of locks to acquire or release */
3588 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003589){
drh73b64e42010-05-30 19:55:15 +00003590 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3591 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3592 unixShm *pX; /* For looping over all siblings */
3593 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3594 int rc = SQLITE_OK; /* Result code */
3595 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003596
drhd91c68f2010-05-14 14:52:25 +00003597 assert( pShmNode==pDbFd->pInode->pShmNode );
3598 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003599 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003600 assert( n>=1 );
3601 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3602 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3603 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3604 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3605 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003606
drhc99597c2010-05-31 01:41:15 +00003607 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003608 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003609 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003610 if( flags & SQLITE_SHM_UNLOCK ){
3611 u16 allMask = 0; /* Mask of locks held by siblings */
3612
3613 /* See if any siblings hold this same lock */
3614 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3615 if( pX==p ) continue;
3616 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3617 allMask |= pX->sharedMask;
3618 }
3619
3620 /* Unlock the system-level locks */
3621 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003622 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003623 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003624 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003625 }
drh73b64e42010-05-30 19:55:15 +00003626
3627 /* Undo the local locks */
3628 if( rc==SQLITE_OK ){
3629 p->exclMask &= ~mask;
3630 p->sharedMask &= ~mask;
3631 }
3632 }else if( flags & SQLITE_SHM_SHARED ){
3633 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3634
3635 /* Find out which shared locks are already held by sibling connections.
3636 ** If any sibling already holds an exclusive lock, go ahead and return
3637 ** SQLITE_BUSY.
3638 */
3639 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003640 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003641 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003642 break;
3643 }
3644 allShared |= pX->sharedMask;
3645 }
3646
3647 /* Get shared locks at the system level, if necessary */
3648 if( rc==SQLITE_OK ){
3649 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003650 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003651 }else{
drh73b64e42010-05-30 19:55:15 +00003652 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003653 }
drhd9e5c4f2010-05-12 18:01:39 +00003654 }
drh73b64e42010-05-30 19:55:15 +00003655
3656 /* Get the local shared locks */
3657 if( rc==SQLITE_OK ){
3658 p->sharedMask |= mask;
3659 }
3660 }else{
3661 /* Make sure no sibling connections hold locks that will block this
3662 ** lock. If any do, return SQLITE_BUSY right away.
3663 */
3664 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003665 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3666 rc = SQLITE_BUSY;
3667 break;
3668 }
3669 }
3670
3671 /* Get the exclusive locks at the system level. Then if successful
3672 ** also mark the local connection as being locked.
3673 */
3674 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003675 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003676 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003677 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003678 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003679 }
drhd9e5c4f2010-05-12 18:01:39 +00003680 }
3681 }
drhd91c68f2010-05-14 14:52:25 +00003682 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003683 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3684 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003685 return rc;
3686}
3687
drh286a2882010-05-20 23:51:06 +00003688/*
3689** Implement a memory barrier or memory fence on shared memory.
3690**
3691** All loads and stores begun before the barrier must complete before
3692** any load or store begun after the barrier.
3693*/
3694static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003695 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003696){
drhff828942010-06-26 21:34:06 +00003697 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003698 unixEnterMutex();
3699 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003700}
3701
dan18801912010-06-14 14:07:50 +00003702/*
danda9fe0c2010-07-13 18:44:03 +00003703** Close a connection to shared-memory. Delete the underlying
3704** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003705**
3706** If there is no shared memory associated with the connection then this
3707** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003708*/
danda9fe0c2010-07-13 18:44:03 +00003709static int unixShmUnmap(
3710 sqlite3_file *fd, /* The underlying database file */
3711 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003712){
danda9fe0c2010-07-13 18:44:03 +00003713 unixShm *p; /* The connection to be closed */
3714 unixShmNode *pShmNode; /* The underlying shared-memory file */
3715 unixShm **pp; /* For looping over sibling connections */
3716 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003717
danda9fe0c2010-07-13 18:44:03 +00003718 pDbFd = (unixFile*)fd;
3719 p = pDbFd->pShm;
3720 if( p==0 ) return SQLITE_OK;
3721 pShmNode = p->pShmNode;
3722
3723 assert( pShmNode==pDbFd->pInode->pShmNode );
3724 assert( pShmNode->pInode==pDbFd->pInode );
3725
3726 /* Remove connection p from the set of connections associated
3727 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003728 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003729 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3730 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003731
danda9fe0c2010-07-13 18:44:03 +00003732 /* Free the connection p */
3733 sqlite3_free(p);
3734 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003735 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003736
3737 /* If pShmNode->nRef has reached 0, then close the underlying
3738 ** shared-memory file, too */
3739 unixEnterMutex();
3740 assert( pShmNode->nRef>0 );
3741 pShmNode->nRef--;
3742 if( pShmNode->nRef==0 ){
3743 if( deleteFlag ) unlink(pShmNode->zFilename);
3744 unixShmPurge(pDbFd);
3745 }
3746 unixLeaveMutex();
3747
3748 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003749}
drh286a2882010-05-20 23:51:06 +00003750
danda9fe0c2010-07-13 18:44:03 +00003751
drhd9e5c4f2010-05-12 18:01:39 +00003752#else
drh6b017cc2010-06-14 18:01:46 +00003753# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003754# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003755# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003756# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003757#endif /* #ifndef SQLITE_OMIT_WAL */
3758
drh734c9862008-11-28 15:37:20 +00003759/*
3760** Here ends the implementation of all sqlite3_file methods.
3761**
3762********************** End sqlite3_file Methods *******************************
3763******************************************************************************/
3764
3765/*
drh6b9d6dd2008-12-03 19:34:47 +00003766** This division contains definitions of sqlite3_io_methods objects that
3767** implement various file locking strategies. It also contains definitions
3768** of "finder" functions. A finder-function is used to locate the appropriate
3769** sqlite3_io_methods object for a particular database file. The pAppData
3770** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3771** the correct finder-function for that VFS.
3772**
3773** Most finder functions return a pointer to a fixed sqlite3_io_methods
3774** object. The only interesting finder-function is autolockIoFinder, which
3775** looks at the filesystem type and tries to guess the best locking
3776** strategy from that.
3777**
drh1875f7a2008-12-08 18:19:17 +00003778** For finder-funtion F, two objects are created:
3779**
3780** (1) The real finder-function named "FImpt()".
3781**
dane946c392009-08-22 11:39:46 +00003782** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003783**
3784**
3785** A pointer to the F pointer is used as the pAppData value for VFS
3786** objects. We have to do this instead of letting pAppData point
3787** directly at the finder-function since C90 rules prevent a void*
3788** from be cast into a function pointer.
3789**
drh6b9d6dd2008-12-03 19:34:47 +00003790**
drh7708e972008-11-29 00:56:52 +00003791** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003792**
drh7708e972008-11-29 00:56:52 +00003793** * A constant sqlite3_io_methods object call METHOD that has locking
3794** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3795**
3796** * An I/O method finder function called FINDER that returns a pointer
3797** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003798*/
drhd9e5c4f2010-05-12 18:01:39 +00003799#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003800static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003801 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003802 CLOSE, /* xClose */ \
3803 unixRead, /* xRead */ \
3804 unixWrite, /* xWrite */ \
3805 unixTruncate, /* xTruncate */ \
3806 unixSync, /* xSync */ \
3807 unixFileSize, /* xFileSize */ \
3808 LOCK, /* xLock */ \
3809 UNLOCK, /* xUnlock */ \
3810 CKLOCK, /* xCheckReservedLock */ \
3811 unixFileControl, /* xFileControl */ \
3812 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003813 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003814 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00003815 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003816 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00003817 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00003818}; \
drh0c2694b2009-09-03 16:23:44 +00003819static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3820 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003821 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003822} \
drh0c2694b2009-09-03 16:23:44 +00003823static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003824 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003825
3826/*
3827** Here are all of the sqlite3_io_methods objects for each of the
3828** locking strategies. Functions that return pointers to these methods
3829** are also created.
3830*/
3831IOMETHODS(
3832 posixIoFinder, /* Finder function name */
3833 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003834 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00003835 unixClose, /* xClose method */
3836 unixLock, /* xLock method */
3837 unixUnlock, /* xUnlock method */
3838 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003839)
drh7708e972008-11-29 00:56:52 +00003840IOMETHODS(
3841 nolockIoFinder, /* Finder function name */
3842 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003843 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003844 nolockClose, /* xClose method */
3845 nolockLock, /* xLock method */
3846 nolockUnlock, /* xUnlock method */
3847 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003848)
drh7708e972008-11-29 00:56:52 +00003849IOMETHODS(
3850 dotlockIoFinder, /* Finder function name */
3851 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003852 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003853 dotlockClose, /* xClose method */
3854 dotlockLock, /* xLock method */
3855 dotlockUnlock, /* xUnlock method */
3856 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003857)
drh7708e972008-11-29 00:56:52 +00003858
chw78a13182009-04-07 05:35:03 +00003859#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003860IOMETHODS(
3861 flockIoFinder, /* Finder function name */
3862 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003863 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003864 flockClose, /* xClose method */
3865 flockLock, /* xLock method */
3866 flockUnlock, /* xUnlock method */
3867 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003868)
drh7708e972008-11-29 00:56:52 +00003869#endif
3870
drh6c7d5c52008-11-21 20:32:33 +00003871#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003872IOMETHODS(
3873 semIoFinder, /* Finder function name */
3874 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003875 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003876 semClose, /* xClose method */
3877 semLock, /* xLock method */
3878 semUnlock, /* xUnlock method */
3879 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003880)
aswiftaebf4132008-11-21 00:10:35 +00003881#endif
drh7708e972008-11-29 00:56:52 +00003882
drhd2cb50b2009-01-09 21:41:17 +00003883#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003884IOMETHODS(
3885 afpIoFinder, /* Finder function name */
3886 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003887 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003888 afpClose, /* xClose method */
3889 afpLock, /* xLock method */
3890 afpUnlock, /* xUnlock method */
3891 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003892)
drh715ff302008-12-03 22:32:44 +00003893#endif
3894
3895/*
3896** The proxy locking method is a "super-method" in the sense that it
3897** opens secondary file descriptors for the conch and lock files and
3898** it uses proxy, dot-file, AFP, and flock() locking methods on those
3899** secondary files. For this reason, the division that implements
3900** proxy locking is located much further down in the file. But we need
3901** to go ahead and define the sqlite3_io_methods and finder function
3902** for proxy locking here. So we forward declare the I/O methods.
3903*/
drhd2cb50b2009-01-09 21:41:17 +00003904#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003905static int proxyClose(sqlite3_file*);
3906static int proxyLock(sqlite3_file*, int);
3907static int proxyUnlock(sqlite3_file*, int);
3908static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003909IOMETHODS(
3910 proxyIoFinder, /* Finder function name */
3911 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003912 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003913 proxyClose, /* xClose method */
3914 proxyLock, /* xLock method */
3915 proxyUnlock, /* xUnlock method */
3916 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003917)
aswiftaebf4132008-11-21 00:10:35 +00003918#endif
drh7708e972008-11-29 00:56:52 +00003919
drh7ed97b92010-01-20 13:07:21 +00003920/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3921#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3922IOMETHODS(
3923 nfsIoFinder, /* Finder function name */
3924 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003925 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00003926 unixClose, /* xClose method */
3927 unixLock, /* xLock method */
3928 nfsUnlock, /* xUnlock method */
3929 unixCheckReservedLock /* xCheckReservedLock method */
3930)
3931#endif
drh7708e972008-11-29 00:56:52 +00003932
drhd2cb50b2009-01-09 21:41:17 +00003933#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003934/*
drh6b9d6dd2008-12-03 19:34:47 +00003935** This "finder" function attempts to determine the best locking strategy
3936** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003937** object that implements that strategy.
3938**
3939** This is for MacOSX only.
3940*/
drh1875f7a2008-12-08 18:19:17 +00003941static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003942 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003943 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003944){
3945 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003946 const char *zFilesystem; /* Filesystem type name */
3947 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003948 } aMap[] = {
3949 { "hfs", &posixIoMethods },
3950 { "ufs", &posixIoMethods },
3951 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003952 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003953 { "webdav", &nolockIoMethods },
3954 { 0, 0 }
3955 };
3956 int i;
3957 struct statfs fsInfo;
3958 struct flock lockInfo;
3959
3960 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003961 /* If filePath==NULL that means we are dealing with a transient file
3962 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003963 return &nolockIoMethods;
3964 }
3965 if( statfs(filePath, &fsInfo) != -1 ){
3966 if( fsInfo.f_flags & MNT_RDONLY ){
3967 return &nolockIoMethods;
3968 }
3969 for(i=0; aMap[i].zFilesystem; i++){
3970 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3971 return aMap[i].pMethods;
3972 }
3973 }
3974 }
3975
3976 /* Default case. Handles, amongst others, "nfs".
3977 ** Test byte-range lock using fcntl(). If the call succeeds,
3978 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003979 */
drh7708e972008-11-29 00:56:52 +00003980 lockInfo.l_len = 1;
3981 lockInfo.l_start = 0;
3982 lockInfo.l_whence = SEEK_SET;
3983 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003984 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003985 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3986 return &nfsIoMethods;
3987 } else {
3988 return &posixIoMethods;
3989 }
drh7708e972008-11-29 00:56:52 +00003990 }else{
3991 return &dotlockIoMethods;
3992 }
3993}
drh0c2694b2009-09-03 16:23:44 +00003994static const sqlite3_io_methods
3995 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003996
drhd2cb50b2009-01-09 21:41:17 +00003997#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003998
chw78a13182009-04-07 05:35:03 +00003999#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4000/*
4001** This "finder" function attempts to determine the best locking strategy
4002** for the database file "filePath". It then returns the sqlite3_io_methods
4003** object that implements that strategy.
4004**
4005** This is for VXWorks only.
4006*/
4007static const sqlite3_io_methods *autolockIoFinderImpl(
4008 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004009 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004010){
4011 struct flock lockInfo;
4012
4013 if( !filePath ){
4014 /* If filePath==NULL that means we are dealing with a transient file
4015 ** that does not need to be locked. */
4016 return &nolockIoMethods;
4017 }
4018
4019 /* Test if fcntl() is supported and use POSIX style locks.
4020 ** Otherwise fall back to the named semaphore method.
4021 */
4022 lockInfo.l_len = 1;
4023 lockInfo.l_start = 0;
4024 lockInfo.l_whence = SEEK_SET;
4025 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004026 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004027 return &posixIoMethods;
4028 }else{
4029 return &semIoMethods;
4030 }
4031}
drh0c2694b2009-09-03 16:23:44 +00004032static const sqlite3_io_methods
4033 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004034
4035#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4036
drh7708e972008-11-29 00:56:52 +00004037/*
4038** An abstract type for a pointer to a IO method finder function:
4039*/
drh0c2694b2009-09-03 16:23:44 +00004040typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004041
aswiftaebf4132008-11-21 00:10:35 +00004042
drh734c9862008-11-28 15:37:20 +00004043/****************************************************************************
4044**************************** sqlite3_vfs methods ****************************
4045**
4046** This division contains the implementation of methods on the
4047** sqlite3_vfs object.
4048*/
4049
danielk1977a3d4c882007-03-23 10:08:38 +00004050/*
danielk1977e339d652008-06-28 11:23:00 +00004051** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004052*/
4053static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004054 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004055 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004056 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004057 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004058 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004059 int noLock, /* Omit locking if true */
4060 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004061){
drh7708e972008-11-29 00:56:52 +00004062 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004063 unixFile *pNew = (unixFile *)pId;
4064 int rc = SQLITE_OK;
4065
drh8af6c222010-05-14 12:43:01 +00004066 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004067
dane946c392009-08-22 11:39:46 +00004068 /* Parameter isDelete is only used on vxworks. Express this explicitly
4069 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004070 */
drh7708e972008-11-29 00:56:52 +00004071 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004072
drh308c2a52010-05-14 11:30:18 +00004073 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004074 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004075 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004076 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004077 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
4078 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004079
drh6c7d5c52008-11-21 20:32:33 +00004080#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004081 pNew->pId = vxworksFindFileId(zFilename);
4082 if( pNew->pId==0 ){
4083 noLock = 1;
4084 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004085 }
4086#endif
4087
drhda0e7682008-07-30 15:27:54 +00004088 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004089 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004090 }else{
drh0c2694b2009-09-03 16:23:44 +00004091 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004092#if SQLITE_ENABLE_LOCKING_STYLE
4093 /* Cache zFilename in the locking context (AFP and dotlock override) for
4094 ** proxyLock activation is possible (remote proxy is based on db name)
4095 ** zFilename remains valid until file is closed, to support */
4096 pNew->lockingContext = (void*)zFilename;
4097#endif
drhda0e7682008-07-30 15:27:54 +00004098 }
danielk1977e339d652008-06-28 11:23:00 +00004099
drh7ed97b92010-01-20 13:07:21 +00004100 if( pLockingStyle == &posixIoMethods
4101#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4102 || pLockingStyle == &nfsIoMethods
4103#endif
4104 ){
drh7708e972008-11-29 00:56:52 +00004105 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004106 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004107 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004108 /* If an error occured in findInodeInfo(), close the file descriptor
4109 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004110 ** in two scenarios:
4111 **
4112 ** (a) A call to fstat() failed.
4113 ** (b) A malloc failed.
4114 **
4115 ** Scenario (b) may only occur if the process is holding no other
4116 ** file descriptors open on the same file. If there were other file
4117 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004118 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004119 ** handle h - as it is guaranteed that no posix locks will be released
4120 ** by doing so.
4121 **
4122 ** If scenario (a) caused the error then things are not so safe. The
4123 ** implicit assumption here is that if fstat() fails, things are in
4124 ** such bad shape that dropping a lock or two doesn't matter much.
4125 */
4126 close(h);
4127 h = -1;
4128 }
drh7708e972008-11-29 00:56:52 +00004129 unixLeaveMutex();
4130 }
danielk1977e339d652008-06-28 11:23:00 +00004131
drhd2cb50b2009-01-09 21:41:17 +00004132#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004133 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004134 /* AFP locking uses the file path so it needs to be included in
4135 ** the afpLockingContext.
4136 */
4137 afpLockingContext *pCtx;
4138 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4139 if( pCtx==0 ){
4140 rc = SQLITE_NOMEM;
4141 }else{
4142 /* NB: zFilename exists and remains valid until the file is closed
4143 ** according to requirement F11141. So we do not need to make a
4144 ** copy of the filename. */
4145 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004146 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004147 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004148 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004149 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004150 if( rc!=SQLITE_OK ){
4151 sqlite3_free(pNew->lockingContext);
4152 close(h);
4153 h = -1;
4154 }
drh7708e972008-11-29 00:56:52 +00004155 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004156 }
drh7708e972008-11-29 00:56:52 +00004157 }
4158#endif
danielk1977e339d652008-06-28 11:23:00 +00004159
drh7708e972008-11-29 00:56:52 +00004160 else if( pLockingStyle == &dotlockIoMethods ){
4161 /* Dotfile locking uses the file path so it needs to be included in
4162 ** the dotlockLockingContext
4163 */
4164 char *zLockFile;
4165 int nFilename;
drhea678832008-12-10 19:26:22 +00004166 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004167 zLockFile = (char *)sqlite3_malloc(nFilename);
4168 if( zLockFile==0 ){
4169 rc = SQLITE_NOMEM;
4170 }else{
4171 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004172 }
drh7708e972008-11-29 00:56:52 +00004173 pNew->lockingContext = zLockFile;
4174 }
danielk1977e339d652008-06-28 11:23:00 +00004175
drh6c7d5c52008-11-21 20:32:33 +00004176#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004177 else if( pLockingStyle == &semIoMethods ){
4178 /* Named semaphore locking uses the file path so it needs to be
4179 ** included in the semLockingContext
4180 */
4181 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004182 rc = findInodeInfo(pNew, &pNew->pInode);
4183 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4184 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004185 int n;
drh2238dcc2009-08-27 17:56:20 +00004186 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004187 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004188 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004189 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004190 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4191 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004192 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004193 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004194 }
chw97185482008-11-17 08:05:31 +00004195 }
drh7708e972008-11-29 00:56:52 +00004196 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004197 }
drh7708e972008-11-29 00:56:52 +00004198#endif
aswift5b1a2562008-08-22 00:22:35 +00004199
4200 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004201#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004202 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004203 if( h>=0 ) close(h);
4204 h = -1;
chw97185482008-11-17 08:05:31 +00004205 unlink(zFilename);
4206 isDelete = 0;
4207 }
4208 pNew->isDelete = isDelete;
4209#endif
danielk1977e339d652008-06-28 11:23:00 +00004210 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004211 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004212 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004213 }else{
drh7708e972008-11-29 00:56:52 +00004214 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004215 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004216 }
danielk1977e339d652008-06-28 11:23:00 +00004217 return rc;
drh054889e2005-11-30 03:20:31 +00004218}
drh9c06c952005-11-26 00:25:00 +00004219
danielk1977ad94b582007-08-20 06:44:22 +00004220/*
4221** Open a file descriptor to the directory containing file zFilename.
4222** If successful, *pFd is set to the opened file descriptor and
4223** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4224** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4225** value.
4226**
4227** If SQLITE_OK is returned, the caller is responsible for closing
4228** the file descriptor *pFd using close().
4229*/
danielk1977fee2d252007-08-18 10:59:19 +00004230static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004231 int ii;
drh777b17a2007-09-20 10:02:54 +00004232 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004233 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004234
drh153c62c2007-08-24 03:51:33 +00004235 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004236 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004237 if( ii>0 ){
4238 zDirname[ii] = '\0';
4239 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004240 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004241#ifdef FD_CLOEXEC
4242 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4243#endif
drh308c2a52010-05-14 11:30:18 +00004244 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004245 }
4246 }
danielk1977fee2d252007-08-18 10:59:19 +00004247 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004248 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004249}
4250
danielk1977b4b47412007-08-17 15:53:36 +00004251/*
drh8b3cf822010-06-01 21:02:51 +00004252** Return the name of a directory in which to put temporary files.
4253** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004254*/
drh7234c6d2010-06-19 15:10:09 +00004255static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004256 static const char *azDirs[] = {
4257 0,
aswiftaebf4132008-11-21 00:10:35 +00004258 0,
danielk197717b90b52008-06-06 11:11:25 +00004259 "/var/tmp",
4260 "/usr/tmp",
4261 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004262 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004263 };
drh8b3cf822010-06-01 21:02:51 +00004264 unsigned int i;
4265 struct stat buf;
4266 const char *zDir = 0;
4267
4268 azDirs[0] = sqlite3_temp_directory;
4269 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004270 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004271 if( zDir==0 ) continue;
4272 if( stat(zDir, &buf) ) continue;
4273 if( !S_ISDIR(buf.st_mode) ) continue;
drh7234c6d2010-06-19 15:10:09 +00004274 if( access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004275 break;
4276 }
4277 return zDir;
4278}
4279
4280/*
4281** Create a temporary file name in zBuf. zBuf must be allocated
4282** by the calling process and must be big enough to hold at least
4283** pVfs->mxPathname bytes.
4284*/
4285static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004286 static const unsigned char zChars[] =
4287 "abcdefghijklmnopqrstuvwxyz"
4288 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4289 "0123456789";
drh41022642008-11-21 00:24:42 +00004290 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004291 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004292
4293 /* It's odd to simulate an io-error here, but really this is just
4294 ** using the io-error infrastructure to test that SQLite handles this
4295 ** function failing.
4296 */
4297 SimulateIOError( return SQLITE_IOERR );
4298
drh7234c6d2010-06-19 15:10:09 +00004299 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004300 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004301
4302 /* Check that the output buffer is large enough for the temporary file
4303 ** name. If it is not, return SQLITE_ERROR.
4304 */
danielk197700e13612008-11-17 19:18:54 +00004305 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004306 return SQLITE_ERROR;
4307 }
4308
4309 do{
4310 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004311 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004312 sqlite3_randomness(15, &zBuf[j]);
4313 for(i=0; i<15; i++, j++){
4314 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4315 }
4316 zBuf[j] = 0;
4317 }while( access(zBuf,0)==0 );
4318 return SQLITE_OK;
4319}
4320
drhd2cb50b2009-01-09 21:41:17 +00004321#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004322/*
4323** Routine to transform a unixFile into a proxy-locking unixFile.
4324** Implementation in the proxy-lock division, but used by unixOpen()
4325** if SQLITE_PREFER_PROXY_LOCKING is defined.
4326*/
4327static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004328#endif
drhc66d5b62008-12-03 22:48:32 +00004329
dan08da86a2009-08-21 17:18:03 +00004330/*
4331** Search for an unused file descriptor that was opened on the database
4332** file (not a journal or master-journal file) identified by pathname
4333** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4334** argument to this function.
4335**
4336** Such a file descriptor may exist if a database connection was closed
4337** but the associated file descriptor could not be closed because some
4338** other file descriptor open on the same file is holding a file-lock.
4339** Refer to comments in the unixClose() function and the lengthy comment
4340** describing "Posix Advisory Locking" at the start of this file for
4341** further details. Also, ticket #4018.
4342**
4343** If a suitable file descriptor is found, then it is returned. If no
4344** such file descriptor is located, -1 is returned.
4345*/
dane946c392009-08-22 11:39:46 +00004346static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4347 UnixUnusedFd *pUnused = 0;
4348
4349 /* Do not search for an unused file descriptor on vxworks. Not because
4350 ** vxworks would not benefit from the change (it might, we're not sure),
4351 ** but because no way to test it is currently available. It is better
4352 ** not to risk breaking vxworks support for the sake of such an obscure
4353 ** feature. */
4354#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004355 struct stat sStat; /* Results of stat() call */
4356
4357 /* A stat() call may fail for various reasons. If this happens, it is
4358 ** almost certain that an open() call on the same path will also fail.
4359 ** For this reason, if an error occurs in the stat() call here, it is
4360 ** ignored and -1 is returned. The caller will try to open a new file
4361 ** descriptor on the same path, fail, and return an error to SQLite.
4362 **
4363 ** Even if a subsequent open() call does succeed, the consequences of
4364 ** not searching for a resusable file descriptor are not dire. */
4365 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004366 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004367
4368 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004369 pInode = inodeList;
4370 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4371 || pInode->fileId.ino!=sStat.st_ino) ){
4372 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004373 }
drh8af6c222010-05-14 12:43:01 +00004374 if( pInode ){
dane946c392009-08-22 11:39:46 +00004375 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004376 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004377 pUnused = *pp;
4378 if( pUnused ){
4379 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004380 }
4381 }
4382 unixLeaveMutex();
4383 }
dane946c392009-08-22 11:39:46 +00004384#endif /* if !OS_VXWORKS */
4385 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004386}
danielk197717b90b52008-06-06 11:11:25 +00004387
4388/*
danddb0ac42010-07-14 14:48:58 +00004389** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004390** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004391** and a value suitable for passing as the third argument to open(2) is
4392** written to *pMode. If an IO error occurs, an SQLite error code is
4393** returned and the value of *pMode is not modified.
4394**
4395** If the file being opened is a temporary file, it is always created with
4396** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004397** is a database or master journal file, it is created with the permissions
4398** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004399**
drh8ab58662010-07-15 18:38:39 +00004400** Finally, if the file being opened is a WAL or regular journal file, then
4401** this function queries the file-system for the permissions on the
4402** corresponding database file and sets *pMode to this value. Whenever
4403** possible, WAL and journal files are created using the same permissions
4404** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004405*/
4406static int findCreateFileMode(
4407 const char *zPath, /* Path of file (possibly) being created */
4408 int flags, /* Flags passed as 4th argument to xOpen() */
4409 mode_t *pMode /* OUT: Permissions to open file with */
4410){
4411 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004412 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004413 char zDb[MAX_PATHNAME+1]; /* Database file path */
4414 int nDb; /* Number of valid bytes in zDb */
4415 struct stat sStat; /* Output of stat() on database file */
4416
drh8ab58662010-07-15 18:38:39 +00004417 nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
danddb0ac42010-07-14 14:48:58 +00004418 memcpy(zDb, zPath, nDb);
4419 zDb[nDb] = '\0';
4420 if( 0==stat(zDb, &sStat) ){
4421 *pMode = sStat.st_mode & 0777;
4422 }else{
4423 rc = SQLITE_IOERR_FSTAT;
4424 }
4425 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4426 *pMode = 0600;
4427 }else{
4428 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4429 }
4430 return rc;
4431}
4432
4433/*
danielk1977ad94b582007-08-20 06:44:22 +00004434** Open the file zPath.
4435**
danielk1977b4b47412007-08-17 15:53:36 +00004436** Previously, the SQLite OS layer used three functions in place of this
4437** one:
4438**
4439** sqlite3OsOpenReadWrite();
4440** sqlite3OsOpenReadOnly();
4441** sqlite3OsOpenExclusive();
4442**
4443** These calls correspond to the following combinations of flags:
4444**
4445** ReadWrite() -> (READWRITE | CREATE)
4446** ReadOnly() -> (READONLY)
4447** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4448**
4449** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4450** true, the file was configured to be automatically deleted when the
4451** file handle closed. To achieve the same effect using this new
4452** interface, add the DELETEONCLOSE flag to those specified above for
4453** OpenExclusive().
4454*/
4455static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004456 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4457 const char *zPath, /* Pathname of file to be opened */
4458 sqlite3_file *pFile, /* The file descriptor to be filled in */
4459 int flags, /* Input flags to control the opening */
4460 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004461){
dan08da86a2009-08-21 17:18:03 +00004462 unixFile *p = (unixFile *)pFile;
4463 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004464 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004465 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004466 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004467 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004468 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004469
4470 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4471 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4472 int isCreate = (flags & SQLITE_OPEN_CREATE);
4473 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4474 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004475#if SQLITE_ENABLE_LOCKING_STYLE
4476 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4477#endif
danielk1977b4b47412007-08-17 15:53:36 +00004478
danielk1977fee2d252007-08-18 10:59:19 +00004479 /* If creating a master or main-file journal, this function will open
4480 ** a file-descriptor on the directory too. The first time unixSync()
4481 ** is called the directory file descriptor will be fsync()ed and close()d.
4482 */
danddb0ac42010-07-14 14:48:58 +00004483 int isOpenDirectory = (isCreate && (
4484 eType==SQLITE_OPEN_MASTER_JOURNAL
4485 || eType==SQLITE_OPEN_MAIN_JOURNAL
4486 || eType==SQLITE_OPEN_WAL
4487 ));
danielk1977fee2d252007-08-18 10:59:19 +00004488
danielk197717b90b52008-06-06 11:11:25 +00004489 /* If argument zPath is a NULL pointer, this function is required to open
4490 ** a temporary file. Use this buffer to store the file name in.
4491 */
4492 char zTmpname[MAX_PATHNAME+1];
4493 const char *zName = zPath;
4494
danielk1977fee2d252007-08-18 10:59:19 +00004495 /* Check the following statements are true:
4496 **
4497 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4498 ** (b) if CREATE is set, then READWRITE must also be set, and
4499 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004500 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004501 */
danielk1977b4b47412007-08-17 15:53:36 +00004502 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004503 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004504 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004505 assert(isDelete==0 || isCreate);
4506
danddb0ac42010-07-14 14:48:58 +00004507 /* The main DB, main journal, WAL file and master journal are never
4508 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004509 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4510 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4511 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004512 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004513
danielk1977fee2d252007-08-18 10:59:19 +00004514 /* Assert that the upper layer has set one of the "file-type" flags. */
4515 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4516 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4517 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004518 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004519 );
4520
dan08da86a2009-08-21 17:18:03 +00004521 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004522
dan08da86a2009-08-21 17:18:03 +00004523 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004524 UnixUnusedFd *pUnused;
4525 pUnused = findReusableFd(zName, flags);
4526 if( pUnused ){
4527 fd = pUnused->fd;
4528 }else{
dan6aa657f2009-08-24 18:57:58 +00004529 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004530 if( !pUnused ){
4531 return SQLITE_NOMEM;
4532 }
4533 }
4534 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004535 }else if( !zName ){
4536 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004537 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004538 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004539 if( rc!=SQLITE_OK ){
4540 return rc;
4541 }
4542 zName = zTmpname;
4543 }
4544
dan08da86a2009-08-21 17:18:03 +00004545 /* Determine the value of the flags parameter passed to POSIX function
4546 ** open(). These must be calculated even if open() is not called, as
4547 ** they may be stored as part of the file handle and used by the
4548 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004549 if( isReadonly ) openFlags |= O_RDONLY;
4550 if( isReadWrite ) openFlags |= O_RDWR;
4551 if( isCreate ) openFlags |= O_CREAT;
4552 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4553 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004554
danielk1977b4b47412007-08-17 15:53:36 +00004555 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004556 mode_t openMode; /* Permissions to create file with */
4557 rc = findCreateFileMode(zName, flags, &openMode);
4558 if( rc!=SQLITE_OK ){
4559 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004560 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004561 return rc;
4562 }
dane946c392009-08-22 11:39:46 +00004563 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004564 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004565 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4566 /* Failed to open the file for read/write access. Try read-only. */
4567 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004568 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004569 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004570 openFlags |= O_RDONLY;
4571 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004572 }
4573 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004574 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004575 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004576 }
danielk1977b4b47412007-08-17 15:53:36 +00004577 }
dan08da86a2009-08-21 17:18:03 +00004578 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004579 if( pOutFlags ){
4580 *pOutFlags = flags;
4581 }
4582
dane946c392009-08-22 11:39:46 +00004583 if( p->pUnused ){
4584 p->pUnused->fd = fd;
4585 p->pUnused->flags = flags;
4586 }
4587
danielk1977b4b47412007-08-17 15:53:36 +00004588 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004589#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004590 zPath = zName;
4591#else
danielk197717b90b52008-06-06 11:11:25 +00004592 unlink(zName);
chw97185482008-11-17 08:05:31 +00004593#endif
danielk1977b4b47412007-08-17 15:53:36 +00004594 }
drh41022642008-11-21 00:24:42 +00004595#if SQLITE_ENABLE_LOCKING_STYLE
4596 else{
dan08da86a2009-08-21 17:18:03 +00004597 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004598 }
4599#endif
4600
danielk1977fee2d252007-08-18 10:59:19 +00004601 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004602 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004603 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004604 /* It is safe to close fd at this point, because it is guaranteed not
4605 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004606 ** it would not be safe to close as this would release any locks held
4607 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004608 assert( eType!=SQLITE_OPEN_MAIN_DB );
4609 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004610 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004611 }
4612 }
danielk1977e339d652008-06-28 11:23:00 +00004613
4614#ifdef FD_CLOEXEC
4615 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4616#endif
4617
drhda0e7682008-07-30 15:27:54 +00004618 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004619
drh7ed97b92010-01-20 13:07:21 +00004620
4621#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4622 struct statfs fsInfo;
4623 if( fstatfs(fd, &fsInfo) == -1 ){
4624 ((unixFile*)pFile)->lastErrno = errno;
4625 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4626 close(fd); /* silently leak if fail, in error */
4627 return SQLITE_IOERR_ACCESS;
4628 }
4629 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4630 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4631 }
4632#endif
4633
4634#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004635#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004636 isAutoProxy = 1;
4637#endif
4638 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004639 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4640 int useProxy = 0;
4641
dan08da86a2009-08-21 17:18:03 +00004642 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4643 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004644 if( envforce!=NULL ){
4645 useProxy = atoi(envforce)>0;
4646 }else{
4647 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004648 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004649 /* In theory, the close(fd) call is sub-optimal. If the file opened
4650 ** with fd is a database file, and there are other connections open
4651 ** on that file that are currently holding advisory locks on it,
4652 ** then the call to close() will cancel those locks. In practice,
4653 ** we're assuming that statfs() doesn't fail very often. At least
4654 ** not while other file descriptors opened by the same process on
4655 ** the same file are working. */
4656 p->lastErrno = errno;
4657 if( dirfd>=0 ){
4658 close(dirfd); /* silently leak if fail, in error */
4659 }
aswiftaebf4132008-11-21 00:10:35 +00004660 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004661 rc = SQLITE_IOERR_ACCESS;
4662 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004663 }
4664 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4665 }
4666 if( useProxy ){
4667 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4668 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004669 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004670 if( rc!=SQLITE_OK ){
4671 /* Use unixClose to clean up the resources added in fillInUnixFile
4672 ** and clear all the structure's references. Specifically,
4673 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4674 */
4675 unixClose(pFile);
4676 return rc;
4677 }
aswiftaebf4132008-11-21 00:10:35 +00004678 }
dane946c392009-08-22 11:39:46 +00004679 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004680 }
4681 }
4682#endif
4683
dane946c392009-08-22 11:39:46 +00004684 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4685open_finished:
4686 if( rc!=SQLITE_OK ){
4687 sqlite3_free(p->pUnused);
4688 }
4689 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004690}
4691
dane946c392009-08-22 11:39:46 +00004692
danielk1977b4b47412007-08-17 15:53:36 +00004693/*
danielk1977fee2d252007-08-18 10:59:19 +00004694** Delete the file at zPath. If the dirSync argument is true, fsync()
4695** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004696*/
drh6b9d6dd2008-12-03 19:34:47 +00004697static int unixDelete(
4698 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4699 const char *zPath, /* Name of file to be deleted */
4700 int dirSync /* If true, fsync() directory after deleting file */
4701){
danielk1977fee2d252007-08-18 10:59:19 +00004702 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004703 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004704 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004705 if( unlink(zPath)==(-1) && errno!=ENOENT ){
4706 return SQLITE_IOERR_DELETE;
4707 }
danielk1977d39fa702008-10-16 13:27:40 +00004708#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004709 if( dirSync ){
4710 int fd;
4711 rc = openDirectory(zPath, &fd);
4712 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004713#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004714 if( fsync(fd)==-1 )
4715#else
4716 if( fsync(fd) )
4717#endif
4718 {
danielk1977fee2d252007-08-18 10:59:19 +00004719 rc = SQLITE_IOERR_DIR_FSYNC;
4720 }
aswiftaebf4132008-11-21 00:10:35 +00004721 if( close(fd)&&!rc ){
4722 rc = SQLITE_IOERR_DIR_CLOSE;
4723 }
danielk1977fee2d252007-08-18 10:59:19 +00004724 }
4725 }
danielk1977d138dd82008-10-15 16:02:48 +00004726#endif
danielk1977fee2d252007-08-18 10:59:19 +00004727 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004728}
4729
danielk197790949c22007-08-17 16:50:38 +00004730/*
4731** Test the existance of or access permissions of file zPath. The
4732** test performed depends on the value of flags:
4733**
4734** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4735** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4736** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4737**
4738** Otherwise return 0.
4739*/
danielk1977861f7452008-06-05 11:39:11 +00004740static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004741 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4742 const char *zPath, /* Path of the file to examine */
4743 int flags, /* What do we want to learn about the zPath file? */
4744 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004745){
rse25c0d1a2007-09-20 08:38:14 +00004746 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004747 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004748 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004749 switch( flags ){
4750 case SQLITE_ACCESS_EXISTS:
4751 amode = F_OK;
4752 break;
4753 case SQLITE_ACCESS_READWRITE:
4754 amode = W_OK|R_OK;
4755 break;
drh50d3f902007-08-27 21:10:36 +00004756 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004757 amode = R_OK;
4758 break;
4759
4760 default:
4761 assert(!"Invalid flags argument");
4762 }
danielk1977861f7452008-06-05 11:39:11 +00004763 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004764 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4765 struct stat buf;
4766 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4767 *pResOut = 0;
4768 }
4769 }
danielk1977861f7452008-06-05 11:39:11 +00004770 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004771}
4772
danielk1977b4b47412007-08-17 15:53:36 +00004773
4774/*
4775** Turn a relative pathname into a full pathname. The relative path
4776** is stored as a nul-terminated string in the buffer pointed to by
4777** zPath.
4778**
4779** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4780** (in this case, MAX_PATHNAME bytes). The full-path is written to
4781** this buffer before returning.
4782*/
danielk1977adfb9b02007-09-17 07:02:56 +00004783static int unixFullPathname(
4784 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4785 const char *zPath, /* Possibly relative input path */
4786 int nOut, /* Size of output buffer in bytes */
4787 char *zOut /* Output buffer */
4788){
danielk1977843e65f2007-09-01 16:16:15 +00004789
4790 /* It's odd to simulate an io-error here, but really this is just
4791 ** using the io-error infrastructure to test that SQLite handles this
4792 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004793 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004794 */
4795 SimulateIOError( return SQLITE_ERROR );
4796
drh153c62c2007-08-24 03:51:33 +00004797 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004798 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004799
drh3c7f2dc2007-12-06 13:26:20 +00004800 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004801 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004802 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004803 }else{
4804 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004805 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004806 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004807 }
drhea678832008-12-10 19:26:22 +00004808 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004809 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004810 }
4811 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004812}
4813
drh0ccebe72005-06-07 22:22:50 +00004814
drh761df872006-12-21 01:29:22 +00004815#ifndef SQLITE_OMIT_LOAD_EXTENSION
4816/*
4817** Interfaces for opening a shared library, finding entry points
4818** within the shared library, and closing the shared library.
4819*/
4820#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004821static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4822 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004823 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4824}
danielk197795c8a542007-09-01 06:51:27 +00004825
4826/*
4827** SQLite calls this function immediately after a call to unixDlSym() or
4828** unixDlOpen() fails (returns a null pointer). If a more detailed error
4829** message is available, it is written to zBufOut. If no error message
4830** is available, zBufOut is left unmodified and SQLite uses a default
4831** error message.
4832*/
danielk1977397d65f2008-11-19 11:35:39 +00004833static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004834 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004835 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004836 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004837 zErr = dlerror();
4838 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004839 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004840 }
drh6c7d5c52008-11-21 20:32:33 +00004841 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004842}
drh1875f7a2008-12-08 18:19:17 +00004843static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4844 /*
4845 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4846 ** cast into a pointer to a function. And yet the library dlsym() routine
4847 ** returns a void* which is really a pointer to a function. So how do we
4848 ** use dlsym() with -pedantic-errors?
4849 **
4850 ** Variable x below is defined to be a pointer to a function taking
4851 ** parameters void* and const char* and returning a pointer to a function.
4852 ** We initialize x by assigning it a pointer to the dlsym() function.
4853 ** (That assignment requires a cast.) Then we call the function that
4854 ** x points to.
4855 **
4856 ** This work-around is unlikely to work correctly on any system where
4857 ** you really cannot cast a function pointer into void*. But then, on the
4858 ** other hand, dlsym() will not work on such a system either, so we have
4859 ** not really lost anything.
4860 */
4861 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004862 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004863 x = (void(*(*)(void*,const char*))(void))dlsym;
4864 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004865}
danielk1977397d65f2008-11-19 11:35:39 +00004866static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4867 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004868 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004869}
danielk1977b4b47412007-08-17 15:53:36 +00004870#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4871 #define unixDlOpen 0
4872 #define unixDlError 0
4873 #define unixDlSym 0
4874 #define unixDlClose 0
4875#endif
4876
4877/*
danielk197790949c22007-08-17 16:50:38 +00004878** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004879*/
danielk1977397d65f2008-11-19 11:35:39 +00004880static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4881 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004882 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004883
drhbbd42a62004-05-22 17:41:58 +00004884 /* We have to initialize zBuf to prevent valgrind from reporting
4885 ** errors. The reports issued by valgrind are incorrect - we would
4886 ** prefer that the randomness be increased by making use of the
4887 ** uninitialized space in zBuf - but valgrind errors tend to worry
4888 ** some users. Rather than argue, it seems easier just to initialize
4889 ** the whole array and silence valgrind, even if that means less randomness
4890 ** in the random seed.
4891 **
4892 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004893 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004894 ** tests repeatable.
4895 */
danielk1977b4b47412007-08-17 15:53:36 +00004896 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004897#if !defined(SQLITE_TEST)
4898 {
drh842b8642005-01-21 17:53:17 +00004899 int pid, fd;
4900 fd = open("/dev/urandom", O_RDONLY);
4901 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004902 time_t t;
4903 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004904 memcpy(zBuf, &t, sizeof(t));
4905 pid = getpid();
4906 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004907 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004908 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004909 }else{
drh72cbd072008-10-14 17:58:38 +00004910 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004911 close(fd);
4912 }
drhbbd42a62004-05-22 17:41:58 +00004913 }
4914#endif
drh72cbd072008-10-14 17:58:38 +00004915 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004916}
4917
danielk1977b4b47412007-08-17 15:53:36 +00004918
drhbbd42a62004-05-22 17:41:58 +00004919/*
4920** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004921** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004922** The return value is the number of microseconds of sleep actually
4923** requested from the underlying operating system, a number which
4924** might be greater than or equal to the argument, but not less
4925** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004926*/
danielk1977397d65f2008-11-19 11:35:39 +00004927static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004928#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004929 struct timespec sp;
4930
4931 sp.tv_sec = microseconds / 1000000;
4932 sp.tv_nsec = (microseconds % 1000000) * 1000;
4933 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004934 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004935 return microseconds;
4936#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004937 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004938 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004939 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004940#else
danielk1977b4b47412007-08-17 15:53:36 +00004941 int seconds = (microseconds+999999)/1000000;
4942 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004943 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004944 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004945#endif
drh88f474a2006-01-02 20:00:12 +00004946}
4947
4948/*
drh6b9d6dd2008-12-03 19:34:47 +00004949** The following variable, if set to a non-zero value, is interpreted as
4950** the number of seconds since 1970 and is used to set the result of
4951** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004952*/
4953#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004954int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004955#endif
4956
4957/*
drhb7e8ea22010-05-03 14:32:30 +00004958** Find the current time (in Universal Coordinated Time). Write into *piNow
4959** the current time and date as a Julian Day number times 86_400_000. In
4960** other words, write into *piNow the number of milliseconds since the Julian
4961** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4962** proleptic Gregorian calendar.
4963**
4964** On success, return 0. Return 1 if the time and date cannot be found.
4965*/
4966static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
4967 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
4968#if defined(NO_GETTOD)
4969 time_t t;
4970 time(&t);
4971 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
4972#elif OS_VXWORKS
4973 struct timespec sNow;
4974 clock_gettime(CLOCK_REALTIME, &sNow);
4975 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
4976#else
4977 struct timeval sNow;
4978 gettimeofday(&sNow, 0);
4979 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
4980#endif
4981
4982#ifdef SQLITE_TEST
4983 if( sqlite3_current_time ){
4984 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
4985 }
4986#endif
4987 UNUSED_PARAMETER(NotUsed);
4988 return 0;
4989}
4990
4991/*
drhbbd42a62004-05-22 17:41:58 +00004992** Find the current time (in Universal Coordinated Time). Write the
4993** current time and date as a Julian Day number into *prNow and
4994** return 0. Return 1 if the time and date cannot be found.
4995*/
danielk1977397d65f2008-11-19 11:35:39 +00004996static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00004997 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00004998 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00004999 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005000 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005001 return 0;
5002}
danielk1977b4b47412007-08-17 15:53:36 +00005003
drh6b9d6dd2008-12-03 19:34:47 +00005004/*
5005** We added the xGetLastError() method with the intention of providing
5006** better low-level error messages when operating-system problems come up
5007** during SQLite operation. But so far, none of that has been implemented
5008** in the core. So this routine is never called. For now, it is merely
5009** a place-holder.
5010*/
danielk1977397d65f2008-11-19 11:35:39 +00005011static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5012 UNUSED_PARAMETER(NotUsed);
5013 UNUSED_PARAMETER(NotUsed2);
5014 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005015 return 0;
5016}
5017
drhf2424c52010-04-26 00:04:55 +00005018
5019/*
drh734c9862008-11-28 15:37:20 +00005020************************ End of sqlite3_vfs methods ***************************
5021******************************************************************************/
5022
drh715ff302008-12-03 22:32:44 +00005023/******************************************************************************
5024************************** Begin Proxy Locking ********************************
5025**
5026** Proxy locking is a "uber-locking-method" in this sense: It uses the
5027** other locking methods on secondary lock files. Proxy locking is a
5028** meta-layer over top of the primitive locking implemented above. For
5029** this reason, the division that implements of proxy locking is deferred
5030** until late in the file (here) after all of the other I/O methods have
5031** been defined - so that the primitive locking methods are available
5032** as services to help with the implementation of proxy locking.
5033**
5034****
5035**
5036** The default locking schemes in SQLite use byte-range locks on the
5037** database file to coordinate safe, concurrent access by multiple readers
5038** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5039** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5040** as POSIX read & write locks over fixed set of locations (via fsctl),
5041** on AFP and SMB only exclusive byte-range locks are available via fsctl
5042** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5043** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5044** address in the shared range is taken for a SHARED lock, the entire
5045** shared range is taken for an EXCLUSIVE lock):
5046**
5047** PENDING_BYTE 0x40000000
5048** RESERVED_BYTE 0x40000001
5049** SHARED_RANGE 0x40000002 -> 0x40000200
5050**
5051** This works well on the local file system, but shows a nearly 100x
5052** slowdown in read performance on AFP because the AFP client disables
5053** the read cache when byte-range locks are present. Enabling the read
5054** cache exposes a cache coherency problem that is present on all OS X
5055** supported network file systems. NFS and AFP both observe the
5056** close-to-open semantics for ensuring cache coherency
5057** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5058** address the requirements for concurrent database access by multiple
5059** readers and writers
5060** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5061**
5062** To address the performance and cache coherency issues, proxy file locking
5063** changes the way database access is controlled by limiting access to a
5064** single host at a time and moving file locks off of the database file
5065** and onto a proxy file on the local file system.
5066**
5067**
5068** Using proxy locks
5069** -----------------
5070**
5071** C APIs
5072**
5073** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5074** <proxy_path> | ":auto:");
5075** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5076**
5077**
5078** SQL pragmas
5079**
5080** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5081** PRAGMA [database.]lock_proxy_file
5082**
5083** Specifying ":auto:" means that if there is a conch file with a matching
5084** host ID in it, the proxy path in the conch file will be used, otherwise
5085** a proxy path based on the user's temp dir
5086** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5087** actual proxy file name is generated from the name and path of the
5088** database file. For example:
5089**
5090** For database path "/Users/me/foo.db"
5091** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5092**
5093** Once a lock proxy is configured for a database connection, it can not
5094** be removed, however it may be switched to a different proxy path via
5095** the above APIs (assuming the conch file is not being held by another
5096** connection or process).
5097**
5098**
5099** How proxy locking works
5100** -----------------------
5101**
5102** Proxy file locking relies primarily on two new supporting files:
5103**
5104** * conch file to limit access to the database file to a single host
5105** at a time
5106**
5107** * proxy file to act as a proxy for the advisory locks normally
5108** taken on the database
5109**
5110** The conch file - to use a proxy file, sqlite must first "hold the conch"
5111** by taking an sqlite-style shared lock on the conch file, reading the
5112** contents and comparing the host's unique host ID (see below) and lock
5113** proxy path against the values stored in the conch. The conch file is
5114** stored in the same directory as the database file and the file name
5115** is patterned after the database file name as ".<databasename>-conch".
5116** If the conch file does not exist, or it's contents do not match the
5117** host ID and/or proxy path, then the lock is escalated to an exclusive
5118** lock and the conch file contents is updated with the host ID and proxy
5119** path and the lock is downgraded to a shared lock again. If the conch
5120** is held by another process (with a shared lock), the exclusive lock
5121** will fail and SQLITE_BUSY is returned.
5122**
5123** The proxy file - a single-byte file used for all advisory file locks
5124** normally taken on the database file. This allows for safe sharing
5125** of the database file for multiple readers and writers on the same
5126** host (the conch ensures that they all use the same local lock file).
5127**
drh715ff302008-12-03 22:32:44 +00005128** Requesting the lock proxy does not immediately take the conch, it is
5129** only taken when the first request to lock database file is made.
5130** This matches the semantics of the traditional locking behavior, where
5131** opening a connection to a database file does not take a lock on it.
5132** The shared lock and an open file descriptor are maintained until
5133** the connection to the database is closed.
5134**
5135** The proxy file and the lock file are never deleted so they only need
5136** to be created the first time they are used.
5137**
5138** Configuration options
5139** ---------------------
5140**
5141** SQLITE_PREFER_PROXY_LOCKING
5142**
5143** Database files accessed on non-local file systems are
5144** automatically configured for proxy locking, lock files are
5145** named automatically using the same logic as
5146** PRAGMA lock_proxy_file=":auto:"
5147**
5148** SQLITE_PROXY_DEBUG
5149**
5150** Enables the logging of error messages during host id file
5151** retrieval and creation
5152**
drh715ff302008-12-03 22:32:44 +00005153** LOCKPROXYDIR
5154**
5155** Overrides the default directory used for lock proxy files that
5156** are named automatically via the ":auto:" setting
5157**
5158** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5159**
5160** Permissions to use when creating a directory for storing the
5161** lock proxy files, only used when LOCKPROXYDIR is not set.
5162**
5163**
5164** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5165** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5166** force proxy locking to be used for every database file opened, and 0
5167** will force automatic proxy locking to be disabled for all database
5168** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5169** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5170*/
5171
5172/*
5173** Proxy locking is only available on MacOSX
5174*/
drhd2cb50b2009-01-09 21:41:17 +00005175#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005176
drh715ff302008-12-03 22:32:44 +00005177/*
5178** The proxyLockingContext has the path and file structures for the remote
5179** and local proxy files in it
5180*/
5181typedef struct proxyLockingContext proxyLockingContext;
5182struct proxyLockingContext {
5183 unixFile *conchFile; /* Open conch file */
5184 char *conchFilePath; /* Name of the conch file */
5185 unixFile *lockProxy; /* Open proxy lock file */
5186 char *lockProxyPath; /* Name of the proxy lock file */
5187 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005188 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005189 void *oldLockingContext; /* Original lockingcontext to restore on close */
5190 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5191};
5192
drh7ed97b92010-01-20 13:07:21 +00005193/*
5194** The proxy lock file path for the database at dbPath is written into lPath,
5195** which must point to valid, writable memory large enough for a maxLen length
5196** file path.
drh715ff302008-12-03 22:32:44 +00005197*/
drh715ff302008-12-03 22:32:44 +00005198static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5199 int len;
5200 int dbLen;
5201 int i;
5202
5203#ifdef LOCKPROXYDIR
5204 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5205#else
5206# ifdef _CS_DARWIN_USER_TEMP_DIR
5207 {
drh7ed97b92010-01-20 13:07:21 +00005208 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005209 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5210 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005211 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005212 }
drh7ed97b92010-01-20 13:07:21 +00005213 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005214 }
5215# else
5216 len = strlcpy(lPath, "/tmp/", maxLen);
5217# endif
5218#endif
5219
5220 if( lPath[len-1]!='/' ){
5221 len = strlcat(lPath, "/", maxLen);
5222 }
5223
5224 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005225 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005226 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005227 char c = dbPath[i];
5228 lPath[i+len] = (c=='/')?'_':c;
5229 }
5230 lPath[i+len]='\0';
5231 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005232 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005233 return SQLITE_OK;
5234}
5235
drh7ed97b92010-01-20 13:07:21 +00005236/*
5237 ** Creates the lock file and any missing directories in lockPath
5238 */
5239static int proxyCreateLockPath(const char *lockPath){
5240 int i, len;
5241 char buf[MAXPATHLEN];
5242 int start = 0;
5243
5244 assert(lockPath!=NULL);
5245 /* try to create all the intermediate directories */
5246 len = (int)strlen(lockPath);
5247 buf[0] = lockPath[0];
5248 for( i=1; i<len; i++ ){
5249 if( lockPath[i] == '/' && (i - start > 0) ){
5250 /* only mkdir if leaf dir != "." or "/" or ".." */
5251 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5252 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5253 buf[i]='\0';
5254 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5255 int err=errno;
5256 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005257 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005258 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005259 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005260 return err;
5261 }
5262 }
5263 }
5264 start=i+1;
5265 }
5266 buf[i] = lockPath[i];
5267 }
drh308c2a52010-05-14 11:30:18 +00005268 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005269 return 0;
5270}
5271
drh715ff302008-12-03 22:32:44 +00005272/*
5273** Create a new VFS file descriptor (stored in memory obtained from
5274** sqlite3_malloc) and open the file named "path" in the file descriptor.
5275**
5276** The caller is responsible not only for closing the file descriptor
5277** but also for freeing the memory associated with the file descriptor.
5278*/
drh7ed97b92010-01-20 13:07:21 +00005279static int proxyCreateUnixFile(
5280 const char *path, /* path for the new unixFile */
5281 unixFile **ppFile, /* unixFile created and returned by ref */
5282 int islockfile /* if non zero missing dirs will be created */
5283) {
5284 int fd = -1;
5285 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005286 unixFile *pNew;
5287 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005288 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005289 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005290 int terrno = 0;
5291 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005292
drh7ed97b92010-01-20 13:07:21 +00005293 /* 1. first try to open/create the file
5294 ** 2. if that fails, and this is a lock file (not-conch), try creating
5295 ** the parent directories and then try again.
5296 ** 3. if that fails, try to open the file read-only
5297 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5298 */
5299 pUnused = findReusableFd(path, openFlags);
5300 if( pUnused ){
5301 fd = pUnused->fd;
5302 }else{
5303 pUnused = sqlite3_malloc(sizeof(*pUnused));
5304 if( !pUnused ){
5305 return SQLITE_NOMEM;
5306 }
5307 }
5308 if( fd<0 ){
5309 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5310 terrno = errno;
5311 if( fd<0 && errno==ENOENT && islockfile ){
5312 if( proxyCreateLockPath(path) == SQLITE_OK ){
5313 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5314 }
5315 }
5316 }
5317 if( fd<0 ){
5318 openFlags = O_RDONLY;
5319 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5320 terrno = errno;
5321 }
5322 if( fd<0 ){
5323 if( islockfile ){
5324 return SQLITE_BUSY;
5325 }
5326 switch (terrno) {
5327 case EACCES:
5328 return SQLITE_PERM;
5329 case EIO:
5330 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5331 default:
drh9978c972010-02-23 17:36:32 +00005332 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005333 }
5334 }
5335
5336 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5337 if( pNew==NULL ){
5338 rc = SQLITE_NOMEM;
5339 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005340 }
5341 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005342 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005343 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005344 pUnused->fd = fd;
5345 pUnused->flags = openFlags;
5346 pNew->pUnused = pUnused;
5347
5348 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5349 if( rc==SQLITE_OK ){
5350 *ppFile = pNew;
5351 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005352 }
drh7ed97b92010-01-20 13:07:21 +00005353end_create_proxy:
5354 close(fd); /* silently leak fd if error, we're already in error */
5355 sqlite3_free(pNew);
5356 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005357 return rc;
5358}
5359
drh7ed97b92010-01-20 13:07:21 +00005360#ifdef SQLITE_TEST
5361/* simulate multiple hosts by creating unique hostid file paths */
5362int sqlite3_hostid_num = 0;
5363#endif
5364
5365#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5366
drh0ab216a2010-07-02 17:10:40 +00005367/* Not always defined in the headers as it ought to be */
5368extern int gethostuuid(uuid_t id, const struct timespec *wait);
5369
drh7ed97b92010-01-20 13:07:21 +00005370/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5371** bytes of writable memory.
5372*/
5373static int proxyGetHostID(unsigned char *pHostID, int *pError){
5374 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5375
5376 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5377 memset(pHostID, 0, PROXY_HOSTIDLEN);
5378 if( gethostuuid(pHostID, &timeout) ){
5379 int err = errno;
5380 if( pError ){
5381 *pError = err;
5382 }
5383 return SQLITE_IOERR;
5384 }
5385#ifdef SQLITE_TEST
5386 /* simulate multiple hosts by creating unique hostid file paths */
5387 if( sqlite3_hostid_num != 0){
5388 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5389 }
5390#endif
5391
5392 return SQLITE_OK;
5393}
5394
5395/* The conch file contains the header, host id and lock file path
5396 */
5397#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5398#define PROXY_HEADERLEN 1 /* conch file header length */
5399#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5400#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5401
5402/*
5403** Takes an open conch file, copies the contents to a new path and then moves
5404** it back. The newly created file's file descriptor is assigned to the
5405** conch file structure and finally the original conch file descriptor is
5406** closed. Returns zero if successful.
5407*/
5408static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5409 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5410 unixFile *conchFile = pCtx->conchFile;
5411 char tPath[MAXPATHLEN];
5412 char buf[PROXY_MAXCONCHLEN];
5413 char *cPath = pCtx->conchFilePath;
5414 size_t readLen = 0;
5415 size_t pathLen = 0;
5416 char errmsg[64] = "";
5417 int fd = -1;
5418 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005419 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005420
5421 /* create a new path by replace the trailing '-conch' with '-break' */
5422 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5423 if( pathLen>MAXPATHLEN || pathLen<6 ||
5424 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5425 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5426 goto end_breaklock;
5427 }
5428 /* read the conch content */
5429 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5430 if( readLen<PROXY_PATHINDEX ){
5431 sprintf(errmsg, "read error (len %d)", (int)readLen);
5432 goto end_breaklock;
5433 }
5434 /* write it out to the temporary break file */
5435 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5436 if( fd<0 ){
5437 sprintf(errmsg, "create failed (%d)", errno);
5438 goto end_breaklock;
5439 }
drh0ab216a2010-07-02 17:10:40 +00005440 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
drh7ed97b92010-01-20 13:07:21 +00005441 sprintf(errmsg, "write failed (%d)", errno);
5442 goto end_breaklock;
5443 }
5444 if( rename(tPath, cPath) ){
5445 sprintf(errmsg, "rename failed (%d)", errno);
5446 goto end_breaklock;
5447 }
5448 rc = 0;
5449 fprintf(stderr, "broke stale lock on %s\n", cPath);
5450 close(conchFile->h);
5451 conchFile->h = fd;
5452 conchFile->openFlags = O_RDWR | O_CREAT;
5453
5454end_breaklock:
5455 if( rc ){
5456 if( fd>=0 ){
5457 unlink(tPath);
5458 close(fd);
5459 }
5460 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5461 }
5462 return rc;
5463}
5464
5465/* Take the requested lock on the conch file and break a stale lock if the
5466** host id matches.
5467*/
5468static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5469 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5470 unixFile *conchFile = pCtx->conchFile;
5471 int rc = SQLITE_OK;
5472 int nTries = 0;
5473 struct timespec conchModTime;
5474
5475 do {
5476 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5477 nTries ++;
5478 if( rc==SQLITE_BUSY ){
5479 /* If the lock failed (busy):
5480 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5481 * 2nd try: fail if the mod time changed or host id is different, wait
5482 * 10 sec and try again
5483 * 3rd try: break the lock unless the mod time has changed.
5484 */
5485 struct stat buf;
5486 if( fstat(conchFile->h, &buf) ){
5487 pFile->lastErrno = errno;
5488 return SQLITE_IOERR_LOCK;
5489 }
5490
5491 if( nTries==1 ){
5492 conchModTime = buf.st_mtimespec;
5493 usleep(500000); /* wait 0.5 sec and try the lock again*/
5494 continue;
5495 }
5496
5497 assert( nTries>1 );
5498 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5499 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5500 return SQLITE_BUSY;
5501 }
5502
5503 if( nTries==2 ){
5504 char tBuf[PROXY_MAXCONCHLEN];
5505 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5506 if( len<0 ){
5507 pFile->lastErrno = errno;
5508 return SQLITE_IOERR_LOCK;
5509 }
5510 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5511 /* don't break the lock if the host id doesn't match */
5512 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5513 return SQLITE_BUSY;
5514 }
5515 }else{
5516 /* don't break the lock on short read or a version mismatch */
5517 return SQLITE_BUSY;
5518 }
5519 usleep(10000000); /* wait 10 sec and try the lock again */
5520 continue;
5521 }
5522
5523 assert( nTries==3 );
5524 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5525 rc = SQLITE_OK;
5526 if( lockType==EXCLUSIVE_LOCK ){
5527 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5528 }
5529 if( !rc ){
5530 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5531 }
5532 }
5533 }
5534 } while( rc==SQLITE_BUSY && nTries<3 );
5535
5536 return rc;
5537}
5538
5539/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005540** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5541** lockPath means that the lockPath in the conch file will be used if the
5542** host IDs match, or a new lock path will be generated automatically
5543** and written to the conch file.
5544*/
5545static int proxyTakeConch(unixFile *pFile){
5546 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5547
drh7ed97b92010-01-20 13:07:21 +00005548 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005549 return SQLITE_OK;
5550 }else{
5551 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005552 uuid_t myHostID;
5553 int pError = 0;
5554 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005555 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005556 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005557 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005558 int createConch = 0;
5559 int hostIdMatch = 0;
5560 int readLen = 0;
5561 int tryOldLockPath = 0;
5562 int forceNewLockPath = 0;
5563
drh308c2a52010-05-14 11:30:18 +00005564 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5565 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005566
drh7ed97b92010-01-20 13:07:21 +00005567 rc = proxyGetHostID(myHostID, &pError);
5568 if( (rc&0xff)==SQLITE_IOERR ){
5569 pFile->lastErrno = pError;
5570 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005571 }
drh7ed97b92010-01-20 13:07:21 +00005572 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005573 if( rc!=SQLITE_OK ){
5574 goto end_takeconch;
5575 }
drh7ed97b92010-01-20 13:07:21 +00005576 /* read the existing conch file */
5577 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5578 if( readLen<0 ){
5579 /* I/O error: lastErrno set by seekAndRead */
5580 pFile->lastErrno = conchFile->lastErrno;
5581 rc = SQLITE_IOERR_READ;
5582 goto end_takeconch;
5583 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5584 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5585 /* a short read or version format mismatch means we need to create a new
5586 ** conch file.
5587 */
5588 createConch = 1;
5589 }
5590 /* if the host id matches and the lock path already exists in the conch
5591 ** we'll try to use the path there, if we can't open that path, we'll
5592 ** retry with a new auto-generated path
5593 */
5594 do { /* in case we need to try again for an :auto: named lock file */
5595
5596 if( !createConch && !forceNewLockPath ){
5597 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5598 PROXY_HOSTIDLEN);
5599 /* if the conch has data compare the contents */
5600 if( !pCtx->lockProxyPath ){
5601 /* for auto-named local lock file, just check the host ID and we'll
5602 ** use the local lock file path that's already in there
5603 */
5604 if( hostIdMatch ){
5605 size_t pathLen = (readLen - PROXY_PATHINDEX);
5606
5607 if( pathLen>=MAXPATHLEN ){
5608 pathLen=MAXPATHLEN-1;
5609 }
5610 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5611 lockPath[pathLen] = 0;
5612 tempLockPath = lockPath;
5613 tryOldLockPath = 1;
5614 /* create a copy of the lock path if the conch is taken */
5615 goto end_takeconch;
5616 }
5617 }else if( hostIdMatch
5618 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5619 readLen-PROXY_PATHINDEX)
5620 ){
5621 /* conch host and lock path match */
5622 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005623 }
drh7ed97b92010-01-20 13:07:21 +00005624 }
5625
5626 /* if the conch isn't writable and doesn't match, we can't take it */
5627 if( (conchFile->openFlags&O_RDWR) == 0 ){
5628 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005629 goto end_takeconch;
5630 }
drh7ed97b92010-01-20 13:07:21 +00005631
5632 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005633 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005634 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5635 tempLockPath = lockPath;
5636 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005637 }
drh7ed97b92010-01-20 13:07:21 +00005638
5639 /* update conch with host and path (this will fail if other process
5640 ** has a shared lock already), if the host id matches, use the big
5641 ** stick.
drh715ff302008-12-03 22:32:44 +00005642 */
drh7ed97b92010-01-20 13:07:21 +00005643 futimes(conchFile->h, NULL);
5644 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005645 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005646 /* We are trying for an exclusive lock but another thread in this
5647 ** same process is still holding a shared lock. */
5648 rc = SQLITE_BUSY;
5649 } else {
5650 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005651 }
drh715ff302008-12-03 22:32:44 +00005652 }else{
drh7ed97b92010-01-20 13:07:21 +00005653 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005654 }
drh7ed97b92010-01-20 13:07:21 +00005655 if( rc==SQLITE_OK ){
5656 char writeBuffer[PROXY_MAXCONCHLEN];
5657 int writeSize = 0;
5658
5659 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5660 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5661 if( pCtx->lockProxyPath!=NULL ){
5662 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5663 }else{
5664 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5665 }
5666 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5667 ftruncate(conchFile->h, writeSize);
5668 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5669 fsync(conchFile->h);
5670 /* If we created a new conch file (not just updated the contents of a
5671 ** valid conch file), try to match the permissions of the database
5672 */
5673 if( rc==SQLITE_OK && createConch ){
5674 struct stat buf;
5675 int err = fstat(pFile->h, &buf);
5676 if( err==0 ){
5677 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5678 S_IROTH|S_IWOTH);
5679 /* try to match the database file R/W permissions, ignore failure */
5680#ifndef SQLITE_PROXY_DEBUG
5681 fchmod(conchFile->h, cmode);
5682#else
5683 if( fchmod(conchFile->h, cmode)!=0 ){
5684 int code = errno;
5685 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5686 cmode, code, strerror(code));
5687 } else {
5688 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5689 }
5690 }else{
5691 int code = errno;
5692 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5693 err, code, strerror(code));
5694#endif
5695 }
drh715ff302008-12-03 22:32:44 +00005696 }
5697 }
drh7ed97b92010-01-20 13:07:21 +00005698 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5699
5700 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005701 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005702 if( rc==SQLITE_OK && pFile->openFlags ){
5703 if( pFile->h>=0 ){
5704#ifdef STRICT_CLOSE_ERROR
5705 if( close(pFile->h) ){
5706 pFile->lastErrno = errno;
5707 return SQLITE_IOERR_CLOSE;
5708 }
5709#else
5710 close(pFile->h); /* silently leak fd if fail */
5711#endif
5712 }
5713 pFile->h = -1;
5714 int fd = open(pCtx->dbPath, pFile->openFlags,
5715 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005716 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005717 if( fd>=0 ){
5718 pFile->h = fd;
5719 }else{
drh9978c972010-02-23 17:36:32 +00005720 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005721 during locking */
5722 }
5723 }
5724 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5725 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5726 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5727 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5728 /* we couldn't create the proxy lock file with the old lock file path
5729 ** so try again via auto-naming
5730 */
5731 forceNewLockPath = 1;
5732 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005733 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005734 }
5735 }
5736 if( rc==SQLITE_OK ){
5737 /* Need to make a copy of path if we extracted the value
5738 ** from the conch file or the path was allocated on the stack
5739 */
5740 if( tempLockPath ){
5741 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5742 if( !pCtx->lockProxyPath ){
5743 rc = SQLITE_NOMEM;
5744 }
5745 }
5746 }
5747 if( rc==SQLITE_OK ){
5748 pCtx->conchHeld = 1;
5749
5750 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5751 afpLockingContext *afpCtx;
5752 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5753 afpCtx->dbPath = pCtx->lockProxyPath;
5754 }
5755 } else {
5756 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5757 }
drh308c2a52010-05-14 11:30:18 +00005758 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5759 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005760 return rc;
drh308c2a52010-05-14 11:30:18 +00005761 } while (1); /* in case we need to retry the :auto: lock file -
5762 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005763 }
5764}
5765
5766/*
5767** If pFile holds a lock on a conch file, then release that lock.
5768*/
5769static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005770 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005771 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5772 unixFile *conchFile; /* Name of the conch file */
5773
5774 pCtx = (proxyLockingContext *)pFile->lockingContext;
5775 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005776 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005777 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005778 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005779 if( pCtx->conchHeld>0 ){
5780 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5781 }
drh715ff302008-12-03 22:32:44 +00005782 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005783 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5784 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005785 return rc;
5786}
5787
5788/*
5789** Given the name of a database file, compute the name of its conch file.
5790** Store the conch filename in memory obtained from sqlite3_malloc().
5791** Make *pConchPath point to the new name. Return SQLITE_OK on success
5792** or SQLITE_NOMEM if unable to obtain memory.
5793**
5794** The caller is responsible for ensuring that the allocated memory
5795** space is eventually freed.
5796**
5797** *pConchPath is set to NULL if a memory allocation error occurs.
5798*/
5799static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5800 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005801 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005802 char *conchPath; /* buffer in which to construct conch name */
5803
5804 /* Allocate space for the conch filename and initialize the name to
5805 ** the name of the original database file. */
5806 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5807 if( conchPath==0 ){
5808 return SQLITE_NOMEM;
5809 }
5810 memcpy(conchPath, dbPath, len+1);
5811
5812 /* now insert a "." before the last / character */
5813 for( i=(len-1); i>=0; i-- ){
5814 if( conchPath[i]=='/' ){
5815 i++;
5816 break;
5817 }
5818 }
5819 conchPath[i]='.';
5820 while ( i<len ){
5821 conchPath[i+1]=dbPath[i];
5822 i++;
5823 }
5824
5825 /* append the "-conch" suffix to the file */
5826 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005827 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005828
5829 return SQLITE_OK;
5830}
5831
5832
5833/* Takes a fully configured proxy locking-style unix file and switches
5834** the local lock file path
5835*/
5836static int switchLockProxyPath(unixFile *pFile, const char *path) {
5837 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5838 char *oldPath = pCtx->lockProxyPath;
5839 int rc = SQLITE_OK;
5840
drh308c2a52010-05-14 11:30:18 +00005841 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005842 return SQLITE_BUSY;
5843 }
5844
5845 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5846 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5847 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5848 return SQLITE_OK;
5849 }else{
5850 unixFile *lockProxy = pCtx->lockProxy;
5851 pCtx->lockProxy=NULL;
5852 pCtx->conchHeld = 0;
5853 if( lockProxy!=NULL ){
5854 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5855 if( rc ) return rc;
5856 sqlite3_free(lockProxy);
5857 }
5858 sqlite3_free(oldPath);
5859 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5860 }
5861
5862 return rc;
5863}
5864
5865/*
5866** pFile is a file that has been opened by a prior xOpen call. dbPath
5867** is a string buffer at least MAXPATHLEN+1 characters in size.
5868**
5869** This routine find the filename associated with pFile and writes it
5870** int dbPath.
5871*/
5872static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005873#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005874 if( pFile->pMethod == &afpIoMethods ){
5875 /* afp style keeps a reference to the db path in the filePath field
5876 ** of the struct */
drhea678832008-12-10 19:26:22 +00005877 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005878 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5879 } else
drh715ff302008-12-03 22:32:44 +00005880#endif
5881 if( pFile->pMethod == &dotlockIoMethods ){
5882 /* dot lock style uses the locking context to store the dot lock
5883 ** file path */
5884 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5885 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5886 }else{
5887 /* all other styles use the locking context to store the db file path */
5888 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005889 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005890 }
5891 return SQLITE_OK;
5892}
5893
5894/*
5895** Takes an already filled in unix file and alters it so all file locking
5896** will be performed on the local proxy lock file. The following fields
5897** are preserved in the locking context so that they can be restored and
5898** the unix structure properly cleaned up at close time:
5899** ->lockingContext
5900** ->pMethod
5901*/
5902static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5903 proxyLockingContext *pCtx;
5904 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5905 char *lockPath=NULL;
5906 int rc = SQLITE_OK;
5907
drh308c2a52010-05-14 11:30:18 +00005908 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005909 return SQLITE_BUSY;
5910 }
5911 proxyGetDbPathForUnixFile(pFile, dbPath);
5912 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5913 lockPath=NULL;
5914 }else{
5915 lockPath=(char *)path;
5916 }
5917
drh308c2a52010-05-14 11:30:18 +00005918 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5919 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005920
5921 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5922 if( pCtx==0 ){
5923 return SQLITE_NOMEM;
5924 }
5925 memset(pCtx, 0, sizeof(*pCtx));
5926
5927 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5928 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005929 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5930 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5931 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5932 ** (c) the file system is read-only, then enable no-locking access.
5933 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5934 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5935 */
5936 struct statfs fsInfo;
5937 struct stat conchInfo;
5938 int goLockless = 0;
5939
5940 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5941 int err = errno;
5942 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5943 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5944 }
5945 }
5946 if( goLockless ){
5947 pCtx->conchHeld = -1; /* read only FS/ lockless */
5948 rc = SQLITE_OK;
5949 }
5950 }
drh715ff302008-12-03 22:32:44 +00005951 }
5952 if( rc==SQLITE_OK && lockPath ){
5953 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5954 }
5955
5956 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005957 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5958 if( pCtx->dbPath==NULL ){
5959 rc = SQLITE_NOMEM;
5960 }
5961 }
5962 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005963 /* all memory is allocated, proxys are created and assigned,
5964 ** switch the locking context and pMethod then return.
5965 */
drh715ff302008-12-03 22:32:44 +00005966 pCtx->oldLockingContext = pFile->lockingContext;
5967 pFile->lockingContext = pCtx;
5968 pCtx->pOldMethod = pFile->pMethod;
5969 pFile->pMethod = &proxyIoMethods;
5970 }else{
5971 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00005972 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00005973 sqlite3_free(pCtx->conchFile);
5974 }
drh7ed97b92010-01-20 13:07:21 +00005975 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00005976 sqlite3_free(pCtx->conchFilePath);
5977 sqlite3_free(pCtx);
5978 }
drh308c2a52010-05-14 11:30:18 +00005979 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
5980 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005981 return rc;
5982}
5983
5984
5985/*
5986** This routine handles sqlite3_file_control() calls that are specific
5987** to proxy locking.
5988*/
5989static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5990 switch( op ){
5991 case SQLITE_GET_LOCKPROXYFILE: {
5992 unixFile *pFile = (unixFile*)id;
5993 if( pFile->pMethod == &proxyIoMethods ){
5994 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5995 proxyTakeConch(pFile);
5996 if( pCtx->lockProxyPath ){
5997 *(const char **)pArg = pCtx->lockProxyPath;
5998 }else{
5999 *(const char **)pArg = ":auto: (not held)";
6000 }
6001 } else {
6002 *(const char **)pArg = NULL;
6003 }
6004 return SQLITE_OK;
6005 }
6006 case SQLITE_SET_LOCKPROXYFILE: {
6007 unixFile *pFile = (unixFile*)id;
6008 int rc = SQLITE_OK;
6009 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6010 if( pArg==NULL || (const char *)pArg==0 ){
6011 if( isProxyStyle ){
6012 /* turn off proxy locking - not supported */
6013 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6014 }else{
6015 /* turn off proxy locking - already off - NOOP */
6016 rc = SQLITE_OK;
6017 }
6018 }else{
6019 const char *proxyPath = (const char *)pArg;
6020 if( isProxyStyle ){
6021 proxyLockingContext *pCtx =
6022 (proxyLockingContext*)pFile->lockingContext;
6023 if( !strcmp(pArg, ":auto:")
6024 || (pCtx->lockProxyPath &&
6025 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6026 ){
6027 rc = SQLITE_OK;
6028 }else{
6029 rc = switchLockProxyPath(pFile, proxyPath);
6030 }
6031 }else{
6032 /* turn on proxy file locking */
6033 rc = proxyTransformUnixFile(pFile, proxyPath);
6034 }
6035 }
6036 return rc;
6037 }
6038 default: {
6039 assert( 0 ); /* The call assures that only valid opcodes are sent */
6040 }
6041 }
6042 /*NOTREACHED*/
6043 return SQLITE_ERROR;
6044}
6045
6046/*
6047** Within this division (the proxying locking implementation) the procedures
6048** above this point are all utilities. The lock-related methods of the
6049** proxy-locking sqlite3_io_method object follow.
6050*/
6051
6052
6053/*
6054** This routine checks if there is a RESERVED lock held on the specified
6055** file by this or any other process. If such a lock is held, set *pResOut
6056** to a non-zero value otherwise *pResOut is set to zero. The return value
6057** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6058*/
6059static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6060 unixFile *pFile = (unixFile*)id;
6061 int rc = proxyTakeConch(pFile);
6062 if( rc==SQLITE_OK ){
6063 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006064 if( pCtx->conchHeld>0 ){
6065 unixFile *proxy = pCtx->lockProxy;
6066 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6067 }else{ /* conchHeld < 0 is lockless */
6068 pResOut=0;
6069 }
drh715ff302008-12-03 22:32:44 +00006070 }
6071 return rc;
6072}
6073
6074/*
drh308c2a52010-05-14 11:30:18 +00006075** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006076** of the following:
6077**
6078** (1) SHARED_LOCK
6079** (2) RESERVED_LOCK
6080** (3) PENDING_LOCK
6081** (4) EXCLUSIVE_LOCK
6082**
6083** Sometimes when requesting one lock state, additional lock states
6084** are inserted in between. The locking might fail on one of the later
6085** transitions leaving the lock state different from what it started but
6086** still short of its goal. The following chart shows the allowed
6087** transitions and the inserted intermediate states:
6088**
6089** UNLOCKED -> SHARED
6090** SHARED -> RESERVED
6091** SHARED -> (PENDING) -> EXCLUSIVE
6092** RESERVED -> (PENDING) -> EXCLUSIVE
6093** PENDING -> EXCLUSIVE
6094**
6095** This routine will only increase a lock. Use the sqlite3OsUnlock()
6096** routine to lower a locking level.
6097*/
drh308c2a52010-05-14 11:30:18 +00006098static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006099 unixFile *pFile = (unixFile*)id;
6100 int rc = proxyTakeConch(pFile);
6101 if( rc==SQLITE_OK ){
6102 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006103 if( pCtx->conchHeld>0 ){
6104 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006105 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6106 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006107 }else{
6108 /* conchHeld < 0 is lockless */
6109 }
drh715ff302008-12-03 22:32:44 +00006110 }
6111 return rc;
6112}
6113
6114
6115/*
drh308c2a52010-05-14 11:30:18 +00006116** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006117** must be either NO_LOCK or SHARED_LOCK.
6118**
6119** If the locking level of the file descriptor is already at or below
6120** the requested locking level, this routine is a no-op.
6121*/
drh308c2a52010-05-14 11:30:18 +00006122static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006123 unixFile *pFile = (unixFile*)id;
6124 int rc = proxyTakeConch(pFile);
6125 if( rc==SQLITE_OK ){
6126 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006127 if( pCtx->conchHeld>0 ){
6128 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006129 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6130 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006131 }else{
6132 /* conchHeld < 0 is lockless */
6133 }
drh715ff302008-12-03 22:32:44 +00006134 }
6135 return rc;
6136}
6137
6138/*
6139** Close a file that uses proxy locks.
6140*/
6141static int proxyClose(sqlite3_file *id) {
6142 if( id ){
6143 unixFile *pFile = (unixFile*)id;
6144 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6145 unixFile *lockProxy = pCtx->lockProxy;
6146 unixFile *conchFile = pCtx->conchFile;
6147 int rc = SQLITE_OK;
6148
6149 if( lockProxy ){
6150 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6151 if( rc ) return rc;
6152 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6153 if( rc ) return rc;
6154 sqlite3_free(lockProxy);
6155 pCtx->lockProxy = 0;
6156 }
6157 if( conchFile ){
6158 if( pCtx->conchHeld ){
6159 rc = proxyReleaseConch(pFile);
6160 if( rc ) return rc;
6161 }
6162 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6163 if( rc ) return rc;
6164 sqlite3_free(conchFile);
6165 }
6166 sqlite3_free(pCtx->lockProxyPath);
6167 sqlite3_free(pCtx->conchFilePath);
6168 sqlite3_free(pCtx->dbPath);
6169 /* restore the original locking context and pMethod then close it */
6170 pFile->lockingContext = pCtx->oldLockingContext;
6171 pFile->pMethod = pCtx->pOldMethod;
6172 sqlite3_free(pCtx);
6173 return pFile->pMethod->xClose(id);
6174 }
6175 return SQLITE_OK;
6176}
6177
6178
6179
drhd2cb50b2009-01-09 21:41:17 +00006180#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006181/*
6182** The proxy locking style is intended for use with AFP filesystems.
6183** And since AFP is only supported on MacOSX, the proxy locking is also
6184** restricted to MacOSX.
6185**
6186**
6187******************* End of the proxy lock implementation **********************
6188******************************************************************************/
6189
drh734c9862008-11-28 15:37:20 +00006190/*
danielk1977e339d652008-06-28 11:23:00 +00006191** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006192**
6193** This routine registers all VFS implementations for unix-like operating
6194** systems. This routine, and the sqlite3_os_end() routine that follows,
6195** should be the only routines in this file that are visible from other
6196** files.
drh6b9d6dd2008-12-03 19:34:47 +00006197**
6198** This routine is called once during SQLite initialization and by a
6199** single thread. The memory allocation and mutex subsystems have not
6200** necessarily been initialized when this routine is called, and so they
6201** should not be used.
drh153c62c2007-08-24 03:51:33 +00006202*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006203int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006204 /*
6205 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006206 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6207 ** to the "finder" function. (pAppData is a pointer to a pointer because
6208 ** silly C90 rules prohibit a void* from being cast to a function pointer
6209 ** and so we have to go through the intermediate pointer to avoid problems
6210 ** when compiling with -pedantic-errors on GCC.)
6211 **
6212 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006213 ** finder-function. The finder-function returns a pointer to the
6214 ** sqlite_io_methods object that implements the desired locking
6215 ** behaviors. See the division above that contains the IOMETHODS
6216 ** macro for addition information on finder-functions.
6217 **
6218 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6219 ** object. But the "autolockIoFinder" available on MacOSX does a little
6220 ** more than that; it looks at the filesystem type that hosts the
6221 ** database file and tries to choose an locking method appropriate for
6222 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006223 */
drh7708e972008-11-29 00:56:52 +00006224 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006225 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006226 sizeof(unixFile), /* szOsFile */ \
6227 MAX_PATHNAME, /* mxPathname */ \
6228 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006229 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006230 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006231 unixOpen, /* xOpen */ \
6232 unixDelete, /* xDelete */ \
6233 unixAccess, /* xAccess */ \
6234 unixFullPathname, /* xFullPathname */ \
6235 unixDlOpen, /* xDlOpen */ \
6236 unixDlError, /* xDlError */ \
6237 unixDlSym, /* xDlSym */ \
6238 unixDlClose, /* xDlClose */ \
6239 unixRandomness, /* xRandomness */ \
6240 unixSleep, /* xSleep */ \
6241 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006242 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006243 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006244 }
6245
drh6b9d6dd2008-12-03 19:34:47 +00006246 /*
6247 ** All default VFSes for unix are contained in the following array.
6248 **
6249 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6250 ** by the SQLite core when the VFS is registered. So the following
6251 ** array cannot be const.
6252 */
danielk1977e339d652008-06-28 11:23:00 +00006253 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006254#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006255 UNIXVFS("unix", autolockIoFinder ),
6256#else
6257 UNIXVFS("unix", posixIoFinder ),
6258#endif
6259 UNIXVFS("unix-none", nolockIoFinder ),
6260 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006261#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006262 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006263#endif
6264#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006265 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006266#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006267 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006268#endif
chw78a13182009-04-07 05:35:03 +00006269#endif
drhd2cb50b2009-01-09 21:41:17 +00006270#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006271 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006272 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006273 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006274#endif
drh153c62c2007-08-24 03:51:33 +00006275 };
drh6b9d6dd2008-12-03 19:34:47 +00006276 unsigned int i; /* Loop counter */
6277
6278 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006279 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006280 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006281 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006282 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006283}
danielk1977e339d652008-06-28 11:23:00 +00006284
6285/*
drh6b9d6dd2008-12-03 19:34:47 +00006286** Shutdown the operating system interface.
6287**
6288** Some operating systems might need to do some cleanup in this routine,
6289** to release dynamically allocated objects. But not on unix.
6290** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006291*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006292int sqlite3_os_end(void){
6293 return SQLITE_OK;
6294}
drhdce8bdb2007-08-16 13:01:44 +00006295
danielk197729bafea2008-06-26 10:41:19 +00006296#endif /* SQLITE_OS_UNIX */