blob: 0a302a455c2899b52cfbbfcbcab7b8b846196baf [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 */
drh08c6d442009-02-09 17:34:07 +0000213#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000214 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000215#endif
drh7ed97b92010-01-20 13:07:21 +0000216#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000217 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000218#endif
219#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000220 int isDelete; /* Delete on close if true */
221 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000222#endif
drh8f941bc2009-01-14 23:03:40 +0000223#ifndef NDEBUG
224 /* The next group of variables are used to track whether or not the
225 ** transaction counter in bytes 24-27 of database files are updated
226 ** whenever any part of the database changes. An assertion fault will
227 ** occur if a file is updated without also updating the transaction
228 ** counter. This test is made to avoid new problems similar to the
229 ** one described by ticket #3584.
230 */
231 unsigned char transCntrChng; /* True if the transaction counter changed */
232 unsigned char dbUpdate; /* True if any part of database file changed */
233 unsigned char inNormalWrite; /* True if in a normal write operation */
234#endif
danielk1977967a4a12007-08-20 14:23:44 +0000235#ifdef SQLITE_TEST
236 /* In test mode, increase the size of this structure a bit so that
237 ** it is larger than the struct CrashFile defined in test6.c.
238 */
239 char aPadding[32];
240#endif
drh9cbe6352005-11-29 03:13:21 +0000241};
242
drh0ccebe72005-06-07 22:22:50 +0000243/*
drh0c2694b2009-09-03 16:23:44 +0000244** The following macros define bits in unixFile.fileFlags
245*/
246#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
247
248/*
drh198bf392006-01-06 21:52:49 +0000249** Include code that is common to all os_*.c files
250*/
251#include "os_common.h"
252
253/*
drh0ccebe72005-06-07 22:22:50 +0000254** Define various macros that are missing from some systems.
255*/
drhbbd42a62004-05-22 17:41:58 +0000256#ifndef O_LARGEFILE
257# define O_LARGEFILE 0
258#endif
259#ifdef SQLITE_DISABLE_LFS
260# undef O_LARGEFILE
261# define O_LARGEFILE 0
262#endif
263#ifndef O_NOFOLLOW
264# define O_NOFOLLOW 0
265#endif
266#ifndef O_BINARY
267# define O_BINARY 0
268#endif
269
270/*
271** The DJGPP compiler environment looks mostly like Unix, but it
272** lacks the fcntl() system call. So redefine fcntl() to be something
273** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000274** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000275*/
276#ifdef __DJGPP__
277# define fcntl(A,B,C) 0
278#endif
279
280/*
drh2b4b5962005-06-15 17:47:55 +0000281** The threadid macro resolves to the thread-id or to 0. Used for
282** testing and debugging only.
283*/
drhd677b3d2007-08-20 22:48:41 +0000284#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000285#define threadid pthread_self()
286#else
287#define threadid 0
288#endif
289
danielk197713adf8a2004-06-03 16:08:41 +0000290
drh107886a2008-11-21 22:21:50 +0000291/*
dan9359c7b2009-08-21 08:29:10 +0000292** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000293** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000294** vxworksFileId objects used by this file, all of which may be
295** shared by multiple threads.
296**
297** Function unixMutexHeld() is used to assert() that the global mutex
298** is held when required. This function is only used as part of assert()
299** statements. e.g.
300**
301** unixEnterMutex()
302** assert( unixMutexHeld() );
303** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000304*/
305static void unixEnterMutex(void){
306 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
307}
308static void unixLeaveMutex(void){
309 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
310}
dan9359c7b2009-08-21 08:29:10 +0000311#ifdef SQLITE_DEBUG
312static int unixMutexHeld(void) {
313 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
314}
315#endif
drh107886a2008-11-21 22:21:50 +0000316
drh734c9862008-11-28 15:37:20 +0000317
318#ifdef SQLITE_DEBUG
319/*
320** Helper function for printing out trace information from debugging
321** binaries. This returns the string represetation of the supplied
322** integer lock-type.
323*/
drh308c2a52010-05-14 11:30:18 +0000324static const char *azFileLock(int eFileLock){
325 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000326 case NO_LOCK: return "NONE";
327 case SHARED_LOCK: return "SHARED";
328 case RESERVED_LOCK: return "RESERVED";
329 case PENDING_LOCK: return "PENDING";
330 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000331 }
332 return "ERROR";
333}
334#endif
335
336#ifdef SQLITE_LOCK_TRACE
337/*
338** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000339**
drh734c9862008-11-28 15:37:20 +0000340** This routine is used for troubleshooting locks on multithreaded
341** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
342** command-line option on the compiler. This code is normally
343** turned off.
344*/
345static int lockTrace(int fd, int op, struct flock *p){
346 char *zOpName, *zType;
347 int s;
348 int savedErrno;
349 if( op==F_GETLK ){
350 zOpName = "GETLK";
351 }else if( op==F_SETLK ){
352 zOpName = "SETLK";
353 }else{
354 s = fcntl(fd, op, p);
355 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
356 return s;
357 }
358 if( p->l_type==F_RDLCK ){
359 zType = "RDLCK";
360 }else if( p->l_type==F_WRLCK ){
361 zType = "WRLCK";
362 }else if( p->l_type==F_UNLCK ){
363 zType = "UNLCK";
364 }else{
365 assert( 0 );
366 }
367 assert( p->l_whence==SEEK_SET );
368 s = fcntl(fd, op, p);
369 savedErrno = errno;
370 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
371 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
372 (int)p->l_pid, s);
373 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
374 struct flock l2;
375 l2 = *p;
376 fcntl(fd, F_GETLK, &l2);
377 if( l2.l_type==F_RDLCK ){
378 zType = "RDLCK";
379 }else if( l2.l_type==F_WRLCK ){
380 zType = "WRLCK";
381 }else if( l2.l_type==F_UNLCK ){
382 zType = "UNLCK";
383 }else{
384 assert( 0 );
385 }
386 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
387 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
388 }
389 errno = savedErrno;
390 return s;
391}
392#define fcntl lockTrace
393#endif /* SQLITE_LOCK_TRACE */
394
395
396
397/*
398** This routine translates a standard POSIX errno code into something
399** useful to the clients of the sqlite3 functions. Specifically, it is
400** intended to translate a variety of "try again" errors into SQLITE_BUSY
401** and a variety of "please close the file descriptor NOW" errors into
402** SQLITE_IOERR
403**
404** Errors during initialization of locks, or file system support for locks,
405** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
406*/
407static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
408 switch (posixError) {
409 case 0:
410 return SQLITE_OK;
411
412 case EAGAIN:
413 case ETIMEDOUT:
414 case EBUSY:
415 case EINTR:
416 case ENOLCK:
417 /* random NFS retry error, unless during file system support
418 * introspection, in which it actually means what it says */
419 return SQLITE_BUSY;
420
421 case EACCES:
422 /* EACCES is like EAGAIN during locking operations, but not any other time*/
423 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
424 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
425 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
426 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
427 return SQLITE_BUSY;
428 }
429 /* else fall through */
430 case EPERM:
431 return SQLITE_PERM;
432
433 case EDEADLK:
434 return SQLITE_IOERR_BLOCKED;
435
436#if EOPNOTSUPP!=ENOTSUP
437 case EOPNOTSUPP:
438 /* something went terribly awry, unless during file system support
439 * introspection, in which it actually means what it says */
440#endif
441#ifdef ENOTSUP
442 case ENOTSUP:
443 /* invalid fd, unless during file system support introspection, in which
444 * it actually means what it says */
445#endif
446 case EIO:
447 case EBADF:
448 case EINVAL:
449 case ENOTCONN:
450 case ENODEV:
451 case ENXIO:
452 case ENOENT:
453 case ESTALE:
454 case ENOSYS:
455 /* these should force the client to close the file and reconnect */
456
457 default:
458 return sqliteIOErr;
459 }
460}
461
462
463
464/******************************************************************************
465****************** Begin Unique File ID Utility Used By VxWorks ***************
466**
467** On most versions of unix, we can get a unique ID for a file by concatenating
468** the device number and the inode number. But this does not work on VxWorks.
469** On VxWorks, a unique file id must be based on the canonical filename.
470**
471** A pointer to an instance of the following structure can be used as a
472** unique file ID in VxWorks. Each instance of this structure contains
473** a copy of the canonical filename. There is also a reference count.
474** The structure is reclaimed when the number of pointers to it drops to
475** zero.
476**
477** There are never very many files open at one time and lookups are not
478** a performance-critical path, so it is sufficient to put these
479** structures on a linked list.
480*/
481struct vxworksFileId {
482 struct vxworksFileId *pNext; /* Next in a list of them all */
483 int nRef; /* Number of references to this one */
484 int nName; /* Length of the zCanonicalName[] string */
485 char *zCanonicalName; /* Canonical filename */
486};
487
488#if OS_VXWORKS
489/*
drh9b35ea62008-11-29 02:20:26 +0000490** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000491** variable:
492*/
493static struct vxworksFileId *vxworksFileList = 0;
494
495/*
496** Simplify a filename into its canonical form
497** by making the following changes:
498**
499** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000500** * convert /./ into just /
501** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000502**
503** Changes are made in-place. Return the new name length.
504**
505** The original filename is in z[0..n-1]. Return the number of
506** characters in the simplified name.
507*/
508static int vxworksSimplifyName(char *z, int n){
509 int i, j;
510 while( n>1 && z[n-1]=='/' ){ n--; }
511 for(i=j=0; i<n; i++){
512 if( z[i]=='/' ){
513 if( z[i+1]=='/' ) continue;
514 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
515 i += 1;
516 continue;
517 }
518 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
519 while( j>0 && z[j-1]!='/' ){ j--; }
520 if( j>0 ){ j--; }
521 i += 2;
522 continue;
523 }
524 }
525 z[j++] = z[i];
526 }
527 z[j] = 0;
528 return j;
529}
530
531/*
532** Find a unique file ID for the given absolute pathname. Return
533** a pointer to the vxworksFileId object. This pointer is the unique
534** file ID.
535**
536** The nRef field of the vxworksFileId object is incremented before
537** the object is returned. A new vxworksFileId object is created
538** and added to the global list if necessary.
539**
540** If a memory allocation error occurs, return NULL.
541*/
542static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
543 struct vxworksFileId *pNew; /* search key and new file ID */
544 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
545 int n; /* Length of zAbsoluteName string */
546
547 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000548 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000549 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
550 if( pNew==0 ) return 0;
551 pNew->zCanonicalName = (char*)&pNew[1];
552 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
553 n = vxworksSimplifyName(pNew->zCanonicalName, n);
554
555 /* Search for an existing entry that matching the canonical name.
556 ** If found, increment the reference count and return a pointer to
557 ** the existing file ID.
558 */
559 unixEnterMutex();
560 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
561 if( pCandidate->nName==n
562 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
563 ){
564 sqlite3_free(pNew);
565 pCandidate->nRef++;
566 unixLeaveMutex();
567 return pCandidate;
568 }
569 }
570
571 /* No match was found. We will make a new file ID */
572 pNew->nRef = 1;
573 pNew->nName = n;
574 pNew->pNext = vxworksFileList;
575 vxworksFileList = pNew;
576 unixLeaveMutex();
577 return pNew;
578}
579
580/*
581** Decrement the reference count on a vxworksFileId object. Free
582** the object when the reference count reaches zero.
583*/
584static void vxworksReleaseFileId(struct vxworksFileId *pId){
585 unixEnterMutex();
586 assert( pId->nRef>0 );
587 pId->nRef--;
588 if( pId->nRef==0 ){
589 struct vxworksFileId **pp;
590 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
591 assert( *pp==pId );
592 *pp = pId->pNext;
593 sqlite3_free(pId);
594 }
595 unixLeaveMutex();
596}
597#endif /* OS_VXWORKS */
598/*************** End of Unique File ID Utility Used By VxWorks ****************
599******************************************************************************/
600
601
602/******************************************************************************
603*************************** Posix Advisory Locking ****************************
604**
drh9b35ea62008-11-29 02:20:26 +0000605** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000606** section 6.5.2.2 lines 483 through 490 specify that when a process
607** sets or clears a lock, that operation overrides any prior locks set
608** by the same process. It does not explicitly say so, but this implies
609** that it overrides locks set by the same process using a different
610** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000611**
612** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000613** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
614**
615** Suppose ./file1 and ./file2 are really the same file (because
616** one is a hard or symbolic link to the other) then if you set
617** an exclusive lock on fd1, then try to get an exclusive lock
618** on fd2, it works. I would have expected the second lock to
619** fail since there was already a lock on the file due to fd1.
620** But not so. Since both locks came from the same process, the
621** second overrides the first, even though they were on different
622** file descriptors opened on different file names.
623**
drh734c9862008-11-28 15:37:20 +0000624** This means that we cannot use POSIX locks to synchronize file access
625** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000626** to synchronize access for threads in separate processes, but not
627** threads within the same process.
628**
629** To work around the problem, SQLite has to manage file locks internally
630** on its own. Whenever a new database is opened, we have to find the
631** specific inode of the database file (the inode is determined by the
632** st_dev and st_ino fields of the stat structure that fstat() fills in)
633** and check for locks already existing on that inode. When locks are
634** created or removed, we have to look at our own internal record of the
635** locks to see if another thread has previously set a lock on that same
636** inode.
637**
drh9b35ea62008-11-29 02:20:26 +0000638** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
639** For VxWorks, we have to use the alternative unique ID system based on
640** canonical filename and implemented in the previous division.)
641**
danielk1977ad94b582007-08-20 06:44:22 +0000642** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000643** descriptor. It is now a structure that holds the integer file
644** descriptor and a pointer to a structure that describes the internal
645** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000646** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000647** point to the same locking structure. The locking structure keeps
648** a reference count (so we will know when to delete it) and a "cnt"
649** field that tells us its internal lock status. cnt==0 means the
650** file is unlocked. cnt==-1 means the file has an exclusive lock.
651** cnt>0 means there are cnt shared locks on the file.
652**
653** Any attempt to lock or unlock a file first checks the locking
654** structure. The fcntl() system call is only invoked to set a
655** POSIX lock if the internal lock structure transitions between
656** a locked and an unlocked state.
657**
drh734c9862008-11-28 15:37:20 +0000658** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000659**
660** If you close a file descriptor that points to a file that has locks,
661** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000662** released. To work around this problem, each unixInodeInfo object
663** maintains a count of the number of pending locks on tha inode.
664** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000665** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000666** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000667** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000668** be closed and that list is walked (and cleared) when the last lock
669** clears.
670**
drh9b35ea62008-11-29 02:20:26 +0000671** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000672**
drh9b35ea62008-11-29 02:20:26 +0000673** Many older versions of linux use the LinuxThreads library which is
674** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000675** A cannot be modified or overridden by a different thread B.
676** Only thread A can modify the lock. Locking behavior is correct
677** if the appliation uses the newer Native Posix Thread Library (NPTL)
678** on linux - with NPTL a lock created by thread A can override locks
679** in thread B. But there is no way to know at compile-time which
680** threading library is being used. So there is no way to know at
681** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000682** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000683** current process.
drh5fdae772004-06-29 03:29:00 +0000684**
drh8af6c222010-05-14 12:43:01 +0000685** SQLite used to support LinuxThreads. But support for LinuxThreads
686** was dropped beginning with version 3.7.0. SQLite will still work with
687** LinuxThreads provided that (1) there is no more than one connection
688** per database file in the same process and (2) database connections
689** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000690*/
691
692/*
693** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000694** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000695*/
696struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000697 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000698#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000699 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000700#else
drh107886a2008-11-21 22:21:50 +0000701 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000702#endif
703};
704
705/*
drhbbd42a62004-05-22 17:41:58 +0000706** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000707** inode. Or, on LinuxThreads, there is one of these structures for
708** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000709**
danielk1977ad94b582007-08-20 06:44:22 +0000710** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000711** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000712** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000713*/
drh8af6c222010-05-14 12:43:01 +0000714struct unixInodeInfo {
715 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000716 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000717 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000718 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000719 unixShmNode *pShmNode; /* Shared memory associated with this inode */
720 int nLock; /* Number of outstanding file locks */
721 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
722 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
723 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000724#if defined(SQLITE_ENABLE_LOCKING_STYLE)
725 unsigned long long sharedByte; /* for AFP simulated shared lock */
726#endif
drh6c7d5c52008-11-21 20:32:33 +0000727#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000728 sem_t *pSem; /* Named POSIX semaphore */
729 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000730#endif
drhbbd42a62004-05-22 17:41:58 +0000731};
732
drhda0e7682008-07-30 15:27:54 +0000733/*
drh8af6c222010-05-14 12:43:01 +0000734** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000735*/
drhd91c68f2010-05-14 14:52:25 +0000736static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000737
drh5fdae772004-06-29 03:29:00 +0000738/*
drh8af6c222010-05-14 12:43:01 +0000739** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000740**
741** The mutex entered using the unixEnterMutex() function must be held
742** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000743*/
drhd91c68f2010-05-14 14:52:25 +0000744static void releaseInodeInfo(unixInodeInfo *pInode){
dan9359c7b2009-08-21 08:29:10 +0000745 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000746 if( pInode ){
747 pInode->nRef--;
748 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000749 assert( pInode->pShmNode==0 );
drh8af6c222010-05-14 12:43:01 +0000750 if( pInode->pPrev ){
751 assert( pInode->pPrev->pNext==pInode );
752 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000753 }else{
drh8af6c222010-05-14 12:43:01 +0000754 assert( inodeList==pInode );
755 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000756 }
drh8af6c222010-05-14 12:43:01 +0000757 if( pInode->pNext ){
758 assert( pInode->pNext->pPrev==pInode );
759 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000760 }
drh8af6c222010-05-14 12:43:01 +0000761 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000762 }
drhbbd42a62004-05-22 17:41:58 +0000763 }
764}
765
766/*
drh8af6c222010-05-14 12:43:01 +0000767** Given a file descriptor, locate the unixInodeInfo object that
768** describes that file descriptor. Create a new one if necessary. The
769** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000770**
dan9359c7b2009-08-21 08:29:10 +0000771** The mutex entered using the unixEnterMutex() function must be held
772** when this function is called.
773**
drh6c7d5c52008-11-21 20:32:33 +0000774** Return an appropriate error code.
775*/
drh8af6c222010-05-14 12:43:01 +0000776static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000777 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000778 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000779){
780 int rc; /* System call return code */
781 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000782 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
783 struct stat statbuf; /* Low-level file information */
784 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000785
dan9359c7b2009-08-21 08:29:10 +0000786 assert( unixMutexHeld() );
787
drh6c7d5c52008-11-21 20:32:33 +0000788 /* Get low-level information about the file that we can used to
789 ** create a unique name for the file.
790 */
791 fd = pFile->h;
792 rc = fstat(fd, &statbuf);
793 if( rc!=0 ){
794 pFile->lastErrno = errno;
795#ifdef EOVERFLOW
796 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
797#endif
798 return SQLITE_IOERR;
799 }
800
drheb0d74f2009-02-03 15:27:02 +0000801#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000802 /* On OS X on an msdos filesystem, the inode number is reported
803 ** incorrectly for zero-size files. See ticket #3260. To work
804 ** around this problem (we consider it a bug in OS X, not SQLite)
805 ** we always increase the file size to 1 by writing a single byte
806 ** prior to accessing the inode number. The one byte written is
807 ** an ASCII 'S' character which also happens to be the first byte
808 ** in the header of every SQLite database. In this way, if there
809 ** is a race condition such that another thread has already populated
810 ** the first page of the database, no damage is done.
811 */
drh7ed97b92010-01-20 13:07:21 +0000812 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +0000813 rc = write(fd, "S", 1);
814 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000815 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000816 return SQLITE_IOERR;
817 }
drh6c7d5c52008-11-21 20:32:33 +0000818 rc = fstat(fd, &statbuf);
819 if( rc!=0 ){
820 pFile->lastErrno = errno;
821 return SQLITE_IOERR;
822 }
823 }
drheb0d74f2009-02-03 15:27:02 +0000824#endif
drh6c7d5c52008-11-21 20:32:33 +0000825
drh8af6c222010-05-14 12:43:01 +0000826 memset(&fileId, 0, sizeof(fileId));
827 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000828#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000829 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000830#else
drh8af6c222010-05-14 12:43:01 +0000831 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000832#endif
drh8af6c222010-05-14 12:43:01 +0000833 pInode = inodeList;
834 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
835 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000836 }
drh8af6c222010-05-14 12:43:01 +0000837 if( pInode==0 ){
838 pInode = sqlite3_malloc( sizeof(*pInode) );
839 if( pInode==0 ){
840 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000841 }
drh8af6c222010-05-14 12:43:01 +0000842 memset(pInode, 0, sizeof(*pInode));
843 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
844 pInode->nRef = 1;
845 pInode->pNext = inodeList;
846 pInode->pPrev = 0;
847 if( inodeList ) inodeList->pPrev = pInode;
848 inodeList = pInode;
849 }else{
850 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000851 }
drh8af6c222010-05-14 12:43:01 +0000852 *ppInode = pInode;
853 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000854}
drh6c7d5c52008-11-21 20:32:33 +0000855
aswift5b1a2562008-08-22 00:22:35 +0000856
857/*
danielk197713adf8a2004-06-03 16:08:41 +0000858** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000859** file by this or any other process. If such a lock is held, set *pResOut
860** to a non-zero value otherwise *pResOut is set to zero. The return value
861** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000862*/
danielk1977861f7452008-06-05 11:39:11 +0000863static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000864 int rc = SQLITE_OK;
865 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000866 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000867
danielk1977861f7452008-06-05 11:39:11 +0000868 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
869
drh054889e2005-11-30 03:20:31 +0000870 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000871 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000872
873 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000874 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000875 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000876 }
877
drh2ac3ee92004-06-07 16:27:46 +0000878 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000879 */
danielk197709480a92009-02-09 05:32:32 +0000880#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000881 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000882 struct flock lock;
883 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000884 lock.l_start = RESERVED_BYTE;
885 lock.l_len = 1;
886 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +0000887 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
888 int tErrno = errno;
889 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
890 pFile->lastErrno = tErrno;
891 } else if( lock.l_type!=F_UNLCK ){
892 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000893 }
894 }
danielk197709480a92009-02-09 05:32:32 +0000895#endif
danielk197713adf8a2004-06-03 16:08:41 +0000896
drh6c7d5c52008-11-21 20:32:33 +0000897 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +0000898 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +0000899
aswift5b1a2562008-08-22 00:22:35 +0000900 *pResOut = reserved;
901 return rc;
danielk197713adf8a2004-06-03 16:08:41 +0000902}
903
904/*
drh308c2a52010-05-14 11:30:18 +0000905** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +0000906** of the following:
907**
drh2ac3ee92004-06-07 16:27:46 +0000908** (1) SHARED_LOCK
909** (2) RESERVED_LOCK
910** (3) PENDING_LOCK
911** (4) EXCLUSIVE_LOCK
912**
drhb3e04342004-06-08 00:47:47 +0000913** Sometimes when requesting one lock state, additional lock states
914** are inserted in between. The locking might fail on one of the later
915** transitions leaving the lock state different from what it started but
916** still short of its goal. The following chart shows the allowed
917** transitions and the inserted intermediate states:
918**
919** UNLOCKED -> SHARED
920** SHARED -> RESERVED
921** SHARED -> (PENDING) -> EXCLUSIVE
922** RESERVED -> (PENDING) -> EXCLUSIVE
923** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000924**
drha6abd042004-06-09 17:37:22 +0000925** This routine will only increase a lock. Use the sqlite3OsUnlock()
926** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000927*/
drh308c2a52010-05-14 11:30:18 +0000928static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +0000929 /* The following describes the implementation of the various locks and
930 ** lock transitions in terms of the POSIX advisory shared and exclusive
931 ** lock primitives (called read-locks and write-locks below, to avoid
932 ** confusion with SQLite lock names). The algorithms are complicated
933 ** slightly in order to be compatible with windows systems simultaneously
934 ** accessing the same database file, in case that is ever required.
935 **
936 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
937 ** byte', each single bytes at well known offsets, and the 'shared byte
938 ** range', a range of 510 bytes at a well known offset.
939 **
940 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
941 ** byte'. If this is successful, a random byte from the 'shared byte
942 ** range' is read-locked and the lock on the 'pending byte' released.
943 **
danielk197790ba3bd2004-06-25 08:32:25 +0000944 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
945 ** A RESERVED lock is implemented by grabbing a write-lock on the
946 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000947 **
948 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000949 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
950 ** on the 'pending byte'. This ensures that no new SHARED locks can be
951 ** obtained, but existing SHARED locks are allowed to persist. A process
952 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
953 ** This property is used by the algorithm for rolling back a journal file
954 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000955 **
danielk197790ba3bd2004-06-25 08:32:25 +0000956 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
957 ** implemented by obtaining a write-lock on the entire 'shared byte
958 ** range'. Since all other locks require a read-lock on one of the bytes
959 ** within this range, this ensures that no other locks are held on the
960 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000961 **
962 ** The reason a single byte cannot be used instead of the 'shared byte
963 ** range' is that some versions of windows do not support read-locks. By
964 ** locking a random byte from a range, concurrent SHARED locks may exist
965 ** even if the locking primitive used is always a write-lock.
966 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000967 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +0000968 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +0000969 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +0000970 struct flock lock;
drh3f022182009-09-09 16:10:50 +0000971 int s = 0;
drh383d30f2010-02-26 13:07:37 +0000972 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000973
drh054889e2005-11-30 03:20:31 +0000974 assert( pFile );
drh308c2a52010-05-14 11:30:18 +0000975 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
976 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +0000977 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +0000978
979 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +0000980 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +0000981 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +0000982 */
drh308c2a52010-05-14 11:30:18 +0000983 if( pFile->eFileLock>=eFileLock ){
984 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
985 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +0000986 return SQLITE_OK;
987 }
988
drh0c2694b2009-09-03 16:23:44 +0000989 /* Make sure the locking sequence is correct.
990 ** (1) We never move from unlocked to anything higher than shared lock.
991 ** (2) SQLite never explicitly requests a pendig lock.
992 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +0000993 */
drh308c2a52010-05-14 11:30:18 +0000994 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
995 assert( eFileLock!=PENDING_LOCK );
996 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000997
drh8af6c222010-05-14 12:43:01 +0000998 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +0000999 */
drh6c7d5c52008-11-21 20:32:33 +00001000 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001001 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001002
danielk1977ad94b582007-08-20 06:44:22 +00001003 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001004 ** handle that precludes the requested lock, return BUSY.
1005 */
drh8af6c222010-05-14 12:43:01 +00001006 if( (pFile->eFileLock!=pInode->eFileLock &&
1007 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001008 ){
1009 rc = SQLITE_BUSY;
1010 goto end_lock;
1011 }
1012
1013 /* If a SHARED lock is requested, and some thread using this PID already
1014 ** has a SHARED or RESERVED lock, then increment reference counts and
1015 ** return SQLITE_OK.
1016 */
drh308c2a52010-05-14 11:30:18 +00001017 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001018 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001019 assert( eFileLock==SHARED_LOCK );
1020 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001021 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001022 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001023 pInode->nShared++;
1024 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001025 goto end_lock;
1026 }
1027
danielk19779a1d0ab2004-06-01 14:09:28 +00001028
drh3cde3bb2004-06-12 02:17:14 +00001029 /* A PENDING lock is needed before acquiring a SHARED lock and before
1030 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1031 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001032 */
drh0c2694b2009-09-03 16:23:44 +00001033 lock.l_len = 1L;
1034 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001035 if( eFileLock==SHARED_LOCK
1036 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001037 ){
drh308c2a52010-05-14 11:30:18 +00001038 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001039 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001040 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001041 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001042 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001043 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1044 if( IS_LOCK_ERROR(rc) ){
1045 pFile->lastErrno = tErrno;
1046 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001047 goto end_lock;
1048 }
drh3cde3bb2004-06-12 02:17:14 +00001049 }
1050
1051
1052 /* If control gets to this point, then actually go ahead and make
1053 ** operating system calls for the specified lock.
1054 */
drh308c2a52010-05-14 11:30:18 +00001055 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001056 assert( pInode->nShared==0 );
1057 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001058
drh2ac3ee92004-06-07 16:27:46 +00001059 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001060 lock.l_start = SHARED_FIRST;
1061 lock.l_len = SHARED_SIZE;
1062 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1063 tErrno = errno;
1064 }
drh2ac3ee92004-06-07 16:27:46 +00001065 /* Drop the temporary PENDING lock */
1066 lock.l_start = PENDING_BYTE;
1067 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001068 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001069 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001070 if( s != -1 ){
1071 /* This could happen with a network mount */
1072 tErrno = errno;
1073 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1074 if( IS_LOCK_ERROR(rc) ){
1075 pFile->lastErrno = tErrno;
1076 }
1077 goto end_lock;
1078 }
drh2b4b5962005-06-15 17:47:55 +00001079 }
drhe2396a12007-03-29 20:19:58 +00001080 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001081 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1082 if( IS_LOCK_ERROR(rc) ){
1083 pFile->lastErrno = tErrno;
1084 }
drhbbd42a62004-05-22 17:41:58 +00001085 }else{
drh308c2a52010-05-14 11:30:18 +00001086 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001087 pInode->nLock++;
1088 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001089 }
drh8af6c222010-05-14 12:43:01 +00001090 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001091 /* We are trying for an exclusive lock but another thread in this
1092 ** same process is still holding a shared lock. */
1093 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001094 }else{
drh3cde3bb2004-06-12 02:17:14 +00001095 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001096 ** assumed that there is a SHARED or greater lock on the file
1097 ** already.
1098 */
drh308c2a52010-05-14 11:30:18 +00001099 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001100 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001101 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001102 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001103 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001104 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001105 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001106 lock.l_start = SHARED_FIRST;
1107 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001108 break;
1109 default:
1110 assert(0);
1111 }
drh7ed97b92010-01-20 13:07:21 +00001112 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001113 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001114 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001115 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1116 if( IS_LOCK_ERROR(rc) ){
1117 pFile->lastErrno = tErrno;
1118 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001119 }
drhbbd42a62004-05-22 17:41:58 +00001120 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001121
drh8f941bc2009-01-14 23:03:40 +00001122
1123#ifndef NDEBUG
1124 /* Set up the transaction-counter change checking flags when
1125 ** transitioning from a SHARED to a RESERVED lock. The change
1126 ** from SHARED to RESERVED marks the beginning of a normal
1127 ** write operation (not a hot journal rollback).
1128 */
1129 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001130 && pFile->eFileLock<=SHARED_LOCK
1131 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001132 ){
1133 pFile->transCntrChng = 0;
1134 pFile->dbUpdate = 0;
1135 pFile->inNormalWrite = 1;
1136 }
1137#endif
1138
1139
danielk1977ecb2a962004-06-02 06:30:16 +00001140 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001141 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001142 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001143 }else if( eFileLock==EXCLUSIVE_LOCK ){
1144 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001145 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001146 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001147
1148end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001149 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001150 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1151 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001152 return rc;
1153}
1154
1155/*
drh8af6c222010-05-14 12:43:01 +00001156** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
dane946c392009-08-22 11:39:46 +00001157** If all such file descriptors are closed without error, the list is
1158** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001159**
1160** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001161** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001162** not deleted and SQLITE_IOERR_CLOSE returned.
1163*/
1164static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001165 int rc = SQLITE_OK;
drhd91c68f2010-05-14 14:52:25 +00001166 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001167 UnixUnusedFd *pError = 0;
1168 UnixUnusedFd *p;
1169 UnixUnusedFd *pNext;
drh8af6c222010-05-14 12:43:01 +00001170 for(p=pInode->pUnused; p; p=pNext){
dane946c392009-08-22 11:39:46 +00001171 pNext = p->pNext;
1172 if( close(p->fd) ){
1173 pFile->lastErrno = errno;
1174 rc = SQLITE_IOERR_CLOSE;
1175 p->pNext = pError;
1176 pError = p;
dane946c392009-08-22 11:39:46 +00001177 }else{
1178 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001179 }
1180 }
drh8af6c222010-05-14 12:43:01 +00001181 pInode->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001182 return rc;
1183}
1184
1185/*
1186** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001187** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001188*/
1189static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001190 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001191 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001192 p->pNext = pInode->pUnused;
1193 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001194 pFile->h = -1;
1195 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001196}
1197
1198/*
drh308c2a52010-05-14 11:30:18 +00001199** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001200** must be either NO_LOCK or SHARED_LOCK.
1201**
1202** If the locking level of the file descriptor is already at or below
1203** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001204**
1205** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1206** the byte range is divided into 2 parts and the first part is unlocked then
1207** set to a read lock, then the other part is simply unlocked. This works
1208** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1209** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001210*/
drh308c2a52010-05-14 11:30:18 +00001211static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001212 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001213 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001214 struct flock lock;
1215 int rc = SQLITE_OK;
1216 int h;
drh0c2694b2009-09-03 16:23:44 +00001217 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001218
drh054889e2005-11-30 03:20:31 +00001219 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001220 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001221 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001222 getpid()));
drha6abd042004-06-09 17:37:22 +00001223
drh308c2a52010-05-14 11:30:18 +00001224 assert( eFileLock<=SHARED_LOCK );
1225 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001226 return SQLITE_OK;
1227 }
drh6c7d5c52008-11-21 20:32:33 +00001228 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001229 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001230 pInode = pFile->pInode;
1231 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001232 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001233 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001234 SimulateIOErrorBenign(1);
1235 SimulateIOError( h=(-1) )
1236 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001237
1238#ifndef NDEBUG
1239 /* When reducing a lock such that other processes can start
1240 ** reading the database file again, make sure that the
1241 ** transaction counter was updated if any part of the database
1242 ** file changed. If the transaction counter is not updated,
1243 ** other connections to the same file might not realize that
1244 ** the file has changed and hence might not know to flush their
1245 ** cache. The use of a stale cache can lead to database corruption.
1246 */
dan7c246102010-04-12 19:00:29 +00001247#if 0
drh8f941bc2009-01-14 23:03:40 +00001248 assert( pFile->inNormalWrite==0
1249 || pFile->dbUpdate==0
1250 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001251#endif
drh8f941bc2009-01-14 23:03:40 +00001252 pFile->inNormalWrite = 0;
1253#endif
1254
drh7ed97b92010-01-20 13:07:21 +00001255 /* downgrading to a shared lock on NFS involves clearing the write lock
1256 ** before establishing the readlock - to avoid a race condition we downgrade
1257 ** the lock in 2 blocks, so that part of the range will be covered by a
1258 ** write lock until the rest is covered by a read lock:
1259 ** 1: [WWWWW]
1260 ** 2: [....W]
1261 ** 3: [RRRRW]
1262 ** 4: [RRRR.]
1263 */
drh308c2a52010-05-14 11:30:18 +00001264 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001265 if( handleNFSUnlock ){
1266 off_t divSize = SHARED_SIZE - 1;
1267
1268 lock.l_type = F_UNLCK;
1269 lock.l_whence = SEEK_SET;
1270 lock.l_start = SHARED_FIRST;
1271 lock.l_len = divSize;
1272 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001273 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001274 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1275 if( IS_LOCK_ERROR(rc) ){
1276 pFile->lastErrno = tErrno;
1277 }
1278 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001279 }
drh7ed97b92010-01-20 13:07:21 +00001280 lock.l_type = F_RDLCK;
1281 lock.l_whence = SEEK_SET;
1282 lock.l_start = SHARED_FIRST;
1283 lock.l_len = divSize;
1284 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001285 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001286 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1287 if( IS_LOCK_ERROR(rc) ){
1288 pFile->lastErrno = tErrno;
1289 }
1290 goto end_unlock;
1291 }
1292 lock.l_type = F_UNLCK;
1293 lock.l_whence = SEEK_SET;
1294 lock.l_start = SHARED_FIRST+divSize;
1295 lock.l_len = SHARED_SIZE-divSize;
1296 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001297 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001298 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1299 if( IS_LOCK_ERROR(rc) ){
1300 pFile->lastErrno = tErrno;
1301 }
1302 goto end_unlock;
1303 }
1304 }else{
1305 lock.l_type = F_RDLCK;
1306 lock.l_whence = SEEK_SET;
1307 lock.l_start = SHARED_FIRST;
1308 lock.l_len = SHARED_SIZE;
1309 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001310 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001311 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1312 if( IS_LOCK_ERROR(rc) ){
1313 pFile->lastErrno = tErrno;
1314 }
1315 goto end_unlock;
1316 }
drh9c105bb2004-10-02 20:38:28 +00001317 }
1318 }
drhbbd42a62004-05-22 17:41:58 +00001319 lock.l_type = F_UNLCK;
1320 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001321 lock.l_start = PENDING_BYTE;
1322 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001323 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001324 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001325 }else{
drh0c2694b2009-09-03 16:23:44 +00001326 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001327 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1328 if( IS_LOCK_ERROR(rc) ){
1329 pFile->lastErrno = tErrno;
1330 }
drhcd731cf2009-03-28 23:23:02 +00001331 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001332 }
drhbbd42a62004-05-22 17:41:58 +00001333 }
drh308c2a52010-05-14 11:30:18 +00001334 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001335 /* Decrement the shared lock counter. Release the lock using an
1336 ** OS call only when all threads in this same process have released
1337 ** the lock.
1338 */
drh8af6c222010-05-14 12:43:01 +00001339 pInode->nShared--;
1340 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001341 lock.l_type = F_UNLCK;
1342 lock.l_whence = SEEK_SET;
1343 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001344 SimulateIOErrorBenign(1);
1345 SimulateIOError( h=(-1) )
1346 SimulateIOErrorBenign(0);
1347 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001348 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001349 }else{
drh0c2694b2009-09-03 16:23:44 +00001350 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001351 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001352 if( IS_LOCK_ERROR(rc) ){
1353 pFile->lastErrno = tErrno;
1354 }
drh8af6c222010-05-14 12:43:01 +00001355 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001356 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001357 }
drha6abd042004-06-09 17:37:22 +00001358 }
1359
drhbbd42a62004-05-22 17:41:58 +00001360 /* Decrement the count of locks against this same file. When the
1361 ** count reaches zero, close any other file descriptors whose close
1362 ** was deferred because of outstanding locks.
1363 */
drh8af6c222010-05-14 12:43:01 +00001364 pInode->nLock--;
1365 assert( pInode->nLock>=0 );
1366 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001367 int rc2 = closePendingFds(pFile);
1368 if( rc==SQLITE_OK ){
1369 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001370 }
drhbbd42a62004-05-22 17:41:58 +00001371 }
1372 }
aswift5b1a2562008-08-22 00:22:35 +00001373
1374end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001375 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001376 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001377 return rc;
drhbbd42a62004-05-22 17:41:58 +00001378}
1379
1380/*
drh308c2a52010-05-14 11:30:18 +00001381** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001382** must be either NO_LOCK or SHARED_LOCK.
1383**
1384** If the locking level of the file descriptor is already at or below
1385** the requested locking level, this routine is a no-op.
1386*/
drh308c2a52010-05-14 11:30:18 +00001387static int unixUnlock(sqlite3_file *id, int eFileLock){
1388 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001389}
1390
1391/*
danielk1977e339d652008-06-28 11:23:00 +00001392** This function performs the parts of the "close file" operation
1393** common to all locking schemes. It closes the directory and file
1394** handles, if they are valid, and sets all fields of the unixFile
1395** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001396**
1397** It is *not* necessary to hold the mutex when this routine is called,
1398** even on VxWorks. A mutex will be acquired on VxWorks by the
1399** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001400*/
1401static int closeUnixFile(sqlite3_file *id){
1402 unixFile *pFile = (unixFile*)id;
1403 if( pFile ){
1404 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001405 int err = close(pFile->dirfd);
1406 if( err ){
1407 pFile->lastErrno = errno;
1408 return SQLITE_IOERR_DIR_CLOSE;
1409 }else{
1410 pFile->dirfd=-1;
1411 }
danielk1977e339d652008-06-28 11:23:00 +00001412 }
1413 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001414 int err = close(pFile->h);
1415 if( err ){
1416 pFile->lastErrno = errno;
1417 return SQLITE_IOERR_CLOSE;
1418 }
danielk1977e339d652008-06-28 11:23:00 +00001419 }
drh6c7d5c52008-11-21 20:32:33 +00001420#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001421 if( pFile->pId ){
1422 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001423 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001424 }
drh107886a2008-11-21 22:21:50 +00001425 vxworksReleaseFileId(pFile->pId);
1426 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001427 }
1428#endif
drhff59a112010-05-14 20:15:51 +00001429 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001430 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001431 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001432 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001433 }
1434 return SQLITE_OK;
1435}
1436
1437/*
danielk1977e3026632004-06-22 11:29:02 +00001438** Close a file.
1439*/
danielk197762079062007-08-15 17:08:46 +00001440static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001441 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001442 if( id ){
1443 unixFile *pFile = (unixFile *)id;
1444 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001445 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001446 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001447 /* If there are outstanding locks, do not actually close the file just
1448 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001449 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001450 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001451 */
dan08da86a2009-08-21 17:18:03 +00001452 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001453 }
drh8af6c222010-05-14 12:43:01 +00001454 releaseInodeInfo(pFile->pInode);
aswiftaebf4132008-11-21 00:10:35 +00001455 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001456 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001457 }
aswiftaebf4132008-11-21 00:10:35 +00001458 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001459}
1460
drh734c9862008-11-28 15:37:20 +00001461/************** End of the posix advisory lock implementation *****************
1462******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001463
drh734c9862008-11-28 15:37:20 +00001464/******************************************************************************
1465****************************** No-op Locking **********************************
1466**
1467** Of the various locking implementations available, this is by far the
1468** simplest: locking is ignored. No attempt is made to lock the database
1469** file for reading or writing.
1470**
1471** This locking mode is appropriate for use on read-only databases
1472** (ex: databases that are burned into CD-ROM, for example.) It can
1473** also be used if the application employs some external mechanism to
1474** prevent simultaneous access of the same database by two or more
1475** database connections. But there is a serious risk of database
1476** corruption if this locking mode is used in situations where multiple
1477** database connections are accessing the same database file at the same
1478** time and one or more of those connections are writing.
1479*/
drhbfe66312006-10-03 17:40:40 +00001480
drh734c9862008-11-28 15:37:20 +00001481static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1482 UNUSED_PARAMETER(NotUsed);
1483 *pResOut = 0;
1484 return SQLITE_OK;
1485}
drh734c9862008-11-28 15:37:20 +00001486static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1487 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1488 return SQLITE_OK;
1489}
drh734c9862008-11-28 15:37:20 +00001490static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1491 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1492 return SQLITE_OK;
1493}
1494
1495/*
drh9b35ea62008-11-29 02:20:26 +00001496** Close the file.
drh734c9862008-11-28 15:37:20 +00001497*/
1498static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001499 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001500}
1501
1502/******************* End of the no-op lock implementation *********************
1503******************************************************************************/
1504
1505/******************************************************************************
1506************************* Begin dot-file Locking ******************************
1507**
drh0c2694b2009-09-03 16:23:44 +00001508** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001509** files in order to control access to the database. This works on just
1510** about every filesystem imaginable. But there are serious downsides:
1511**
1512** (1) There is zero concurrency. A single reader blocks all other
1513** connections from reading or writing the database.
1514**
1515** (2) An application crash or power loss can leave stale lock files
1516** sitting around that need to be cleared manually.
1517**
1518** Nevertheless, a dotlock is an appropriate locking mode for use if no
1519** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001520**
1521** Dotfile locking works by creating a file in the same directory as the
1522** database and with the same name but with a ".lock" extension added.
1523** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1524** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001525*/
1526
1527/*
1528** The file suffix added to the data base filename in order to create the
1529** lock file.
1530*/
1531#define DOTLOCK_SUFFIX ".lock"
1532
drh7708e972008-11-29 00:56:52 +00001533/*
1534** This routine checks if there is a RESERVED lock held on the specified
1535** file by this or any other process. If such a lock is held, set *pResOut
1536** to a non-zero value otherwise *pResOut is set to zero. The return value
1537** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1538**
1539** In dotfile locking, either a lock exists or it does not. So in this
1540** variation of CheckReservedLock(), *pResOut is set to true if any lock
1541** is held on the file and false if the file is unlocked.
1542*/
drh734c9862008-11-28 15:37:20 +00001543static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1544 int rc = SQLITE_OK;
1545 int reserved = 0;
1546 unixFile *pFile = (unixFile*)id;
1547
1548 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1549
1550 assert( pFile );
1551
1552 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001553 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001554 /* Either this connection or some other connection in the same process
1555 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001556 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001557 }else{
1558 /* The lock is held if and only if the lockfile exists */
1559 const char *zLockFile = (const char*)pFile->lockingContext;
1560 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001561 }
drh308c2a52010-05-14 11:30:18 +00001562 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001563 *pResOut = reserved;
1564 return rc;
1565}
1566
drh7708e972008-11-29 00:56:52 +00001567/*
drh308c2a52010-05-14 11:30:18 +00001568** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001569** of the following:
1570**
1571** (1) SHARED_LOCK
1572** (2) RESERVED_LOCK
1573** (3) PENDING_LOCK
1574** (4) EXCLUSIVE_LOCK
1575**
1576** Sometimes when requesting one lock state, additional lock states
1577** are inserted in between. The locking might fail on one of the later
1578** transitions leaving the lock state different from what it started but
1579** still short of its goal. The following chart shows the allowed
1580** transitions and the inserted intermediate states:
1581**
1582** UNLOCKED -> SHARED
1583** SHARED -> RESERVED
1584** SHARED -> (PENDING) -> EXCLUSIVE
1585** RESERVED -> (PENDING) -> EXCLUSIVE
1586** PENDING -> EXCLUSIVE
1587**
1588** This routine will only increase a lock. Use the sqlite3OsUnlock()
1589** routine to lower a locking level.
1590**
1591** With dotfile locking, we really only support state (4): EXCLUSIVE.
1592** But we track the other locking levels internally.
1593*/
drh308c2a52010-05-14 11:30:18 +00001594static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001595 unixFile *pFile = (unixFile*)id;
1596 int fd;
1597 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001598 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001599
drh7708e972008-11-29 00:56:52 +00001600
1601 /* If we have any lock, then the lock file already exists. All we have
1602 ** to do is adjust our internal record of the lock level.
1603 */
drh308c2a52010-05-14 11:30:18 +00001604 if( pFile->eFileLock > NO_LOCK ){
1605 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001606#if !OS_VXWORKS
1607 /* Always update the timestamp on the old file */
1608 utimes(zLockFile, NULL);
1609#endif
drh7708e972008-11-29 00:56:52 +00001610 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001611 }
1612
1613 /* grab an exclusive lock */
1614 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1615 if( fd<0 ){
1616 /* failed to open/create the file, someone else may have stolen the lock */
1617 int tErrno = errno;
1618 if( EEXIST == tErrno ){
1619 rc = SQLITE_BUSY;
1620 } else {
1621 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1622 if( IS_LOCK_ERROR(rc) ){
1623 pFile->lastErrno = tErrno;
1624 }
1625 }
drh7708e972008-11-29 00:56:52 +00001626 return rc;
drh734c9862008-11-28 15:37:20 +00001627 }
1628 if( close(fd) ){
1629 pFile->lastErrno = errno;
1630 rc = SQLITE_IOERR_CLOSE;
1631 }
1632
1633 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001634 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001635 return rc;
1636}
1637
drh7708e972008-11-29 00:56:52 +00001638/*
drh308c2a52010-05-14 11:30:18 +00001639** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001640** must be either NO_LOCK or SHARED_LOCK.
1641**
1642** If the locking level of the file descriptor is already at or below
1643** the requested locking level, this routine is a no-op.
1644**
1645** When the locking level reaches NO_LOCK, delete the lock file.
1646*/
drh308c2a52010-05-14 11:30:18 +00001647static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001648 unixFile *pFile = (unixFile*)id;
1649 char *zLockFile = (char *)pFile->lockingContext;
1650
1651 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001652 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1653 pFile->eFileLock, getpid()));
1654 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001655
1656 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001657 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001658 return SQLITE_OK;
1659 }
drh7708e972008-11-29 00:56:52 +00001660
1661 /* To downgrade to shared, simply update our internal notion of the
1662 ** lock state. No need to mess with the file on disk.
1663 */
drh308c2a52010-05-14 11:30:18 +00001664 if( eFileLock==SHARED_LOCK ){
1665 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001666 return SQLITE_OK;
1667 }
1668
drh7708e972008-11-29 00:56:52 +00001669 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001670 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001671 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001672 int rc = 0;
1673 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001674 if( ENOENT != tErrno ){
1675 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1676 }
1677 if( IS_LOCK_ERROR(rc) ){
1678 pFile->lastErrno = tErrno;
1679 }
1680 return rc;
1681 }
drh308c2a52010-05-14 11:30:18 +00001682 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001683 return SQLITE_OK;
1684}
1685
1686/*
drh9b35ea62008-11-29 02:20:26 +00001687** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001688*/
1689static int dotlockClose(sqlite3_file *id) {
1690 int rc;
1691 if( id ){
1692 unixFile *pFile = (unixFile*)id;
1693 dotlockUnlock(id, NO_LOCK);
1694 sqlite3_free(pFile->lockingContext);
1695 }
drh734c9862008-11-28 15:37:20 +00001696 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001697 return rc;
1698}
1699/****************** End of the dot-file lock implementation *******************
1700******************************************************************************/
1701
1702/******************************************************************************
1703************************** Begin flock Locking ********************************
1704**
1705** Use the flock() system call to do file locking.
1706**
drh6b9d6dd2008-12-03 19:34:47 +00001707** flock() locking is like dot-file locking in that the various
1708** fine-grain locking levels supported by SQLite are collapsed into
1709** a single exclusive lock. In other words, SHARED, RESERVED, and
1710** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1711** still works when you do this, but concurrency is reduced since
1712** only a single process can be reading the database at a time.
1713**
drh734c9862008-11-28 15:37:20 +00001714** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1715** compiling for VXWORKS.
1716*/
1717#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001718
drh6b9d6dd2008-12-03 19:34:47 +00001719/*
1720** This routine checks if there is a RESERVED lock held on the specified
1721** file by this or any other process. If such a lock is held, set *pResOut
1722** to a non-zero value otherwise *pResOut is set to zero. The return value
1723** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1724*/
drh734c9862008-11-28 15:37:20 +00001725static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1726 int rc = SQLITE_OK;
1727 int reserved = 0;
1728 unixFile *pFile = (unixFile*)id;
1729
1730 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1731
1732 assert( pFile );
1733
1734 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001735 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001736 reserved = 1;
1737 }
1738
1739 /* Otherwise see if some other process holds it. */
1740 if( !reserved ){
1741 /* attempt to get the lock */
1742 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1743 if( !lrc ){
1744 /* got the lock, unlock it */
1745 lrc = flock(pFile->h, LOCK_UN);
1746 if ( lrc ) {
1747 int tErrno = errno;
1748 /* unlock failed with an error */
1749 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1750 if( IS_LOCK_ERROR(lrc) ){
1751 pFile->lastErrno = tErrno;
1752 rc = lrc;
1753 }
1754 }
1755 } else {
1756 int tErrno = errno;
1757 reserved = 1;
1758 /* someone else might have it reserved */
1759 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1760 if( IS_LOCK_ERROR(lrc) ){
1761 pFile->lastErrno = tErrno;
1762 rc = lrc;
1763 }
1764 }
1765 }
drh308c2a52010-05-14 11:30:18 +00001766 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001767
1768#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1769 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1770 rc = SQLITE_OK;
1771 reserved=1;
1772 }
1773#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1774 *pResOut = reserved;
1775 return rc;
1776}
1777
drh6b9d6dd2008-12-03 19:34:47 +00001778/*
drh308c2a52010-05-14 11:30:18 +00001779** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001780** of the following:
1781**
1782** (1) SHARED_LOCK
1783** (2) RESERVED_LOCK
1784** (3) PENDING_LOCK
1785** (4) EXCLUSIVE_LOCK
1786**
1787** Sometimes when requesting one lock state, additional lock states
1788** are inserted in between. The locking might fail on one of the later
1789** transitions leaving the lock state different from what it started but
1790** still short of its goal. The following chart shows the allowed
1791** transitions and the inserted intermediate states:
1792**
1793** UNLOCKED -> SHARED
1794** SHARED -> RESERVED
1795** SHARED -> (PENDING) -> EXCLUSIVE
1796** RESERVED -> (PENDING) -> EXCLUSIVE
1797** PENDING -> EXCLUSIVE
1798**
1799** flock() only really support EXCLUSIVE locks. We track intermediate
1800** lock states in the sqlite3_file structure, but all locks SHARED or
1801** above are really EXCLUSIVE locks and exclude all other processes from
1802** access the file.
1803**
1804** This routine will only increase a lock. Use the sqlite3OsUnlock()
1805** routine to lower a locking level.
1806*/
drh308c2a52010-05-14 11:30:18 +00001807static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001808 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001809 unixFile *pFile = (unixFile*)id;
1810
1811 assert( pFile );
1812
1813 /* if we already have a lock, it is exclusive.
1814 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001815 if (pFile->eFileLock > NO_LOCK) {
1816 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001817 return SQLITE_OK;
1818 }
1819
1820 /* grab an exclusive lock */
1821
1822 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1823 int tErrno = errno;
1824 /* didn't get, must be busy */
1825 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1826 if( IS_LOCK_ERROR(rc) ){
1827 pFile->lastErrno = tErrno;
1828 }
1829 } else {
1830 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001831 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001832 }
drh308c2a52010-05-14 11:30:18 +00001833 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1834 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001835#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1836 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1837 rc = SQLITE_BUSY;
1838 }
1839#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1840 return rc;
1841}
1842
drh6b9d6dd2008-12-03 19:34:47 +00001843
1844/*
drh308c2a52010-05-14 11:30:18 +00001845** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001846** must be either NO_LOCK or SHARED_LOCK.
1847**
1848** If the locking level of the file descriptor is already at or below
1849** the requested locking level, this routine is a no-op.
1850*/
drh308c2a52010-05-14 11:30:18 +00001851static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001852 unixFile *pFile = (unixFile*)id;
1853
1854 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001855 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1856 pFile->eFileLock, getpid()));
1857 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001858
1859 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001860 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001861 return SQLITE_OK;
1862 }
1863
1864 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001865 if (eFileLock==SHARED_LOCK) {
1866 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001867 return SQLITE_OK;
1868 }
1869
1870 /* no, really, unlock. */
1871 int rc = flock(pFile->h, LOCK_UN);
1872 if (rc) {
1873 int r, tErrno = errno;
1874 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1875 if( IS_LOCK_ERROR(r) ){
1876 pFile->lastErrno = tErrno;
1877 }
1878#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1879 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1880 r = SQLITE_BUSY;
1881 }
1882#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1883
1884 return r;
1885 } else {
drh308c2a52010-05-14 11:30:18 +00001886 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001887 return SQLITE_OK;
1888 }
1889}
1890
1891/*
1892** Close a file.
1893*/
1894static int flockClose(sqlite3_file *id) {
1895 if( id ){
1896 flockUnlock(id, NO_LOCK);
1897 }
1898 return closeUnixFile(id);
1899}
1900
1901#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1902
1903/******************* End of the flock lock implementation *********************
1904******************************************************************************/
1905
1906/******************************************************************************
1907************************ Begin Named Semaphore Locking ************************
1908**
1909** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00001910**
1911** Semaphore locking is like dot-lock and flock in that it really only
1912** supports EXCLUSIVE locking. Only a single process can read or write
1913** the database file at a time. This reduces potential concurrency, but
1914** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00001915*/
1916#if OS_VXWORKS
1917
drh6b9d6dd2008-12-03 19:34:47 +00001918/*
1919** This routine checks if there is a RESERVED lock held on the specified
1920** file by this or any other process. If such a lock is held, set *pResOut
1921** to a non-zero value otherwise *pResOut is set to zero. The return value
1922** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1923*/
drh734c9862008-11-28 15:37:20 +00001924static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1925 int rc = SQLITE_OK;
1926 int reserved = 0;
1927 unixFile *pFile = (unixFile*)id;
1928
1929 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1930
1931 assert( pFile );
1932
1933 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001934 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001935 reserved = 1;
1936 }
1937
1938 /* Otherwise see if some other process holds it. */
1939 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00001940 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001941 struct stat statBuf;
1942
1943 if( sem_trywait(pSem)==-1 ){
1944 int tErrno = errno;
1945 if( EAGAIN != tErrno ){
1946 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1947 pFile->lastErrno = tErrno;
1948 } else {
1949 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00001950 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00001951 }
1952 }else{
1953 /* we could have it if we want it */
1954 sem_post(pSem);
1955 }
1956 }
drh308c2a52010-05-14 11:30:18 +00001957 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001958
1959 *pResOut = reserved;
1960 return rc;
1961}
1962
drh6b9d6dd2008-12-03 19:34:47 +00001963/*
drh308c2a52010-05-14 11:30:18 +00001964** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001965** of the following:
1966**
1967** (1) SHARED_LOCK
1968** (2) RESERVED_LOCK
1969** (3) PENDING_LOCK
1970** (4) EXCLUSIVE_LOCK
1971**
1972** Sometimes when requesting one lock state, additional lock states
1973** are inserted in between. The locking might fail on one of the later
1974** transitions leaving the lock state different from what it started but
1975** still short of its goal. The following chart shows the allowed
1976** transitions and the inserted intermediate states:
1977**
1978** UNLOCKED -> SHARED
1979** SHARED -> RESERVED
1980** SHARED -> (PENDING) -> EXCLUSIVE
1981** RESERVED -> (PENDING) -> EXCLUSIVE
1982** PENDING -> EXCLUSIVE
1983**
1984** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
1985** lock states in the sqlite3_file structure, but all locks SHARED or
1986** above are really EXCLUSIVE locks and exclude all other processes from
1987** access the file.
1988**
1989** This routine will only increase a lock. Use the sqlite3OsUnlock()
1990** routine to lower a locking level.
1991*/
drh308c2a52010-05-14 11:30:18 +00001992static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001993 unixFile *pFile = (unixFile*)id;
1994 int fd;
drh8af6c222010-05-14 12:43:01 +00001995 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001996 int rc = SQLITE_OK;
1997
1998 /* if we already have a lock, it is exclusive.
1999 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002000 if (pFile->eFileLock > NO_LOCK) {
2001 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002002 rc = SQLITE_OK;
2003 goto sem_end_lock;
2004 }
2005
2006 /* lock semaphore now but bail out when already locked. */
2007 if( sem_trywait(pSem)==-1 ){
2008 rc = SQLITE_BUSY;
2009 goto sem_end_lock;
2010 }
2011
2012 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002013 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002014
2015 sem_end_lock:
2016 return rc;
2017}
2018
drh6b9d6dd2008-12-03 19:34:47 +00002019/*
drh308c2a52010-05-14 11:30:18 +00002020** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002021** must be either NO_LOCK or SHARED_LOCK.
2022**
2023** If the locking level of the file descriptor is already at or below
2024** the requested locking level, this routine is a no-op.
2025*/
drh308c2a52010-05-14 11:30:18 +00002026static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002027 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002028 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002029
2030 assert( pFile );
2031 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002032 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2033 pFile->eFileLock, getpid()));
2034 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002035
2036 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002037 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002038 return SQLITE_OK;
2039 }
2040
2041 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002042 if (eFileLock==SHARED_LOCK) {
2043 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002044 return SQLITE_OK;
2045 }
2046
2047 /* no, really unlock. */
2048 if ( sem_post(pSem)==-1 ) {
2049 int rc, tErrno = errno;
2050 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2051 if( IS_LOCK_ERROR(rc) ){
2052 pFile->lastErrno = tErrno;
2053 }
2054 return rc;
2055 }
drh308c2a52010-05-14 11:30:18 +00002056 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002057 return SQLITE_OK;
2058}
2059
2060/*
2061 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002062 */
drh734c9862008-11-28 15:37:20 +00002063static int semClose(sqlite3_file *id) {
2064 if( id ){
2065 unixFile *pFile = (unixFile*)id;
2066 semUnlock(id, NO_LOCK);
2067 assert( pFile );
2068 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002069 releaseLockInfo(pFile->pInode);
drh734c9862008-11-28 15:37:20 +00002070 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002071 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002072 }
2073 return SQLITE_OK;
2074}
2075
2076#endif /* OS_VXWORKS */
2077/*
2078** Named semaphore locking is only available on VxWorks.
2079**
2080*************** End of the named semaphore lock implementation ****************
2081******************************************************************************/
2082
2083
2084/******************************************************************************
2085*************************** Begin AFP Locking *********************************
2086**
2087** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2088** on Apple Macintosh computers - both OS9 and OSX.
2089**
2090** Third-party implementations of AFP are available. But this code here
2091** only works on OSX.
2092*/
2093
drhd2cb50b2009-01-09 21:41:17 +00002094#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002095/*
2096** The afpLockingContext structure contains all afp lock specific state
2097*/
drhbfe66312006-10-03 17:40:40 +00002098typedef struct afpLockingContext afpLockingContext;
2099struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002100 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002101 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002102};
2103
2104struct ByteRangeLockPB2
2105{
2106 unsigned long long offset; /* offset to first byte to lock */
2107 unsigned long long length; /* nbr of bytes to lock */
2108 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2109 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2110 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2111 int fd; /* file desc to assoc this lock with */
2112};
2113
drhfd131da2007-08-07 17:13:03 +00002114#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002115
drh6b9d6dd2008-12-03 19:34:47 +00002116/*
2117** This is a utility for setting or clearing a bit-range lock on an
2118** AFP filesystem.
2119**
2120** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2121*/
2122static int afpSetLock(
2123 const char *path, /* Name of the file to be locked or unlocked */
2124 unixFile *pFile, /* Open file descriptor on path */
2125 unsigned long long offset, /* First byte to be locked */
2126 unsigned long long length, /* Number of bytes to lock */
2127 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002128){
drh6b9d6dd2008-12-03 19:34:47 +00002129 struct ByteRangeLockPB2 pb;
2130 int err;
drhbfe66312006-10-03 17:40:40 +00002131
2132 pb.unLockFlag = setLockFlag ? 0 : 1;
2133 pb.startEndFlag = 0;
2134 pb.offset = offset;
2135 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002136 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002137
drh308c2a52010-05-14 11:30:18 +00002138 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002139 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002140 offset, length));
drhbfe66312006-10-03 17:40:40 +00002141 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2142 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002143 int rc;
2144 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002145 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2146 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002147#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2148 rc = SQLITE_BUSY;
2149#else
drh734c9862008-11-28 15:37:20 +00002150 rc = sqliteErrorFromPosixError(tErrno,
2151 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002152#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002153 if( IS_LOCK_ERROR(rc) ){
2154 pFile->lastErrno = tErrno;
2155 }
2156 return rc;
drhbfe66312006-10-03 17:40:40 +00002157 } else {
aswift5b1a2562008-08-22 00:22:35 +00002158 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002159 }
2160}
2161
drh6b9d6dd2008-12-03 19:34:47 +00002162/*
2163** This routine checks if there is a RESERVED lock held on the specified
2164** file by this or any other process. If such a lock is held, set *pResOut
2165** to a non-zero value otherwise *pResOut is set to zero. The return value
2166** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2167*/
danielk1977e339d652008-06-28 11:23:00 +00002168static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002169 int rc = SQLITE_OK;
2170 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002171 unixFile *pFile = (unixFile*)id;
2172
aswift5b1a2562008-08-22 00:22:35 +00002173 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2174
2175 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002176 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002177 if( context->reserved ){
2178 *pResOut = 1;
2179 return SQLITE_OK;
2180 }
drh8af6c222010-05-14 12:43:01 +00002181 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002182
2183 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002184 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002185 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002186 }
2187
2188 /* Otherwise see if some other process holds it.
2189 */
aswift5b1a2562008-08-22 00:22:35 +00002190 if( !reserved ){
2191 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002192 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002193 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002194 /* if we succeeded in taking the reserved lock, unlock it to restore
2195 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002196 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002197 } else {
2198 /* if we failed to get the lock then someone else must have it */
2199 reserved = 1;
2200 }
2201 if( IS_LOCK_ERROR(lrc) ){
2202 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002203 }
2204 }
drhbfe66312006-10-03 17:40:40 +00002205
drh7ed97b92010-01-20 13:07:21 +00002206 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002207 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002208
2209 *pResOut = reserved;
2210 return rc;
drhbfe66312006-10-03 17:40:40 +00002211}
2212
drh6b9d6dd2008-12-03 19:34:47 +00002213/*
drh308c2a52010-05-14 11:30:18 +00002214** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002215** of the following:
2216**
2217** (1) SHARED_LOCK
2218** (2) RESERVED_LOCK
2219** (3) PENDING_LOCK
2220** (4) EXCLUSIVE_LOCK
2221**
2222** Sometimes when requesting one lock state, additional lock states
2223** are inserted in between. The locking might fail on one of the later
2224** transitions leaving the lock state different from what it started but
2225** still short of its goal. The following chart shows the allowed
2226** transitions and the inserted intermediate states:
2227**
2228** UNLOCKED -> SHARED
2229** SHARED -> RESERVED
2230** SHARED -> (PENDING) -> EXCLUSIVE
2231** RESERVED -> (PENDING) -> EXCLUSIVE
2232** PENDING -> EXCLUSIVE
2233**
2234** This routine will only increase a lock. Use the sqlite3OsUnlock()
2235** routine to lower a locking level.
2236*/
drh308c2a52010-05-14 11:30:18 +00002237static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002238 int rc = SQLITE_OK;
2239 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002240 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002241 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002242
2243 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002244 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2245 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002246 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002247
drhbfe66312006-10-03 17:40:40 +00002248 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002249 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002250 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002251 */
drh308c2a52010-05-14 11:30:18 +00002252 if( pFile->eFileLock>=eFileLock ){
2253 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2254 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002255 return SQLITE_OK;
2256 }
2257
2258 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002259 ** (1) We never move from unlocked to anything higher than shared lock.
2260 ** (2) SQLite never explicitly requests a pendig lock.
2261 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002262 */
drh308c2a52010-05-14 11:30:18 +00002263 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2264 assert( eFileLock!=PENDING_LOCK );
2265 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002266
drh8af6c222010-05-14 12:43:01 +00002267 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002268 */
drh6c7d5c52008-11-21 20:32:33 +00002269 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002270 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002271
2272 /* If some thread using this PID has a lock via a different unixFile*
2273 ** handle that precludes the requested lock, return BUSY.
2274 */
drh8af6c222010-05-14 12:43:01 +00002275 if( (pFile->eFileLock!=pInode->eFileLock &&
2276 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002277 ){
2278 rc = SQLITE_BUSY;
2279 goto afp_end_lock;
2280 }
2281
2282 /* If a SHARED lock is requested, and some thread using this PID already
2283 ** has a SHARED or RESERVED lock, then increment reference counts and
2284 ** return SQLITE_OK.
2285 */
drh308c2a52010-05-14 11:30:18 +00002286 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002287 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002288 assert( eFileLock==SHARED_LOCK );
2289 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002290 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002291 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002292 pInode->nShared++;
2293 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002294 goto afp_end_lock;
2295 }
drhbfe66312006-10-03 17:40:40 +00002296
2297 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002298 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2299 ** be released.
2300 */
drh308c2a52010-05-14 11:30:18 +00002301 if( eFileLock==SHARED_LOCK
2302 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002303 ){
2304 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002305 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002306 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002307 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002308 goto afp_end_lock;
2309 }
2310 }
2311
2312 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002313 ** operating system calls for the specified lock.
2314 */
drh308c2a52010-05-14 11:30:18 +00002315 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002316 int lrc1, lrc2, lrc1Errno;
2317 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002318
drh8af6c222010-05-14 12:43:01 +00002319 assert( pInode->nShared==0 );
2320 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002321
2322 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002323 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002324 /* note that the quality of the randomness doesn't matter that much */
2325 lk = random();
drh8af6c222010-05-14 12:43:01 +00002326 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002327 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002328 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002329 if( IS_LOCK_ERROR(lrc1) ){
2330 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002331 }
aswift5b1a2562008-08-22 00:22:35 +00002332 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002333 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002334
aswift5b1a2562008-08-22 00:22:35 +00002335 if( IS_LOCK_ERROR(lrc1) ) {
2336 pFile->lastErrno = lrc1Errno;
2337 rc = lrc1;
2338 goto afp_end_lock;
2339 } else if( IS_LOCK_ERROR(lrc2) ){
2340 rc = lrc2;
2341 goto afp_end_lock;
2342 } else if( lrc1 != SQLITE_OK ) {
2343 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002344 } else {
drh308c2a52010-05-14 11:30:18 +00002345 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002346 pInode->nLock++;
2347 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002348 }
drh8af6c222010-05-14 12:43:01 +00002349 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002350 /* We are trying for an exclusive lock but another thread in this
2351 ** same process is still holding a shared lock. */
2352 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002353 }else{
2354 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2355 ** assumed that there is a SHARED or greater lock on the file
2356 ** already.
2357 */
2358 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002359 assert( 0!=pFile->eFileLock );
2360 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002361 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002362 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002363 if( !failed ){
2364 context->reserved = 1;
2365 }
drhbfe66312006-10-03 17:40:40 +00002366 }
drh308c2a52010-05-14 11:30:18 +00002367 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002368 /* Acquire an EXCLUSIVE lock */
2369
2370 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002371 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002372 */
drh6b9d6dd2008-12-03 19:34:47 +00002373 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002374 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002375 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002376 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002377 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002378 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002379 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002380 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002381 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2382 ** a critical I/O error
2383 */
2384 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2385 SQLITE_IOERR_LOCK;
2386 goto afp_end_lock;
2387 }
2388 }else{
aswift5b1a2562008-08-22 00:22:35 +00002389 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002390 }
2391 }
aswift5b1a2562008-08-22 00:22:35 +00002392 if( failed ){
2393 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002394 }
2395 }
2396
2397 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002398 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002399 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002400 }else if( eFileLock==EXCLUSIVE_LOCK ){
2401 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002402 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002403 }
2404
2405afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002406 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002407 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2408 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002409 return rc;
2410}
2411
2412/*
drh308c2a52010-05-14 11:30:18 +00002413** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002414** must be either NO_LOCK or SHARED_LOCK.
2415**
2416** If the locking level of the file descriptor is already at or below
2417** the requested locking level, this routine is a no-op.
2418*/
drh308c2a52010-05-14 11:30:18 +00002419static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002420 int rc = SQLITE_OK;
2421 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002422 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002423 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2424 int skipShared = 0;
2425#ifdef SQLITE_TEST
2426 int h = pFile->h;
2427#endif
drhbfe66312006-10-03 17:40:40 +00002428
2429 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002430 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002431 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002432 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002433
drh308c2a52010-05-14 11:30:18 +00002434 assert( eFileLock<=SHARED_LOCK );
2435 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002436 return SQLITE_OK;
2437 }
drh6c7d5c52008-11-21 20:32:33 +00002438 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002439 pInode = pFile->pInode;
2440 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002441 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002442 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002443 SimulateIOErrorBenign(1);
2444 SimulateIOError( h=(-1) )
2445 SimulateIOErrorBenign(0);
2446
2447#ifndef NDEBUG
2448 /* When reducing a lock such that other processes can start
2449 ** reading the database file again, make sure that the
2450 ** transaction counter was updated if any part of the database
2451 ** file changed. If the transaction counter is not updated,
2452 ** other connections to the same file might not realize that
2453 ** the file has changed and hence might not know to flush their
2454 ** cache. The use of a stale cache can lead to database corruption.
2455 */
2456 assert( pFile->inNormalWrite==0
2457 || pFile->dbUpdate==0
2458 || pFile->transCntrChng==1 );
2459 pFile->inNormalWrite = 0;
2460#endif
aswiftaebf4132008-11-21 00:10:35 +00002461
drh308c2a52010-05-14 11:30:18 +00002462 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002463 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002464 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002465 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002466 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002467 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2468 } else {
2469 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002470 }
2471 }
drh308c2a52010-05-14 11:30:18 +00002472 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002473 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002474 }
drh308c2a52010-05-14 11:30:18 +00002475 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002476 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2477 if( !rc ){
2478 context->reserved = 0;
2479 }
aswiftaebf4132008-11-21 00:10:35 +00002480 }
drh8af6c222010-05-14 12:43:01 +00002481 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2482 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002483 }
aswiftaebf4132008-11-21 00:10:35 +00002484 }
drh308c2a52010-05-14 11:30:18 +00002485 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002486
drh7ed97b92010-01-20 13:07:21 +00002487 /* Decrement the shared lock counter. Release the lock using an
2488 ** OS call only when all threads in this same process have released
2489 ** the lock.
2490 */
drh8af6c222010-05-14 12:43:01 +00002491 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2492 pInode->nShared--;
2493 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002494 SimulateIOErrorBenign(1);
2495 SimulateIOError( h=(-1) )
2496 SimulateIOErrorBenign(0);
2497 if( !skipShared ){
2498 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2499 }
2500 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002501 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002502 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002503 }
2504 }
2505 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002506 pInode->nLock--;
2507 assert( pInode->nLock>=0 );
2508 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002509 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002510 }
2511 }
drhbfe66312006-10-03 17:40:40 +00002512 }
drh7ed97b92010-01-20 13:07:21 +00002513
drh6c7d5c52008-11-21 20:32:33 +00002514 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002515 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002516 return rc;
2517}
2518
2519/*
drh339eb0b2008-03-07 15:34:11 +00002520** Close a file & cleanup AFP specific locking context
2521*/
danielk1977e339d652008-06-28 11:23:00 +00002522static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002523 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002524 if( id ){
2525 unixFile *pFile = (unixFile*)id;
2526 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002527 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002528 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002529 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002530 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002531 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002532 ** the last lock is cleared.
2533 */
dan08da86a2009-08-21 17:18:03 +00002534 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002535 }
drh8af6c222010-05-14 12:43:01 +00002536 releaseLockInfo(pFile->pInode);
danielk1977e339d652008-06-28 11:23:00 +00002537 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002538 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002539 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002540 }
drh7ed97b92010-01-20 13:07:21 +00002541 return rc;
drhbfe66312006-10-03 17:40:40 +00002542}
2543
drhd2cb50b2009-01-09 21:41:17 +00002544#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002545/*
2546** The code above is the AFP lock implementation. The code is specific
2547** to MacOSX and does not work on other unix platforms. No alternative
2548** is available. If you don't compile for a mac, then the "unix-afp"
2549** VFS is not available.
2550**
2551********************* End of the AFP lock implementation **********************
2552******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002553
drh7ed97b92010-01-20 13:07:21 +00002554/******************************************************************************
2555*************************** Begin NFS Locking ********************************/
2556
2557#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2558/*
drh308c2a52010-05-14 11:30:18 +00002559 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002560 ** must be either NO_LOCK or SHARED_LOCK.
2561 **
2562 ** If the locking level of the file descriptor is already at or below
2563 ** the requested locking level, this routine is a no-op.
2564 */
drh308c2a52010-05-14 11:30:18 +00002565static int nfsUnlock(sqlite3_file *id, int eFileLock){
2566 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002567}
2568
2569#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2570/*
2571** The code above is the NFS lock implementation. The code is specific
2572** to MacOSX and does not work on other unix platforms. No alternative
2573** is available.
2574**
2575********************* End of the NFS lock implementation **********************
2576******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002577
2578/******************************************************************************
2579**************** Non-locking sqlite3_file methods *****************************
2580**
2581** The next division contains implementations for all methods of the
2582** sqlite3_file object other than the locking methods. The locking
2583** methods were defined in divisions above (one locking method per
2584** division). Those methods that are common to all locking modes
2585** are gather together into this division.
2586*/
drhbfe66312006-10-03 17:40:40 +00002587
2588/*
drh734c9862008-11-28 15:37:20 +00002589** Seek to the offset passed as the second argument, then read cnt
2590** bytes into pBuf. Return the number of bytes actually read.
2591**
2592** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2593** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2594** one system to another. Since SQLite does not define USE_PREAD
2595** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2596** See tickets #2741 and #2681.
2597**
2598** To avoid stomping the errno value on a failed read the lastErrno value
2599** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002600*/
drh734c9862008-11-28 15:37:20 +00002601static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2602 int got;
drh7ed97b92010-01-20 13:07:21 +00002603#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002604 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002605#endif
drh734c9862008-11-28 15:37:20 +00002606 TIMER_START;
2607#if defined(USE_PREAD)
2608 got = pread(id->h, pBuf, cnt, offset);
2609 SimulateIOError( got = -1 );
2610#elif defined(USE_PREAD64)
2611 got = pread64(id->h, pBuf, cnt, offset);
2612 SimulateIOError( got = -1 );
2613#else
2614 newOffset = lseek(id->h, offset, SEEK_SET);
2615 SimulateIOError( newOffset-- );
2616 if( newOffset!=offset ){
2617 if( newOffset == -1 ){
2618 ((unixFile*)id)->lastErrno = errno;
2619 }else{
2620 ((unixFile*)id)->lastErrno = 0;
2621 }
2622 return -1;
2623 }
2624 got = read(id->h, pBuf, cnt);
2625#endif
2626 TIMER_END;
2627 if( got<0 ){
2628 ((unixFile*)id)->lastErrno = errno;
2629 }
drh308c2a52010-05-14 11:30:18 +00002630 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002631 return got;
drhbfe66312006-10-03 17:40:40 +00002632}
2633
2634/*
drh734c9862008-11-28 15:37:20 +00002635** Read data from a file into a buffer. Return SQLITE_OK if all
2636** bytes were read successfully and SQLITE_IOERR if anything goes
2637** wrong.
drh339eb0b2008-03-07 15:34:11 +00002638*/
drh734c9862008-11-28 15:37:20 +00002639static int unixRead(
2640 sqlite3_file *id,
2641 void *pBuf,
2642 int amt,
2643 sqlite3_int64 offset
2644){
dan08da86a2009-08-21 17:18:03 +00002645 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002646 int got;
2647 assert( id );
drh08c6d442009-02-09 17:34:07 +00002648
dan08da86a2009-08-21 17:18:03 +00002649 /* If this is a database file (not a journal, master-journal or temp
2650 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002651#if 0
dane946c392009-08-22 11:39:46 +00002652 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002653 || offset>=PENDING_BYTE+512
2654 || offset+amt<=PENDING_BYTE
2655 );
dan7c246102010-04-12 19:00:29 +00002656#endif
drh08c6d442009-02-09 17:34:07 +00002657
dan08da86a2009-08-21 17:18:03 +00002658 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002659 if( got==amt ){
2660 return SQLITE_OK;
2661 }else if( got<0 ){
2662 /* lastErrno set by seekAndRead */
2663 return SQLITE_IOERR_READ;
2664 }else{
dan08da86a2009-08-21 17:18:03 +00002665 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002666 /* Unread parts of the buffer must be zero-filled */
2667 memset(&((char*)pBuf)[got], 0, amt-got);
2668 return SQLITE_IOERR_SHORT_READ;
2669 }
2670}
2671
2672/*
2673** Seek to the offset in id->offset then read cnt bytes into pBuf.
2674** Return the number of bytes actually read. Update the offset.
2675**
2676** To avoid stomping the errno value on a failed write the lastErrno value
2677** is set before returning.
2678*/
2679static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2680 int got;
drh7ed97b92010-01-20 13:07:21 +00002681#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002682 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002683#endif
drh734c9862008-11-28 15:37:20 +00002684 TIMER_START;
2685#if defined(USE_PREAD)
2686 got = pwrite(id->h, pBuf, cnt, offset);
2687#elif defined(USE_PREAD64)
2688 got = pwrite64(id->h, pBuf, cnt, offset);
2689#else
2690 newOffset = lseek(id->h, offset, SEEK_SET);
2691 if( newOffset!=offset ){
2692 if( newOffset == -1 ){
2693 ((unixFile*)id)->lastErrno = errno;
2694 }else{
2695 ((unixFile*)id)->lastErrno = 0;
2696 }
2697 return -1;
2698 }
2699 got = write(id->h, pBuf, cnt);
2700#endif
2701 TIMER_END;
2702 if( got<0 ){
2703 ((unixFile*)id)->lastErrno = errno;
2704 }
2705
drh308c2a52010-05-14 11:30:18 +00002706 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002707 return got;
2708}
2709
2710
2711/*
2712** Write data from a buffer into a file. Return SQLITE_OK on success
2713** or some other error code on failure.
2714*/
2715static int unixWrite(
2716 sqlite3_file *id,
2717 const void *pBuf,
2718 int amt,
2719 sqlite3_int64 offset
2720){
dan08da86a2009-08-21 17:18:03 +00002721 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002722 int wrote = 0;
2723 assert( id );
2724 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002725
dan08da86a2009-08-21 17:18:03 +00002726 /* If this is a database file (not a journal, master-journal or temp
2727 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002728#if 0
dane946c392009-08-22 11:39:46 +00002729 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002730 || offset>=PENDING_BYTE+512
2731 || offset+amt<=PENDING_BYTE
2732 );
dan7c246102010-04-12 19:00:29 +00002733#endif
drh08c6d442009-02-09 17:34:07 +00002734
drh8f941bc2009-01-14 23:03:40 +00002735#ifndef NDEBUG
2736 /* If we are doing a normal write to a database file (as opposed to
2737 ** doing a hot-journal rollback or a write to some file other than a
2738 ** normal database file) then record the fact that the database
2739 ** has changed. If the transaction counter is modified, record that
2740 ** fact too.
2741 */
dan08da86a2009-08-21 17:18:03 +00002742 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002743 pFile->dbUpdate = 1; /* The database has been modified */
2744 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002745 int rc;
drh8f941bc2009-01-14 23:03:40 +00002746 char oldCntr[4];
2747 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002748 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002749 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002750 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002751 pFile->transCntrChng = 1; /* The transaction counter has changed */
2752 }
2753 }
2754 }
2755#endif
2756
dan08da86a2009-08-21 17:18:03 +00002757 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002758 amt -= wrote;
2759 offset += wrote;
2760 pBuf = &((char*)pBuf)[wrote];
2761 }
2762 SimulateIOError(( wrote=(-1), amt=1 ));
2763 SimulateDiskfullError(( wrote=0, amt=1 ));
2764 if( amt>0 ){
2765 if( wrote<0 ){
2766 /* lastErrno set by seekAndWrite */
2767 return SQLITE_IOERR_WRITE;
2768 }else{
dan08da86a2009-08-21 17:18:03 +00002769 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002770 return SQLITE_FULL;
2771 }
2772 }
2773 return SQLITE_OK;
2774}
2775
2776#ifdef SQLITE_TEST
2777/*
2778** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002779** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002780*/
2781int sqlite3_sync_count = 0;
2782int sqlite3_fullsync_count = 0;
2783#endif
2784
2785/*
drh89240432009-03-25 01:06:01 +00002786** We do not trust systems to provide a working fdatasync(). Some do.
2787** Others do no. To be safe, we will stick with the (slower) fsync().
2788** If you know that your system does support fdatasync() correctly,
2789** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002790*/
drh89240432009-03-25 01:06:01 +00002791#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002792# define fdatasync fsync
2793#endif
2794
2795/*
2796** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2797** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2798** only available on Mac OS X. But that could change.
2799*/
2800#ifdef F_FULLFSYNC
2801# define HAVE_FULLFSYNC 1
2802#else
2803# define HAVE_FULLFSYNC 0
2804#endif
2805
2806
2807/*
2808** The fsync() system call does not work as advertised on many
2809** unix systems. The following procedure is an attempt to make
2810** it work better.
2811**
2812** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2813** for testing when we want to run through the test suite quickly.
2814** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2815** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2816** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002817**
2818** SQLite sets the dataOnly flag if the size of the file is unchanged.
2819** The idea behind dataOnly is that it should only write the file content
2820** to disk, not the inode. We only set dataOnly if the file size is
2821** unchanged since the file size is part of the inode. However,
2822** Ted Ts'o tells us that fdatasync() will also write the inode if the
2823** file size has changed. The only real difference between fdatasync()
2824** and fsync(), Ted tells us, is that fdatasync() will not flush the
2825** inode if the mtime or owner or other inode attributes have changed.
2826** We only care about the file size, not the other file attributes, so
2827** as far as SQLite is concerned, an fdatasync() is always adequate.
2828** So, we always use fdatasync() if it is available, regardless of
2829** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002830*/
2831static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002832 int rc;
drh734c9862008-11-28 15:37:20 +00002833
2834 /* The following "ifdef/elif/else/" block has the same structure as
2835 ** the one below. It is replicated here solely to avoid cluttering
2836 ** up the real code with the UNUSED_PARAMETER() macros.
2837 */
2838#ifdef SQLITE_NO_SYNC
2839 UNUSED_PARAMETER(fd);
2840 UNUSED_PARAMETER(fullSync);
2841 UNUSED_PARAMETER(dataOnly);
2842#elif HAVE_FULLFSYNC
2843 UNUSED_PARAMETER(dataOnly);
2844#else
2845 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002846 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002847#endif
2848
2849 /* Record the number of times that we do a normal fsync() and
2850 ** FULLSYNC. This is used during testing to verify that this procedure
2851 ** gets called with the correct arguments.
2852 */
2853#ifdef SQLITE_TEST
2854 if( fullSync ) sqlite3_fullsync_count++;
2855 sqlite3_sync_count++;
2856#endif
2857
2858 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2859 ** no-op
2860 */
2861#ifdef SQLITE_NO_SYNC
2862 rc = SQLITE_OK;
2863#elif HAVE_FULLFSYNC
2864 if( fullSync ){
2865 rc = fcntl(fd, F_FULLFSYNC, 0);
2866 }else{
2867 rc = 1;
2868 }
2869 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002870 ** It shouldn't be possible for fullfsync to fail on the local
2871 ** file system (on OSX), so failure indicates that FULLFSYNC
2872 ** isn't supported for this file system. So, attempt an fsync
2873 ** and (for now) ignore the overhead of a superfluous fcntl call.
2874 ** It'd be better to detect fullfsync support once and avoid
2875 ** the fcntl call every time sync is called.
2876 */
drh734c9862008-11-28 15:37:20 +00002877 if( rc ) rc = fsync(fd);
2878
drh7ed97b92010-01-20 13:07:21 +00002879#elif defined(__APPLE__)
2880 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2881 ** so currently we default to the macro that redefines fdatasync to fsync
2882 */
2883 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002884#else
drh0b647ff2009-03-21 14:41:04 +00002885 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002886#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002887 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002888 rc = fsync(fd);
2889 }
drh0b647ff2009-03-21 14:41:04 +00002890#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002891#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2892
2893 if( OS_VXWORKS && rc!= -1 ){
2894 rc = 0;
2895 }
chw97185482008-11-17 08:05:31 +00002896 return rc;
drhbfe66312006-10-03 17:40:40 +00002897}
2898
drh734c9862008-11-28 15:37:20 +00002899/*
2900** Make sure all writes to a particular file are committed to disk.
2901**
2902** If dataOnly==0 then both the file itself and its metadata (file
2903** size, access time, etc) are synced. If dataOnly!=0 then only the
2904** file data is synced.
2905**
2906** Under Unix, also make sure that the directory entry for the file
2907** has been created by fsync-ing the directory that contains the file.
2908** If we do not do this and we encounter a power failure, the directory
2909** entry for the journal might not exist after we reboot. The next
2910** SQLite to access the file will not know that the journal exists (because
2911** the directory entry for the journal was never created) and the transaction
2912** will not roll back - possibly leading to database corruption.
2913*/
2914static int unixSync(sqlite3_file *id, int flags){
2915 int rc;
2916 unixFile *pFile = (unixFile*)id;
2917
2918 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2919 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2920
2921 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2922 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2923 || (flags&0x0F)==SQLITE_SYNC_FULL
2924 );
2925
2926 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2927 ** line is to test that doing so does not cause any problems.
2928 */
2929 SimulateDiskfullError( return SQLITE_FULL );
2930
2931 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002932 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00002933 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2934 SimulateIOError( rc=1 );
2935 if( rc ){
2936 pFile->lastErrno = errno;
2937 return SQLITE_IOERR_FSYNC;
2938 }
2939 if( pFile->dirfd>=0 ){
2940 int err;
drh308c2a52010-05-14 11:30:18 +00002941 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2942 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00002943#ifndef SQLITE_DISABLE_DIRSYNC
2944 /* The directory sync is only attempted if full_fsync is
2945 ** turned off or unavailable. If a full_fsync occurred above,
2946 ** then the directory sync is superfluous.
2947 */
2948 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2949 /*
2950 ** We have received multiple reports of fsync() returning
2951 ** errors when applied to directories on certain file systems.
2952 ** A failed directory sync is not a big deal. So it seems
2953 ** better to ignore the error. Ticket #1657
2954 */
2955 /* pFile->lastErrno = errno; */
2956 /* return SQLITE_IOERR; */
2957 }
2958#endif
2959 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2960 if( err==0 ){ /* directory when we are done */
2961 pFile->dirfd = -1;
2962 }else{
2963 pFile->lastErrno = errno;
2964 rc = SQLITE_IOERR_DIR_CLOSE;
2965 }
2966 }
2967 return rc;
2968}
2969
2970/*
2971** Truncate an open file to a specified size
2972*/
2973static int unixTruncate(sqlite3_file *id, i64 nByte){
2974 int rc;
2975 assert( id );
2976 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2977 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2978 if( rc ){
2979 ((unixFile*)id)->lastErrno = errno;
2980 return SQLITE_IOERR_TRUNCATE;
2981 }else{
drh3313b142009-11-06 04:13:18 +00002982#ifndef NDEBUG
2983 /* If we are doing a normal write to a database file (as opposed to
2984 ** doing a hot-journal rollback or a write to some file other than a
2985 ** normal database file) and we truncate the file to zero length,
2986 ** that effectively updates the change counter. This might happen
2987 ** when restoring a database using the backup API from a zero-length
2988 ** source.
2989 */
2990 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
2991 ((unixFile*)id)->transCntrChng = 1;
2992 }
2993#endif
2994
drh734c9862008-11-28 15:37:20 +00002995 return SQLITE_OK;
2996 }
2997}
2998
2999/*
3000** Determine the current size of a file in bytes
3001*/
3002static int unixFileSize(sqlite3_file *id, i64 *pSize){
3003 int rc;
3004 struct stat buf;
3005 assert( id );
3006 rc = fstat(((unixFile*)id)->h, &buf);
3007 SimulateIOError( rc=1 );
3008 if( rc!=0 ){
3009 ((unixFile*)id)->lastErrno = errno;
3010 return SQLITE_IOERR_FSTAT;
3011 }
3012 *pSize = buf.st_size;
3013
drh8af6c222010-05-14 12:43:01 +00003014 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003015 ** writes a single byte into that file in order to work around a bug
3016 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3017 ** layers, we need to report this file size as zero even though it is
3018 ** really 1. Ticket #3260.
3019 */
3020 if( *pSize==1 ) *pSize = 0;
3021
3022
3023 return SQLITE_OK;
3024}
3025
drhd2cb50b2009-01-09 21:41:17 +00003026#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003027/*
3028** Handler for proxy-locking file-control verbs. Defined below in the
3029** proxying locking division.
3030*/
3031static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003032#endif
drh715ff302008-12-03 22:32:44 +00003033
danielk1977ad94b582007-08-20 06:44:22 +00003034
danielk1977e3026632004-06-22 11:29:02 +00003035/*
drh9e33c2c2007-08-31 18:34:59 +00003036** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003037*/
drhcc6bb3e2007-08-31 16:11:35 +00003038static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003039 switch( op ){
3040 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003041 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003042 return SQLITE_OK;
3043 }
drh7708e972008-11-29 00:56:52 +00003044 case SQLITE_LAST_ERRNO: {
3045 *(int*)pArg = ((unixFile*)id)->lastErrno;
3046 return SQLITE_OK;
3047 }
drh9ff27ec2010-05-19 19:26:05 +00003048 case SQLITE_FCNTL_SIZE_HINT: {
3049 sqlite3_int64 szFile = *(sqlite3_int64*)pArg;
3050 unixFile *pFile = (unixFile*)id;
3051 ftruncate(pFile->h, szFile);
3052 return SQLITE_OK;
3053 }
drh8f941bc2009-01-14 23:03:40 +00003054#ifndef NDEBUG
3055 /* The pager calls this method to signal that it has done
3056 ** a rollback and that the database is therefore unchanged and
3057 ** it hence it is OK for the transaction change counter to be
3058 ** unchanged.
3059 */
3060 case SQLITE_FCNTL_DB_UNCHANGED: {
3061 ((unixFile*)id)->dbUpdate = 0;
3062 return SQLITE_OK;
3063 }
3064#endif
drhd2cb50b2009-01-09 21:41:17 +00003065#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003066 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003067 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003068 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003069 }
drhd2cb50b2009-01-09 21:41:17 +00003070#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003071 }
drhcc6bb3e2007-08-31 16:11:35 +00003072 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003073}
3074
3075/*
danielk1977a3d4c882007-03-23 10:08:38 +00003076** Return the sector size in bytes of the underlying block device for
3077** the specified file. This is almost always 512 bytes, but may be
3078** larger for some devices.
3079**
3080** SQLite code assumes this function cannot fail. It also assumes that
3081** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003082** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003083** same for both.
3084*/
danielk1977397d65f2008-11-19 11:35:39 +00003085static int unixSectorSize(sqlite3_file *NotUsed){
3086 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003087 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003088}
3089
danielk197790949c22007-08-17 16:50:38 +00003090/*
danielk1977397d65f2008-11-19 11:35:39 +00003091** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003092*/
danielk1977397d65f2008-11-19 11:35:39 +00003093static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3094 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003095 return 0;
3096}
3097
drhd9e5c4f2010-05-12 18:01:39 +00003098#ifndef SQLITE_OMIT_WAL
3099
3100
3101/*
drhd91c68f2010-05-14 14:52:25 +00003102** Object used to represent an shared memory buffer.
3103**
3104** When multiple threads all reference the same wal-index, each thread
3105** has its own unixShm object, but they all point to a single instance
3106** of this unixShmNode object. In other words, each wal-index is opened
3107** only once per process.
3108**
3109** Each unixShmNode object is connected to a single unixInodeInfo object.
3110** We could coalesce this object into unixInodeInfo, but that would mean
3111** every open file that does not use shared memory (in other words, most
3112** open files) would have to carry around this extra information. So
3113** the unixInodeInfo object contains a pointer to this unixShmNode object
3114** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003115**
3116** unixMutexHeld() must be true when creating or destroying
3117** this object or while reading or writing the following fields:
3118**
3119** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003120**
3121** The following fields are read-only after the object is created:
3122**
3123** fid
3124** zFilename
3125**
drhd91c68f2010-05-14 14:52:25 +00003126** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003127** unixMutexHeld() is true when reading or writing any other field
3128** in this structure.
3129**
3130** To avoid deadlocks, mutex and mutexBuf are always released in the
3131** reverse order that they are acquired. mutexBuf is always acquired
3132** first and released last. This invariant is check by asserting
3133** sqlite3_mutex_notheld() on mutex whenever mutexBuf is acquired or
3134** released.
3135*/
drhd91c68f2010-05-14 14:52:25 +00003136struct unixShmNode {
3137 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003138 sqlite3_mutex *mutex; /* Mutex to access this object */
3139 sqlite3_mutex *mutexBuf; /* Mutex to access zBuf[] */
3140 char *zFilename; /* Name of the mmapped file */
3141 int h; /* Open file descriptor */
drhd91c68f2010-05-14 14:52:25 +00003142 int szMap; /* Size of the mapping into memory */
drhd9e5c4f2010-05-12 18:01:39 +00003143 char *pMMapBuf; /* Where currently mmapped(). NULL if unmapped */
3144 int nRef; /* Number of unixShm objects pointing to this */
3145 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003146#ifdef SQLITE_DEBUG
3147 u8 exclMask; /* Mask of exclusive locks held */
3148 u8 sharedMask; /* Mask of shared locks held */
3149 u8 nextShmId; /* Next available unixShm.id value */
3150#endif
3151};
3152
3153/*
drhd9e5c4f2010-05-12 18:01:39 +00003154** Structure used internally by this VFS to record the state of an
3155** open shared memory connection.
3156**
drhd91c68f2010-05-14 14:52:25 +00003157** The following fields are initialized when this object is created and
3158** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003159**
drhd91c68f2010-05-14 14:52:25 +00003160** unixShm.pFile
3161** unixShm.id
3162**
3163** All other fields are read/write. The unixShm.pFile->mutex must be held
3164** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003165*/
3166struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003167 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3168 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003169 u8 lockState; /* Current lock state */
drhd91c68f2010-05-14 14:52:25 +00003170 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhd9e5c4f2010-05-12 18:01:39 +00003171 u8 hasMutexBuf; /* True if holding pFile->mutexBuf */
3172 u8 sharedMask; /* Mask of shared locks held */
3173 u8 exclMask; /* Mask of exclusive locks held */
3174#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003175 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003176#endif
3177};
3178
3179/*
3180** Size increment by which shared memory grows
3181*/
3182#define SQLITE_UNIX_SHM_INCR 4096
3183
3184/*
3185** Constants used for locking
3186*/
3187#define UNIX_SHM_BASE 32 /* Byte offset of the first lock byte */
3188#define UNIX_SHM_DMS 0x01 /* Mask for Dead-Man-Switch lock */
3189#define UNIX_SHM_A 0x10 /* Mask for region locks... */
3190#define UNIX_SHM_B 0x20
3191#define UNIX_SHM_C 0x40
3192#define UNIX_SHM_D 0x80
3193
3194#ifdef SQLITE_DEBUG
3195/*
3196** Return a pointer to a nul-terminated string in static memory that
3197** describes a locking mask. The string is of the form "MSABCD" with
3198** each character representing a lock. "M" for MUTEX, "S" for DMS,
3199** and "A" through "D" for the region locks. If a lock is held, the
3200** letter is shown. If the lock is not held, the letter is converted
3201** to ".".
3202**
3203** This routine is for debugging purposes only and does not appear
3204** in a production build.
3205*/
3206static const char *unixShmLockString(u8 mask){
3207 static char zBuf[48];
3208 static int iBuf = 0;
3209 char *z;
3210
3211 z = &zBuf[iBuf];
3212 iBuf += 8;
3213 if( iBuf>=sizeof(zBuf) ) iBuf = 0;
3214
3215 z[0] = (mask & UNIX_SHM_DMS) ? 'S' : '.';
3216 z[1] = (mask & UNIX_SHM_A) ? 'A' : '.';
3217 z[2] = (mask & UNIX_SHM_B) ? 'B' : '.';
3218 z[3] = (mask & UNIX_SHM_C) ? 'C' : '.';
3219 z[4] = (mask & UNIX_SHM_D) ? 'D' : '.';
3220 z[5] = 0;
3221 return z;
3222}
3223#endif /* SQLITE_DEBUG */
3224
3225/*
3226** Apply posix advisory locks for all bytes identified in lockMask.
3227**
3228** lockMask might contain multiple bits but all bits are guaranteed
3229** to be contiguous.
3230**
3231** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3232** otherwise.
3233*/
3234static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003235 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3236 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
3237 u8 lockMask /* Which bytes to lock or unlock */
drhd9e5c4f2010-05-12 18:01:39 +00003238){
3239 struct flock f; /* The posix advisory locking structure */
3240 int lockOp; /* The opcode for fcntl() */
3241 int i; /* Offset into the locking byte range */
3242 int rc; /* Result code form fcntl() */
3243 u8 mask; /* Mask of bits in lockMask */
3244
drhd91c68f2010-05-14 14:52:25 +00003245 /* Access to the unixShmNode object is serialized by the caller */
3246 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003247
3248 /* Initialize the locking parameters */
3249 memset(&f, 0, sizeof(f));
3250 f.l_type = lockType;
3251 f.l_whence = SEEK_SET;
3252 if( lockMask==UNIX_SHM_C && lockType!=F_UNLCK ){
3253 lockOp = F_SETLKW;
3254 OSTRACE(("SHM-LOCK requesting blocking lock\n"));
3255 }else{
3256 lockOp = F_SETLK;
3257 }
3258
3259 /* Find the first bit in lockMask that is set */
3260 for(i=0, mask=0x01; mask!=0 && (lockMask&mask)==0; mask <<= 1, i++){}
3261 assert( mask!=0 );
3262 f.l_start = i+UNIX_SHM_BASE;
3263 f.l_len = 1;
3264
3265 /* Extend the locking range for each additional bit that is set */
3266 mask <<= 1;
3267 while( mask!=0 && (lockMask & mask)!=0 ){
3268 f.l_len++;
3269 mask <<= 1;
3270 }
3271
3272 /* Verify that all bits set in lockMask are contiguous */
3273 assert( mask==0 || (lockMask & ~(mask | (mask-1)))==0 );
3274
3275 /* Acquire the system-level lock */
drhd91c68f2010-05-14 14:52:25 +00003276 rc = fcntl(pShmNode->h, lockOp, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003277 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3278
3279 /* Update the global lock state and do debug tracing */
3280#ifdef SQLITE_DEBUG
3281 OSTRACE(("SHM-LOCK "));
3282 if( rc==SQLITE_OK ){
3283 if( lockType==F_UNLCK ){
3284 OSTRACE(("unlock ok"));
drhd91c68f2010-05-14 14:52:25 +00003285 pShmNode->exclMask &= ~lockMask;
3286 pShmNode->sharedMask &= ~lockMask;
drhd9e5c4f2010-05-12 18:01:39 +00003287 }else if( lockType==F_RDLCK ){
3288 OSTRACE(("read-lock ok"));
drhd91c68f2010-05-14 14:52:25 +00003289 pShmNode->exclMask &= ~lockMask;
3290 pShmNode->sharedMask |= lockMask;
drhd9e5c4f2010-05-12 18:01:39 +00003291 }else{
3292 assert( lockType==F_WRLCK );
3293 OSTRACE(("write-lock ok"));
drhd91c68f2010-05-14 14:52:25 +00003294 pShmNode->exclMask |= lockMask;
3295 pShmNode->sharedMask &= ~lockMask;
drhd9e5c4f2010-05-12 18:01:39 +00003296 }
3297 }else{
3298 if( lockType==F_UNLCK ){
3299 OSTRACE(("unlock failed"));
3300 }else if( lockType==F_RDLCK ){
3301 OSTRACE(("read-lock failed"));
3302 }else{
3303 assert( lockType==F_WRLCK );
3304 OSTRACE(("write-lock failed"));
3305 }
3306 }
3307 OSTRACE((" - change requested %s - afterwards %s:%s\n",
3308 unixShmLockString(lockMask),
drhd91c68f2010-05-14 14:52:25 +00003309 unixShmLockString(pShmNode->sharedMask),
3310 unixShmLockString(pShmNode->exclMask)));
drhd9e5c4f2010-05-12 18:01:39 +00003311#endif
3312
3313 return rc;
3314}
3315
3316/*
3317** For connection p, unlock all of the locks identified by the unlockMask
3318** parameter.
3319*/
3320static int unixShmUnlock(
drhd91c68f2010-05-14 14:52:25 +00003321 unixShmNode *pShmNode, /* The underlying shared-memory file */
3322 unixShm *p, /* The connection to be unlocked */
3323 u8 unlockMask /* Mask of locks to be unlocked */
drhd9e5c4f2010-05-12 18:01:39 +00003324){
3325 int rc; /* Result code */
3326 unixShm *pX; /* For looping over all sibling connections */
3327 u8 allMask; /* Union of locks held by connections other than "p" */
3328
drhd91c68f2010-05-14 14:52:25 +00003329 /* Access to the unixShmNode object is serialized by the caller */
3330 assert( sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00003331
3332 /* Compute locks held by sibling connections */
3333 allMask = 0;
drhd91c68f2010-05-14 14:52:25 +00003334 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drhd9e5c4f2010-05-12 18:01:39 +00003335 if( pX==p ) continue;
3336 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3337 allMask |= pX->sharedMask;
3338 }
3339
3340 /* Unlock the system-level locks */
3341 if( (unlockMask & allMask)!=unlockMask ){
drhd91c68f2010-05-14 14:52:25 +00003342 rc = unixShmSystemLock(pShmNode, F_UNLCK, unlockMask & ~allMask);
drhd9e5c4f2010-05-12 18:01:39 +00003343 }else{
3344 rc = SQLITE_OK;
3345 }
3346
3347 /* Undo the local locks */
3348 if( rc==SQLITE_OK ){
3349 p->exclMask &= ~unlockMask;
3350 p->sharedMask &= ~unlockMask;
3351 }
3352 return rc;
3353}
3354
3355/*
3356** Get reader locks for connection p on all locks in the readMask parameter.
3357*/
3358static int unixShmSharedLock(
drhd91c68f2010-05-14 14:52:25 +00003359 unixShmNode *pShmNode, /* The underlying shared-memory file */
3360 unixShm *p, /* The connection to get the shared locks */
3361 u8 readMask /* Mask of shared locks to be acquired */
drhd9e5c4f2010-05-12 18:01:39 +00003362){
3363 int rc; /* Result code */
3364 unixShm *pX; /* For looping over all sibling connections */
3365 u8 allShared; /* Union of locks held by connections other than "p" */
3366
drhd91c68f2010-05-14 14:52:25 +00003367 /* Access to the unixShmNode object is serialized by the caller */
3368 assert( sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00003369
3370 /* Find out which shared locks are already held by sibling connections.
3371 ** If any sibling already holds an exclusive lock, go ahead and return
3372 ** SQLITE_BUSY.
3373 */
3374 allShared = 0;
drhd91c68f2010-05-14 14:52:25 +00003375 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drhd9e5c4f2010-05-12 18:01:39 +00003376 if( pX==p ) continue;
3377 if( (pX->exclMask & readMask)!=0 ) return SQLITE_BUSY;
3378 allShared |= pX->sharedMask;
3379 }
3380
3381 /* Get shared locks at the system level, if necessary */
3382 if( (~allShared) & readMask ){
drhd91c68f2010-05-14 14:52:25 +00003383 rc = unixShmSystemLock(pShmNode, F_RDLCK, readMask);
drhd9e5c4f2010-05-12 18:01:39 +00003384 }else{
3385 rc = SQLITE_OK;
3386 }
3387
3388 /* Get the local shared locks */
3389 if( rc==SQLITE_OK ){
3390 p->sharedMask |= readMask;
3391 }
3392 return rc;
3393}
3394
3395/*
3396** For connection p, get an exclusive lock on all locks identified in
3397** the writeMask parameter.
3398*/
3399static int unixShmExclusiveLock(
drhd91c68f2010-05-14 14:52:25 +00003400 unixShmNode *pShmNode, /* The underlying shared-memory file */
3401 unixShm *p, /* The connection to get the exclusive locks */
3402 u8 writeMask /* Mask of exclusive locks to be acquired */
drhd9e5c4f2010-05-12 18:01:39 +00003403){
3404 int rc; /* Result code */
3405 unixShm *pX; /* For looping over all sibling connections */
3406
drhd91c68f2010-05-14 14:52:25 +00003407 /* Access to the unixShmNode object is serialized by the caller */
3408 assert( sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00003409
3410 /* Make sure no sibling connections hold locks that will block this
3411 ** lock. If any do, return SQLITE_BUSY right away.
3412 */
drhd91c68f2010-05-14 14:52:25 +00003413 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drhd9e5c4f2010-05-12 18:01:39 +00003414 if( pX==p ) continue;
3415 if( (pX->exclMask & writeMask)!=0 ) return SQLITE_BUSY;
3416 if( (pX->sharedMask & writeMask)!=0 ) return SQLITE_BUSY;
3417 }
3418
3419 /* Get the exclusive locks at the system level. Then if successful
3420 ** also mark the local connection as being locked.
3421 */
drhd91c68f2010-05-14 14:52:25 +00003422 rc = unixShmSystemLock(pShmNode, F_WRLCK, writeMask);
drhd9e5c4f2010-05-12 18:01:39 +00003423 if( rc==SQLITE_OK ){
3424 p->sharedMask &= ~writeMask;
3425 p->exclMask |= writeMask;
3426 }
3427 return rc;
3428}
3429
3430/*
drhd91c68f2010-05-14 14:52:25 +00003431** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003432**
3433** This is not a VFS shared-memory method; it is a utility function called
3434** by VFS shared-memory methods.
3435*/
drhd91c68f2010-05-14 14:52:25 +00003436static void unixShmPurge(unixFile *pFd){
3437 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003438 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003439 if( p && p->nRef==0 ){
3440 assert( p->pInode==pFd->pInode );
3441 if( p->mutex ) sqlite3_mutex_free(p->mutex);
3442 if( p->mutexBuf ) sqlite3_mutex_free(p->mutexBuf);
3443 if( p->h>=0 ) close(p->h);
3444 p->pInode->pShmNode = 0;
3445 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003446 }
3447}
3448
3449/*
3450** Open a shared-memory area. This particular implementation uses
3451** mmapped files.
3452**
3453** zName is a filename used to identify the shared-memory area. The
3454** implementation does not (and perhaps should not) use this name
3455** directly, but rather use it as a template for finding an appropriate
3456** name for the shared-memory storage. In this implementation, the
3457** string "-index" is appended to zName and used as the name of the
3458** mmapped file.
3459**
3460** When opening a new shared-memory file, if no other instances of that
3461** file are currently open, in this process or in other processes, then
3462** the file must be truncated to zero length or have its header cleared.
3463*/
3464static int unixShmOpen(
3465 sqlite3_file *fd /* The file descriptor of the associated database */
3466){
3467 struct unixShm *p = 0; /* The connection to be opened */
drhd91c68f2010-05-14 14:52:25 +00003468 struct unixShmNode *pShmNode = 0; /* The underlying mmapped file */
drhd9e5c4f2010-05-12 18:01:39 +00003469 int rc; /* Result code */
drhd9e5c4f2010-05-12 18:01:39 +00003470 struct unixFile *pDbFd; /* Underlying database file */
3471 int nPath; /* Size of pDbFd->zPath in bytes */
3472
drhd91c68f2010-05-14 14:52:25 +00003473 /* Allocate space for the new sqlite3_shm object.
drhd9e5c4f2010-05-12 18:01:39 +00003474 */
3475 p = sqlite3_malloc( sizeof(*p) );
3476 if( p==0 ) return SQLITE_NOMEM;
3477 memset(p, 0, sizeof(*p));
3478 pDbFd = (struct unixFile*)fd;
3479 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003480
drhd91c68f2010-05-14 14:52:25 +00003481 /* Check to see if a unixShmNode object already exists. Reuse an existing
3482 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003483 */
3484 unixEnterMutex();
drhd91c68f2010-05-14 14:52:25 +00003485 pShmNode = pDbFd->pInode->pShmNode;
3486 if( pShmNode==0 ){
3487 nPath = strlen(pDbFd->zPath);
3488 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nPath + 15 );
3489 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003490 rc = SQLITE_NOMEM;
3491 goto shm_open_err;
3492 }
drhd91c68f2010-05-14 14:52:25 +00003493 memset(pShmNode, 0, sizeof(*pShmNode));
3494 pShmNode->zFilename = (char*)&pShmNode[1];
3495 sqlite3_snprintf(nPath+15, pShmNode->zFilename,
3496 "%s-wal-index", pDbFd->zPath);
3497 pShmNode->h = -1;
3498 pDbFd->pInode->pShmNode = pShmNode;
3499 pShmNode->pInode = pDbFd->pInode;
3500 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3501 if( pShmNode->mutex==0 ){
3502 rc = SQLITE_NOMEM;
3503 goto shm_open_err;
3504 }
3505 pShmNode->mutexBuf = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3506 if( pShmNode->mutexBuf==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003507 rc = SQLITE_NOMEM;
3508 goto shm_open_err;
3509 }
3510
drhd91c68f2010-05-14 14:52:25 +00003511 pShmNode->h = open(pShmNode->zFilename, O_RDWR|O_CREAT, 0664);
3512 if( pShmNode->h<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003513 rc = SQLITE_CANTOPEN_BKPT;
3514 goto shm_open_err;
3515 }
3516
drhd9e5c4f2010-05-12 18:01:39 +00003517 /* Check to see if another process is holding the dead-man switch.
3518 ** If not, truncate the file to zero length.
3519 */
drhd91c68f2010-05-14 14:52:25 +00003520 rc = SQLITE_OK;
3521 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS)==SQLITE_OK ){
3522 if( ftruncate(pShmNode->h, 0) ){
drhd9e5c4f2010-05-12 18:01:39 +00003523 rc = SQLITE_IOERR;
3524 }
3525 }
3526 if( rc==SQLITE_OK ){
drhd91c68f2010-05-14 14:52:25 +00003527 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS);
drhd9e5c4f2010-05-12 18:01:39 +00003528 }
3529 if( rc ) goto shm_open_err;
3530 }
3531
drhd91c68f2010-05-14 14:52:25 +00003532 /* Make the new connection a child of the unixShmNode */
3533 p->pShmNode = pShmNode;
3534 p->pNext = pShmNode->pFirst;
drhd9e5c4f2010-05-12 18:01:39 +00003535#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003536 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003537#endif
drhd91c68f2010-05-14 14:52:25 +00003538 pShmNode->pFirst = p;
3539 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003540 pDbFd->pShm = p;
3541 unixLeaveMutex();
3542 return SQLITE_OK;
3543
3544 /* Jump here on any error */
3545shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003546 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003547 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003548 unixLeaveMutex();
3549 return rc;
3550}
3551
3552/*
3553** Close a connection to shared-memory. Delete the underlying
3554** storage if deleteFlag is true.
3555*/
3556static int unixShmClose(
3557 sqlite3_file *fd, /* The underlying database file */
3558 int deleteFlag /* Delete shared-memory if true */
3559){
3560 unixShm *p; /* The connection to be closed */
drhd91c68f2010-05-14 14:52:25 +00003561 unixShmNode *pShmNode; /* The underlying shared-memory file */
drhd9e5c4f2010-05-12 18:01:39 +00003562 unixShm **pp; /* For looping over sibling connections */
3563 unixFile *pDbFd; /* The underlying database file */
3564
3565 pDbFd = (unixFile*)fd;
3566 p = pDbFd->pShm;
3567 if( p==0 ) return SQLITE_OK;
drhd91c68f2010-05-14 14:52:25 +00003568 pShmNode = p->pShmNode;
3569
3570 assert( pShmNode==pDbFd->pInode->pShmNode );
3571 assert( pShmNode->pInode==pDbFd->pInode );
drhd9e5c4f2010-05-12 18:01:39 +00003572
3573 /* Verify that the connection being closed holds no locks */
3574 assert( p->exclMask==0 );
3575 assert( p->sharedMask==0 );
3576
drhd91c68f2010-05-14 14:52:25 +00003577 /* Remove connection p from the set of connections associated
3578 ** with pShmNode */
3579 sqlite3_mutex_enter(pShmNode->mutex);
3580 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
drhd9e5c4f2010-05-12 18:01:39 +00003581 *pp = p->pNext;
3582
3583 /* Free the connection p */
3584 sqlite3_free(p);
3585 pDbFd->pShm = 0;
drhd91c68f2010-05-14 14:52:25 +00003586 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003587
drhd91c68f2010-05-14 14:52:25 +00003588 /* If pShmNode->nRef has reached 0, then close the underlying
drhd9e5c4f2010-05-12 18:01:39 +00003589 ** shared-memory file, too */
3590 unixEnterMutex();
drhd91c68f2010-05-14 14:52:25 +00003591 assert( pShmNode->nRef>0 );
3592 pShmNode->nRef--;
3593 if( pShmNode->nRef==0 ){
3594 if( deleteFlag ) unlink(pShmNode->zFilename);
3595 unixShmPurge(pDbFd);
drhd9e5c4f2010-05-12 18:01:39 +00003596 }
3597 unixLeaveMutex();
3598
3599 return SQLITE_OK;
3600}
3601
3602/*
3603** Query and/or changes the size of the underlying storage for
3604** a shared-memory segment. The reqSize parameter is the new size
3605** of the underlying storage, or -1 to do just a query. The size
3606** of the underlying storage (after resizing if resizing occurs) is
3607** written into pNewSize.
3608**
3609** This routine does not (necessarily) change the size of the mapping
3610** of the underlying storage into memory. Use xShmGet() to change
3611** the mapping size.
3612**
3613** The reqSize parameter is the minimum size requested. The implementation
3614** is free to expand the storage to some larger amount if it chooses.
3615*/
3616static int unixShmSize(
3617 sqlite3_file *fd, /* The open database file holding SHM */
3618 int reqSize, /* Requested size. -1 for query only */
3619 int *pNewSize /* Write new size here */
3620){
3621 unixFile *pDbFd = (unixFile*)fd;
3622 unixShm *p = pDbFd->pShm;
drhd91c68f2010-05-14 14:52:25 +00003623 unixShmNode *pShmNode = p->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003624 int rc = SQLITE_OK;
3625 struct stat sStat;
3626
drhd91c68f2010-05-14 14:52:25 +00003627 assert( pShmNode==pDbFd->pInode->pShmNode );
3628 assert( pShmNode->pInode==pDbFd->pInode );
3629
drha925fd22010-05-13 08:33:35 +00003630 /* On a query, this loop runs once. When reqSize>=0, the loop potentially
3631 ** runs twice, except if the actual size is already greater than or equal
3632 ** to the requested size, reqSize is set to -1 on the first iteration and
3633 ** the loop only runs once.
3634 */
3635 while( 1 ){
drhd91c68f2010-05-14 14:52:25 +00003636 if( fstat(pShmNode->h, &sStat)==0 ){
drha925fd22010-05-13 08:33:35 +00003637 *pNewSize = (int)sStat.st_size;
3638 if( reqSize>=0 && reqSize<=(int)sStat.st_size ) break;
3639 }else{
3640 *pNewSize = 0;
3641 rc = SQLITE_IOERR;
3642 break;
3643 }
3644 if( reqSize<0 ) break;
drhd9e5c4f2010-05-12 18:01:39 +00003645 reqSize = (reqSize + SQLITE_UNIX_SHM_INCR - 1)/SQLITE_UNIX_SHM_INCR;
3646 reqSize *= SQLITE_UNIX_SHM_INCR;
drhd91c68f2010-05-14 14:52:25 +00003647 rc = ftruncate(pShmNode->h, reqSize);
drha925fd22010-05-13 08:33:35 +00003648 reqSize = -1;
drhd9e5c4f2010-05-12 18:01:39 +00003649 }
3650 return rc;
3651}
3652
3653
3654/*
3655** Map the shared storage into memory. The minimum size of the
3656** mapping should be reqMapSize if reqMapSize is positive. If
3657** reqMapSize is zero or negative, the implementation can choose
3658** whatever mapping size is convenient.
3659**
3660** *ppBuf is made to point to the memory which is a mapping of the
3661** underlying storage. A mutex is acquired to prevent other threads
3662** from running while *ppBuf is in use in order to prevent other threads
3663** remapping *ppBuf out from under this thread. The unixShmRelease()
3664** call will release the mutex. However, if the lock state is CHECKPOINT,
3665** the mutex is not acquired because CHECKPOINT will never remap the
3666** buffer. RECOVER might remap, though, so CHECKPOINT will acquire
3667** the mutex if and when it promotes to RECOVER.
3668**
3669** RECOVER needs to be atomic. The same mutex that prevents *ppBuf from
3670** being remapped also prevents more than one thread from being in
3671** RECOVER at a time. But, RECOVER sometimes wants to remap itself.
3672** To prevent RECOVER from losing its lock while remapping, the
3673** mutex is not released by unixShmRelease() when in RECOVER.
3674**
3675** *pNewMapSize is set to the size of the mapping.
3676**
3677** *ppBuf and *pNewMapSize might be NULL and zero if no space has
3678** yet been allocated to the underlying storage.
3679*/
3680static int unixShmGet(
3681 sqlite3_file *fd, /* Database file holding shared memory */
3682 int reqMapSize, /* Requested size of mapping. -1 means don't care */
3683 int *pNewMapSize, /* Write new size of mapping here */
drh5939f442010-05-18 13:27:12 +00003684 void volatile **ppBuf /* Write mapping buffer origin here */
drhd9e5c4f2010-05-12 18:01:39 +00003685){
3686 unixFile *pDbFd = (unixFile*)fd;
3687 unixShm *p = pDbFd->pShm;
drhd91c68f2010-05-14 14:52:25 +00003688 unixShmNode *pShmNode = p->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003689 int rc = SQLITE_OK;
3690
drhd91c68f2010-05-14 14:52:25 +00003691 assert( pShmNode==pDbFd->pInode->pShmNode );
3692 assert( pShmNode->pInode==pDbFd->pInode );
3693
drhd9e5c4f2010-05-12 18:01:39 +00003694 if( p->lockState!=SQLITE_SHM_CHECKPOINT && p->hasMutexBuf==0 ){
drhd91c68f2010-05-14 14:52:25 +00003695 assert( sqlite3_mutex_notheld(pShmNode->mutex) );
3696 sqlite3_mutex_enter(pShmNode->mutexBuf);
drhd9e5c4f2010-05-12 18:01:39 +00003697 p->hasMutexBuf = 1;
3698 }
drhd91c68f2010-05-14 14:52:25 +00003699 sqlite3_mutex_enter(pShmNode->mutex);
3700 if( pShmNode->szMap==0 || reqMapSize>pShmNode->szMap ){
drhd9e5c4f2010-05-12 18:01:39 +00003701 int actualSize;
3702 if( unixShmSize(fd, -1, &actualSize)==SQLITE_OK
3703 && reqMapSize<actualSize
3704 ){
3705 reqMapSize = actualSize;
3706 }
drhd91c68f2010-05-14 14:52:25 +00003707 if( pShmNode->pMMapBuf ){
3708 munmap(pShmNode->pMMapBuf, pShmNode->szMap);
drhd9e5c4f2010-05-12 18:01:39 +00003709 }
drhd91c68f2010-05-14 14:52:25 +00003710 pShmNode->pMMapBuf = mmap(0, reqMapSize, PROT_READ|PROT_WRITE, MAP_SHARED,
3711 pShmNode->h, 0);
3712 pShmNode->szMap = pShmNode->pMMapBuf ? reqMapSize : 0;
drhd9e5c4f2010-05-12 18:01:39 +00003713 }
drhd91c68f2010-05-14 14:52:25 +00003714 *pNewMapSize = pShmNode->szMap;
3715 *ppBuf = pShmNode->pMMapBuf;
3716 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003717 return rc;
3718}
3719
3720/*
3721** Release the lock held on the shared memory segment to that other
3722** threads are free to resize it if necessary.
3723**
3724** If the lock is not currently held, this routine is a harmless no-op.
3725**
3726** If the shared-memory object is in lock state RECOVER, then we do not
3727** really want to release the lock, so in that case too, this routine
3728** is a no-op.
3729*/
3730static int unixShmRelease(sqlite3_file *fd){
3731 unixFile *pDbFd = (unixFile*)fd;
3732 unixShm *p = pDbFd->pShm;
3733
3734 if( p->hasMutexBuf && p->lockState!=SQLITE_SHM_RECOVER ){
drhd91c68f2010-05-14 14:52:25 +00003735 assert( sqlite3_mutex_notheld(p->pShmNode->mutex) );
3736 sqlite3_mutex_leave(p->pShmNode->mutexBuf);
drhd9e5c4f2010-05-12 18:01:39 +00003737 p->hasMutexBuf = 0;
3738 }
3739 return SQLITE_OK;
3740}
3741
3742/*
3743** Symbolic names for LOCK states used for debugging.
3744*/
3745#ifdef SQLITE_DEBUG
3746static const char *azLkName[] = {
3747 "UNLOCK",
3748 "READ",
3749 "READ_FULL",
3750 "WRITE",
3751 "PENDING",
3752 "CHECKPOINT",
3753 "RECOVER"
3754};
3755#endif
3756
3757
3758/*
3759** Change the lock state for a shared-memory segment.
3760*/
3761static int unixShmLock(
3762 sqlite3_file *fd, /* Database file holding the shared memory */
3763 int desiredLock, /* One of SQLITE_SHM_xxxxx locking states */
3764 int *pGotLock /* The lock you actually got */
3765){
3766 unixFile *pDbFd = (unixFile*)fd;
3767 unixShm *p = pDbFd->pShm;
drhd91c68f2010-05-14 14:52:25 +00003768 unixShmNode *pShmNode = p->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003769 int rc = SQLITE_PROTOCOL;
3770
drhd91c68f2010-05-14 14:52:25 +00003771 assert( pShmNode==pDbFd->pInode->pShmNode );
3772 assert( pShmNode->pInode==pDbFd->pInode );
3773
drhd9e5c4f2010-05-12 18:01:39 +00003774 /* Note that SQLITE_SHM_READ_FULL and SQLITE_SHM_PENDING are never
3775 ** directly requested; they are side effects from requesting
3776 ** SQLITE_SHM_READ and SQLITE_SHM_CHECKPOINT, respectively.
3777 */
3778 assert( desiredLock==SQLITE_SHM_UNLOCK
3779 || desiredLock==SQLITE_SHM_READ
3780 || desiredLock==SQLITE_SHM_WRITE
3781 || desiredLock==SQLITE_SHM_CHECKPOINT
3782 || desiredLock==SQLITE_SHM_RECOVER );
3783
3784 /* Return directly if this is just a lock state query, or if
3785 ** the connection is already in the desired locking state.
3786 */
3787 if( desiredLock==p->lockState
3788 || (desiredLock==SQLITE_SHM_READ && p->lockState==SQLITE_SHM_READ_FULL)
3789 ){
3790 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s and got %s\n",
3791 p->id, getpid(), azLkName[desiredLock], azLkName[p->lockState]));
3792 if( pGotLock ) *pGotLock = p->lockState;
3793 return SQLITE_OK;
3794 }
3795
3796 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s->%s\n",
3797 p->id, getpid(), azLkName[p->lockState], azLkName[desiredLock]));
3798
3799 if( desiredLock==SQLITE_SHM_RECOVER && !p->hasMutexBuf ){
drhd91c68f2010-05-14 14:52:25 +00003800 assert( sqlite3_mutex_notheld(pShmNode->mutex) );
3801 sqlite3_mutex_enter(pShmNode->mutexBuf);
drhd9e5c4f2010-05-12 18:01:39 +00003802 p->hasMutexBuf = 1;
3803 }
drhd91c68f2010-05-14 14:52:25 +00003804 sqlite3_mutex_enter(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003805 switch( desiredLock ){
3806 case SQLITE_SHM_UNLOCK: {
3807 assert( p->lockState!=SQLITE_SHM_RECOVER );
drhd91c68f2010-05-14 14:52:25 +00003808 unixShmUnlock(pShmNode, p, UNIX_SHM_A|UNIX_SHM_B|UNIX_SHM_C|UNIX_SHM_D);
drhd9e5c4f2010-05-12 18:01:39 +00003809 rc = SQLITE_OK;
3810 p->lockState = SQLITE_SHM_UNLOCK;
3811 break;
3812 }
3813 case SQLITE_SHM_READ: {
3814 if( p->lockState==SQLITE_SHM_UNLOCK ){
3815 int nAttempt;
3816 rc = SQLITE_BUSY;
3817 assert( p->lockState==SQLITE_SHM_UNLOCK );
3818 for(nAttempt=0; nAttempt<5 && rc==SQLITE_BUSY; nAttempt++){
drhd91c68f2010-05-14 14:52:25 +00003819 rc = unixShmSharedLock(pShmNode, p, UNIX_SHM_A|UNIX_SHM_B);
drhd9e5c4f2010-05-12 18:01:39 +00003820 if( rc==SQLITE_BUSY ){
drhd91c68f2010-05-14 14:52:25 +00003821 rc = unixShmSharedLock(pShmNode, p, UNIX_SHM_D);
drhd9e5c4f2010-05-12 18:01:39 +00003822 if( rc==SQLITE_OK ){
3823 p->lockState = SQLITE_SHM_READ_FULL;
3824 }
3825 }else{
drhd91c68f2010-05-14 14:52:25 +00003826 unixShmUnlock(pShmNode, p, UNIX_SHM_B);
drhd9e5c4f2010-05-12 18:01:39 +00003827 p->lockState = SQLITE_SHM_READ;
3828 }
3829 }
3830 }else{
3831 assert( p->lockState==SQLITE_SHM_WRITE
3832 || p->lockState==SQLITE_SHM_RECOVER );
drhd91c68f2010-05-14 14:52:25 +00003833 rc = unixShmSharedLock(pShmNode, p, UNIX_SHM_A);
3834 unixShmUnlock(pShmNode, p, UNIX_SHM_C|UNIX_SHM_D);
drhd9e5c4f2010-05-12 18:01:39 +00003835 p->lockState = SQLITE_SHM_READ;
3836 }
3837 break;
3838 }
3839 case SQLITE_SHM_WRITE: {
3840 assert( p->lockState==SQLITE_SHM_READ
3841 || p->lockState==SQLITE_SHM_READ_FULL );
drhd91c68f2010-05-14 14:52:25 +00003842 rc = unixShmExclusiveLock(pShmNode, p, UNIX_SHM_C|UNIX_SHM_D);
drhd9e5c4f2010-05-12 18:01:39 +00003843 if( rc==SQLITE_OK ){
3844 p->lockState = SQLITE_SHM_WRITE;
3845 }
3846 break;
3847 }
3848 case SQLITE_SHM_CHECKPOINT: {
3849 assert( p->lockState==SQLITE_SHM_UNLOCK
3850 || p->lockState==SQLITE_SHM_PENDING
3851 );
3852 if( p->lockState==SQLITE_SHM_UNLOCK ){
drhd91c68f2010-05-14 14:52:25 +00003853 rc = unixShmExclusiveLock(pShmNode, p, UNIX_SHM_B|UNIX_SHM_C);
drhd9e5c4f2010-05-12 18:01:39 +00003854 if( rc==SQLITE_OK ){
3855 p->lockState = SQLITE_SHM_PENDING;
3856 }
3857 }
3858 if( p->lockState==SQLITE_SHM_PENDING ){
drhd91c68f2010-05-14 14:52:25 +00003859 rc = unixShmExclusiveLock(pShmNode, p, UNIX_SHM_A);
drhd9e5c4f2010-05-12 18:01:39 +00003860 if( rc==SQLITE_OK ){
3861 p->lockState = SQLITE_SHM_CHECKPOINT;
3862 }
3863 }
3864 break;
3865 }
3866 default: {
3867 assert( desiredLock==SQLITE_SHM_RECOVER );
3868 assert( p->lockState==SQLITE_SHM_READ
3869 || p->lockState==SQLITE_SHM_READ_FULL
3870 );
drhd91c68f2010-05-14 14:52:25 +00003871 assert( sqlite3_mutex_held(pShmNode->mutexBuf) );
3872 rc = unixShmExclusiveLock(pShmNode, p, UNIX_SHM_C);
drhd9e5c4f2010-05-12 18:01:39 +00003873 if( rc==SQLITE_OK ){
3874 p->lockState = SQLITE_SHM_RECOVER;
3875 }
3876 break;
3877 }
3878 }
drhd91c68f2010-05-14 14:52:25 +00003879 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003880 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %s\n",
3881 p->id, getpid(), azLkName[p->lockState]));
3882 if( pGotLock ) *pGotLock = p->lockState;
3883 return rc;
3884}
3885
drh286a2882010-05-20 23:51:06 +00003886/*
3887** Implement a memory barrier or memory fence on shared memory.
3888**
3889** All loads and stores begun before the barrier must complete before
3890** any load or store begun after the barrier.
3891*/
3892static void unixShmBarrier(
3893 sqlite3_file *fd /* Database file holding the shared memory */
3894){
3895#ifdef __GNUC__
3896 __sync_synchronize();
3897#else
3898 unixMutexEnter();
3899 unixMutexLeave();
3900#endif
3901}
3902
3903
drhd9e5c4f2010-05-12 18:01:39 +00003904#else
3905# define unixShmOpen 0
3906# define unixShmSize 0
3907# define unixShmGet 0
3908# define unixShmRelease 0
3909# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003910# define unixShmBarrier 0
drhd9e5c4f2010-05-12 18:01:39 +00003911# define unixShmClose 0
3912#endif /* #ifndef SQLITE_OMIT_WAL */
3913
drh734c9862008-11-28 15:37:20 +00003914/*
3915** Here ends the implementation of all sqlite3_file methods.
3916**
3917********************** End sqlite3_file Methods *******************************
3918******************************************************************************/
3919
3920/*
drh6b9d6dd2008-12-03 19:34:47 +00003921** This division contains definitions of sqlite3_io_methods objects that
3922** implement various file locking strategies. It also contains definitions
3923** of "finder" functions. A finder-function is used to locate the appropriate
3924** sqlite3_io_methods object for a particular database file. The pAppData
3925** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3926** the correct finder-function for that VFS.
3927**
3928** Most finder functions return a pointer to a fixed sqlite3_io_methods
3929** object. The only interesting finder-function is autolockIoFinder, which
3930** looks at the filesystem type and tries to guess the best locking
3931** strategy from that.
3932**
drh1875f7a2008-12-08 18:19:17 +00003933** For finder-funtion F, two objects are created:
3934**
3935** (1) The real finder-function named "FImpt()".
3936**
dane946c392009-08-22 11:39:46 +00003937** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003938**
3939**
3940** A pointer to the F pointer is used as the pAppData value for VFS
3941** objects. We have to do this instead of letting pAppData point
3942** directly at the finder-function since C90 rules prevent a void*
3943** from be cast into a function pointer.
3944**
drh6b9d6dd2008-12-03 19:34:47 +00003945**
drh7708e972008-11-29 00:56:52 +00003946** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003947**
drh7708e972008-11-29 00:56:52 +00003948** * A constant sqlite3_io_methods object call METHOD that has locking
3949** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3950**
3951** * An I/O method finder function called FINDER that returns a pointer
3952** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003953*/
drhd9e5c4f2010-05-12 18:01:39 +00003954#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003955static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003956 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003957 CLOSE, /* xClose */ \
3958 unixRead, /* xRead */ \
3959 unixWrite, /* xWrite */ \
3960 unixTruncate, /* xTruncate */ \
3961 unixSync, /* xSync */ \
3962 unixFileSize, /* xFileSize */ \
3963 LOCK, /* xLock */ \
3964 UNLOCK, /* xUnlock */ \
3965 CKLOCK, /* xCheckReservedLock */ \
3966 unixFileControl, /* xFileControl */ \
3967 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003968 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
3969 unixShmOpen, /* xShmOpen */ \
3970 unixShmSize, /* xShmSize */ \
3971 unixShmGet, /* xShmGet */ \
3972 unixShmRelease, /* xShmRelease */ \
3973 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003974 unixShmBarrier, /* xShmBarrier */ \
drhd9e5c4f2010-05-12 18:01:39 +00003975 unixShmClose /* xShmClose */ \
drh7708e972008-11-29 00:56:52 +00003976}; \
drh0c2694b2009-09-03 16:23:44 +00003977static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3978 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003979 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003980} \
drh0c2694b2009-09-03 16:23:44 +00003981static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003982 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003983
3984/*
3985** Here are all of the sqlite3_io_methods objects for each of the
3986** locking strategies. Functions that return pointers to these methods
3987** are also created.
3988*/
3989IOMETHODS(
3990 posixIoFinder, /* Finder function name */
3991 posixIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003992 2, /* ShmOpen is enabled */
drh7708e972008-11-29 00:56:52 +00003993 unixClose, /* xClose method */
3994 unixLock, /* xLock method */
3995 unixUnlock, /* xUnlock method */
3996 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003997)
drh7708e972008-11-29 00:56:52 +00003998IOMETHODS(
3999 nolockIoFinder, /* Finder function name */
4000 nolockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004001 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004002 nolockClose, /* xClose method */
4003 nolockLock, /* xLock method */
4004 nolockUnlock, /* xUnlock method */
4005 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004006)
drh7708e972008-11-29 00:56:52 +00004007IOMETHODS(
4008 dotlockIoFinder, /* Finder function name */
4009 dotlockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004010 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004011 dotlockClose, /* xClose method */
4012 dotlockLock, /* xLock method */
4013 dotlockUnlock, /* xUnlock method */
4014 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004015)
drh7708e972008-11-29 00:56:52 +00004016
chw78a13182009-04-07 05:35:03 +00004017#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004018IOMETHODS(
4019 flockIoFinder, /* Finder function name */
4020 flockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004021 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004022 flockClose, /* xClose method */
4023 flockLock, /* xLock method */
4024 flockUnlock, /* xUnlock method */
4025 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004026)
drh7708e972008-11-29 00:56:52 +00004027#endif
4028
drh6c7d5c52008-11-21 20:32:33 +00004029#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004030IOMETHODS(
4031 semIoFinder, /* Finder function name */
4032 semIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004033 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004034 semClose, /* xClose method */
4035 semLock, /* xLock method */
4036 semUnlock, /* xUnlock method */
4037 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004038)
aswiftaebf4132008-11-21 00:10:35 +00004039#endif
drh7708e972008-11-29 00:56:52 +00004040
drhd2cb50b2009-01-09 21:41:17 +00004041#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004042IOMETHODS(
4043 afpIoFinder, /* Finder function name */
4044 afpIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004045 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004046 afpClose, /* xClose method */
4047 afpLock, /* xLock method */
4048 afpUnlock, /* xUnlock method */
4049 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004050)
drh715ff302008-12-03 22:32:44 +00004051#endif
4052
4053/*
4054** The proxy locking method is a "super-method" in the sense that it
4055** opens secondary file descriptors for the conch and lock files and
4056** it uses proxy, dot-file, AFP, and flock() locking methods on those
4057** secondary files. For this reason, the division that implements
4058** proxy locking is located much further down in the file. But we need
4059** to go ahead and define the sqlite3_io_methods and finder function
4060** for proxy locking here. So we forward declare the I/O methods.
4061*/
drhd2cb50b2009-01-09 21:41:17 +00004062#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004063static int proxyClose(sqlite3_file*);
4064static int proxyLock(sqlite3_file*, int);
4065static int proxyUnlock(sqlite3_file*, int);
4066static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004067IOMETHODS(
4068 proxyIoFinder, /* Finder function name */
4069 proxyIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004070 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004071 proxyClose, /* xClose method */
4072 proxyLock, /* xLock method */
4073 proxyUnlock, /* xUnlock method */
4074 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004075)
aswiftaebf4132008-11-21 00:10:35 +00004076#endif
drh7708e972008-11-29 00:56:52 +00004077
drh7ed97b92010-01-20 13:07:21 +00004078/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4079#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4080IOMETHODS(
4081 nfsIoFinder, /* Finder function name */
4082 nfsIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004083 1, /* ShmOpen is disabled */
drh7ed97b92010-01-20 13:07:21 +00004084 unixClose, /* xClose method */
4085 unixLock, /* xLock method */
4086 nfsUnlock, /* xUnlock method */
4087 unixCheckReservedLock /* xCheckReservedLock method */
4088)
4089#endif
drh7708e972008-11-29 00:56:52 +00004090
drhd2cb50b2009-01-09 21:41:17 +00004091#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004092/*
drh6b9d6dd2008-12-03 19:34:47 +00004093** This "finder" function attempts to determine the best locking strategy
4094** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004095** object that implements that strategy.
4096**
4097** This is for MacOSX only.
4098*/
drh1875f7a2008-12-08 18:19:17 +00004099static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004100 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004101 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004102){
4103 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004104 const char *zFilesystem; /* Filesystem type name */
4105 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004106 } aMap[] = {
4107 { "hfs", &posixIoMethods },
4108 { "ufs", &posixIoMethods },
4109 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004110 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004111 { "webdav", &nolockIoMethods },
4112 { 0, 0 }
4113 };
4114 int i;
4115 struct statfs fsInfo;
4116 struct flock lockInfo;
4117
4118 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004119 /* If filePath==NULL that means we are dealing with a transient file
4120 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004121 return &nolockIoMethods;
4122 }
4123 if( statfs(filePath, &fsInfo) != -1 ){
4124 if( fsInfo.f_flags & MNT_RDONLY ){
4125 return &nolockIoMethods;
4126 }
4127 for(i=0; aMap[i].zFilesystem; i++){
4128 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4129 return aMap[i].pMethods;
4130 }
4131 }
4132 }
4133
4134 /* Default case. Handles, amongst others, "nfs".
4135 ** Test byte-range lock using fcntl(). If the call succeeds,
4136 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004137 */
drh7708e972008-11-29 00:56:52 +00004138 lockInfo.l_len = 1;
4139 lockInfo.l_start = 0;
4140 lockInfo.l_whence = SEEK_SET;
4141 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004142 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004143 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4144 return &nfsIoMethods;
4145 } else {
4146 return &posixIoMethods;
4147 }
drh7708e972008-11-29 00:56:52 +00004148 }else{
4149 return &dotlockIoMethods;
4150 }
4151}
drh0c2694b2009-09-03 16:23:44 +00004152static const sqlite3_io_methods
4153 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004154
drhd2cb50b2009-01-09 21:41:17 +00004155#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004156
chw78a13182009-04-07 05:35:03 +00004157#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4158/*
4159** This "finder" function attempts to determine the best locking strategy
4160** for the database file "filePath". It then returns the sqlite3_io_methods
4161** object that implements that strategy.
4162**
4163** This is for VXWorks only.
4164*/
4165static const sqlite3_io_methods *autolockIoFinderImpl(
4166 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004167 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004168){
4169 struct flock lockInfo;
4170
4171 if( !filePath ){
4172 /* If filePath==NULL that means we are dealing with a transient file
4173 ** that does not need to be locked. */
4174 return &nolockIoMethods;
4175 }
4176
4177 /* Test if fcntl() is supported and use POSIX style locks.
4178 ** Otherwise fall back to the named semaphore method.
4179 */
4180 lockInfo.l_len = 1;
4181 lockInfo.l_start = 0;
4182 lockInfo.l_whence = SEEK_SET;
4183 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004184 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004185 return &posixIoMethods;
4186 }else{
4187 return &semIoMethods;
4188 }
4189}
drh0c2694b2009-09-03 16:23:44 +00004190static const sqlite3_io_methods
4191 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004192
4193#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4194
drh7708e972008-11-29 00:56:52 +00004195/*
4196** An abstract type for a pointer to a IO method finder function:
4197*/
drh0c2694b2009-09-03 16:23:44 +00004198typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004199
aswiftaebf4132008-11-21 00:10:35 +00004200
drh734c9862008-11-28 15:37:20 +00004201/****************************************************************************
4202**************************** sqlite3_vfs methods ****************************
4203**
4204** This division contains the implementation of methods on the
4205** sqlite3_vfs object.
4206*/
4207
danielk1977a3d4c882007-03-23 10:08:38 +00004208/*
danielk1977e339d652008-06-28 11:23:00 +00004209** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004210*/
4211static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004212 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004213 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004214 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004215 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004216 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004217 int noLock, /* Omit locking if true */
4218 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004219){
drh7708e972008-11-29 00:56:52 +00004220 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004221 unixFile *pNew = (unixFile *)pId;
4222 int rc = SQLITE_OK;
4223
drh8af6c222010-05-14 12:43:01 +00004224 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004225
dane946c392009-08-22 11:39:46 +00004226 /* Parameter isDelete is only used on vxworks. Express this explicitly
4227 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004228 */
drh7708e972008-11-29 00:56:52 +00004229 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004230
drh308c2a52010-05-14 11:30:18 +00004231 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004232 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004233 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004234 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004235 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
4236 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004237
drh6c7d5c52008-11-21 20:32:33 +00004238#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004239 pNew->pId = vxworksFindFileId(zFilename);
4240 if( pNew->pId==0 ){
4241 noLock = 1;
4242 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004243 }
4244#endif
4245
drhda0e7682008-07-30 15:27:54 +00004246 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004247 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004248 }else{
drh0c2694b2009-09-03 16:23:44 +00004249 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004250#if SQLITE_ENABLE_LOCKING_STYLE
4251 /* Cache zFilename in the locking context (AFP and dotlock override) for
4252 ** proxyLock activation is possible (remote proxy is based on db name)
4253 ** zFilename remains valid until file is closed, to support */
4254 pNew->lockingContext = (void*)zFilename;
4255#endif
drhda0e7682008-07-30 15:27:54 +00004256 }
danielk1977e339d652008-06-28 11:23:00 +00004257
drh7ed97b92010-01-20 13:07:21 +00004258 if( pLockingStyle == &posixIoMethods
4259#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4260 || pLockingStyle == &nfsIoMethods
4261#endif
4262 ){
drh7708e972008-11-29 00:56:52 +00004263 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004264 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004265 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004266 /* If an error occured in findInodeInfo(), close the file descriptor
4267 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004268 ** in two scenarios:
4269 **
4270 ** (a) A call to fstat() failed.
4271 ** (b) A malloc failed.
4272 **
4273 ** Scenario (b) may only occur if the process is holding no other
4274 ** file descriptors open on the same file. If there were other file
4275 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004276 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004277 ** handle h - as it is guaranteed that no posix locks will be released
4278 ** by doing so.
4279 **
4280 ** If scenario (a) caused the error then things are not so safe. The
4281 ** implicit assumption here is that if fstat() fails, things are in
4282 ** such bad shape that dropping a lock or two doesn't matter much.
4283 */
4284 close(h);
4285 h = -1;
4286 }
drh7708e972008-11-29 00:56:52 +00004287 unixLeaveMutex();
4288 }
danielk1977e339d652008-06-28 11:23:00 +00004289
drhd2cb50b2009-01-09 21:41:17 +00004290#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004291 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004292 /* AFP locking uses the file path so it needs to be included in
4293 ** the afpLockingContext.
4294 */
4295 afpLockingContext *pCtx;
4296 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4297 if( pCtx==0 ){
4298 rc = SQLITE_NOMEM;
4299 }else{
4300 /* NB: zFilename exists and remains valid until the file is closed
4301 ** according to requirement F11141. So we do not need to make a
4302 ** copy of the filename. */
4303 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004304 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004305 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004306 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004307 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004308 if( rc!=SQLITE_OK ){
4309 sqlite3_free(pNew->lockingContext);
4310 close(h);
4311 h = -1;
4312 }
drh7708e972008-11-29 00:56:52 +00004313 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004314 }
drh7708e972008-11-29 00:56:52 +00004315 }
4316#endif
danielk1977e339d652008-06-28 11:23:00 +00004317
drh7708e972008-11-29 00:56:52 +00004318 else if( pLockingStyle == &dotlockIoMethods ){
4319 /* Dotfile locking uses the file path so it needs to be included in
4320 ** the dotlockLockingContext
4321 */
4322 char *zLockFile;
4323 int nFilename;
drhea678832008-12-10 19:26:22 +00004324 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004325 zLockFile = (char *)sqlite3_malloc(nFilename);
4326 if( zLockFile==0 ){
4327 rc = SQLITE_NOMEM;
4328 }else{
4329 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004330 }
drh7708e972008-11-29 00:56:52 +00004331 pNew->lockingContext = zLockFile;
4332 }
danielk1977e339d652008-06-28 11:23:00 +00004333
drh6c7d5c52008-11-21 20:32:33 +00004334#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004335 else if( pLockingStyle == &semIoMethods ){
4336 /* Named semaphore locking uses the file path so it needs to be
4337 ** included in the semLockingContext
4338 */
4339 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004340 rc = findInodeInfo(pNew, &pNew->pInode);
4341 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4342 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004343 int n;
drh2238dcc2009-08-27 17:56:20 +00004344 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004345 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004346 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004347 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004348 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4349 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004350 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004351 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004352 }
chw97185482008-11-17 08:05:31 +00004353 }
drh7708e972008-11-29 00:56:52 +00004354 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004355 }
drh7708e972008-11-29 00:56:52 +00004356#endif
aswift5b1a2562008-08-22 00:22:35 +00004357
4358 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004359#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004360 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004361 if( h>=0 ) close(h);
4362 h = -1;
chw97185482008-11-17 08:05:31 +00004363 unlink(zFilename);
4364 isDelete = 0;
4365 }
4366 pNew->isDelete = isDelete;
4367#endif
danielk1977e339d652008-06-28 11:23:00 +00004368 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004369 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004370 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004371 }else{
drh7708e972008-11-29 00:56:52 +00004372 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004373 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004374 }
danielk1977e339d652008-06-28 11:23:00 +00004375 return rc;
drh054889e2005-11-30 03:20:31 +00004376}
drh9c06c952005-11-26 00:25:00 +00004377
danielk1977ad94b582007-08-20 06:44:22 +00004378/*
4379** Open a file descriptor to the directory containing file zFilename.
4380** If successful, *pFd is set to the opened file descriptor and
4381** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4382** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4383** value.
4384**
4385** If SQLITE_OK is returned, the caller is responsible for closing
4386** the file descriptor *pFd using close().
4387*/
danielk1977fee2d252007-08-18 10:59:19 +00004388static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004389 int ii;
drh777b17a2007-09-20 10:02:54 +00004390 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004391 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004392
drh153c62c2007-08-24 03:51:33 +00004393 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004394 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004395 if( ii>0 ){
4396 zDirname[ii] = '\0';
4397 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004398 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004399#ifdef FD_CLOEXEC
4400 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4401#endif
drh308c2a52010-05-14 11:30:18 +00004402 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004403 }
4404 }
danielk1977fee2d252007-08-18 10:59:19 +00004405 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004406 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004407}
4408
danielk1977b4b47412007-08-17 15:53:36 +00004409/*
danielk197717b90b52008-06-06 11:11:25 +00004410** Create a temporary file name in zBuf. zBuf must be allocated
4411** by the calling process and must be big enough to hold at least
4412** pVfs->mxPathname bytes.
4413*/
4414static int getTempname(int nBuf, char *zBuf){
4415 static const char *azDirs[] = {
4416 0,
aswiftaebf4132008-11-21 00:10:35 +00004417 0,
danielk197717b90b52008-06-06 11:11:25 +00004418 "/var/tmp",
4419 "/usr/tmp",
4420 "/tmp",
4421 ".",
4422 };
4423 static const unsigned char zChars[] =
4424 "abcdefghijklmnopqrstuvwxyz"
4425 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4426 "0123456789";
drh41022642008-11-21 00:24:42 +00004427 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00004428 struct stat buf;
4429 const char *zDir = ".";
4430
4431 /* It's odd to simulate an io-error here, but really this is just
4432 ** using the io-error infrastructure to test that SQLite handles this
4433 ** function failing.
4434 */
4435 SimulateIOError( return SQLITE_IOERR );
4436
4437 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00004438 if (NULL == azDirs[1]) {
4439 azDirs[1] = getenv("TMPDIR");
4440 }
4441
4442 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00004443 if( azDirs[i]==0 ) continue;
4444 if( stat(azDirs[i], &buf) ) continue;
4445 if( !S_ISDIR(buf.st_mode) ) continue;
4446 if( access(azDirs[i], 07) ) continue;
4447 zDir = azDirs[i];
4448 break;
4449 }
4450
4451 /* Check that the output buffer is large enough for the temporary file
4452 ** name. If it is not, return SQLITE_ERROR.
4453 */
danielk197700e13612008-11-17 19:18:54 +00004454 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004455 return SQLITE_ERROR;
4456 }
4457
4458 do{
4459 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004460 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004461 sqlite3_randomness(15, &zBuf[j]);
4462 for(i=0; i<15; i++, j++){
4463 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4464 }
4465 zBuf[j] = 0;
4466 }while( access(zBuf,0)==0 );
4467 return SQLITE_OK;
4468}
4469
drhd2cb50b2009-01-09 21:41:17 +00004470#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004471/*
4472** Routine to transform a unixFile into a proxy-locking unixFile.
4473** Implementation in the proxy-lock division, but used by unixOpen()
4474** if SQLITE_PREFER_PROXY_LOCKING is defined.
4475*/
4476static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004477#endif
drhc66d5b62008-12-03 22:48:32 +00004478
dan08da86a2009-08-21 17:18:03 +00004479/*
4480** Search for an unused file descriptor that was opened on the database
4481** file (not a journal or master-journal file) identified by pathname
4482** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4483** argument to this function.
4484**
4485** Such a file descriptor may exist if a database connection was closed
4486** but the associated file descriptor could not be closed because some
4487** other file descriptor open on the same file is holding a file-lock.
4488** Refer to comments in the unixClose() function and the lengthy comment
4489** describing "Posix Advisory Locking" at the start of this file for
4490** further details. Also, ticket #4018.
4491**
4492** If a suitable file descriptor is found, then it is returned. If no
4493** such file descriptor is located, -1 is returned.
4494*/
dane946c392009-08-22 11:39:46 +00004495static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4496 UnixUnusedFd *pUnused = 0;
4497
4498 /* Do not search for an unused file descriptor on vxworks. Not because
4499 ** vxworks would not benefit from the change (it might, we're not sure),
4500 ** but because no way to test it is currently available. It is better
4501 ** not to risk breaking vxworks support for the sake of such an obscure
4502 ** feature. */
4503#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004504 struct stat sStat; /* Results of stat() call */
4505
4506 /* A stat() call may fail for various reasons. If this happens, it is
4507 ** almost certain that an open() call on the same path will also fail.
4508 ** For this reason, if an error occurs in the stat() call here, it is
4509 ** ignored and -1 is returned. The caller will try to open a new file
4510 ** descriptor on the same path, fail, and return an error to SQLite.
4511 **
4512 ** Even if a subsequent open() call does succeed, the consequences of
4513 ** not searching for a resusable file descriptor are not dire. */
4514 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004515 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004516
4517 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004518 pInode = inodeList;
4519 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4520 || pInode->fileId.ino!=sStat.st_ino) ){
4521 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004522 }
drh8af6c222010-05-14 12:43:01 +00004523 if( pInode ){
dane946c392009-08-22 11:39:46 +00004524 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004525 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004526 pUnused = *pp;
4527 if( pUnused ){
4528 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004529 }
4530 }
4531 unixLeaveMutex();
4532 }
dane946c392009-08-22 11:39:46 +00004533#endif /* if !OS_VXWORKS */
4534 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004535}
danielk197717b90b52008-06-06 11:11:25 +00004536
4537/*
danielk1977ad94b582007-08-20 06:44:22 +00004538** Open the file zPath.
4539**
danielk1977b4b47412007-08-17 15:53:36 +00004540** Previously, the SQLite OS layer used three functions in place of this
4541** one:
4542**
4543** sqlite3OsOpenReadWrite();
4544** sqlite3OsOpenReadOnly();
4545** sqlite3OsOpenExclusive();
4546**
4547** These calls correspond to the following combinations of flags:
4548**
4549** ReadWrite() -> (READWRITE | CREATE)
4550** ReadOnly() -> (READONLY)
4551** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4552**
4553** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4554** true, the file was configured to be automatically deleted when the
4555** file handle closed. To achieve the same effect using this new
4556** interface, add the DELETEONCLOSE flag to those specified above for
4557** OpenExclusive().
4558*/
4559static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004560 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4561 const char *zPath, /* Pathname of file to be opened */
4562 sqlite3_file *pFile, /* The file descriptor to be filled in */
4563 int flags, /* Input flags to control the opening */
4564 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004565){
dan08da86a2009-08-21 17:18:03 +00004566 unixFile *p = (unixFile *)pFile;
4567 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004568 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004569 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004570 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004571 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004572 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004573
4574 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4575 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4576 int isCreate = (flags & SQLITE_OPEN_CREATE);
4577 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4578 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004579#if SQLITE_ENABLE_LOCKING_STYLE
4580 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4581#endif
danielk1977b4b47412007-08-17 15:53:36 +00004582
danielk1977fee2d252007-08-18 10:59:19 +00004583 /* If creating a master or main-file journal, this function will open
4584 ** a file-descriptor on the directory too. The first time unixSync()
4585 ** is called the directory file descriptor will be fsync()ed and close()d.
4586 */
4587 int isOpenDirectory = (isCreate &&
4588 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4589 );
4590
danielk197717b90b52008-06-06 11:11:25 +00004591 /* If argument zPath is a NULL pointer, this function is required to open
4592 ** a temporary file. Use this buffer to store the file name in.
4593 */
4594 char zTmpname[MAX_PATHNAME+1];
4595 const char *zName = zPath;
4596
danielk1977fee2d252007-08-18 10:59:19 +00004597 /* Check the following statements are true:
4598 **
4599 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4600 ** (b) if CREATE is set, then READWRITE must also be set, and
4601 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004602 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004603 */
danielk1977b4b47412007-08-17 15:53:36 +00004604 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004605 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004606 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004607 assert(isDelete==0 || isCreate);
4608
drh33f4e022007-09-03 15:19:34 +00004609 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004610 ** deleted. Nor are they ever temporary files. */
4611 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4612 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4613 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004614
danielk1977fee2d252007-08-18 10:59:19 +00004615 /* Assert that the upper layer has set one of the "file-type" flags. */
4616 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4617 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4618 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004619 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004620 );
4621
dan08da86a2009-08-21 17:18:03 +00004622 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004623
dan08da86a2009-08-21 17:18:03 +00004624 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004625 UnixUnusedFd *pUnused;
4626 pUnused = findReusableFd(zName, flags);
4627 if( pUnused ){
4628 fd = pUnused->fd;
4629 }else{
dan6aa657f2009-08-24 18:57:58 +00004630 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004631 if( !pUnused ){
4632 return SQLITE_NOMEM;
4633 }
4634 }
4635 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004636 }else if( !zName ){
4637 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004638 assert(isDelete && !isOpenDirectory);
4639 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4640 if( rc!=SQLITE_OK ){
4641 return rc;
4642 }
4643 zName = zTmpname;
4644 }
4645
dan08da86a2009-08-21 17:18:03 +00004646 /* Determine the value of the flags parameter passed to POSIX function
4647 ** open(). These must be calculated even if open() is not called, as
4648 ** they may be stored as part of the file handle and used by the
4649 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004650 if( isReadonly ) openFlags |= O_RDONLY;
4651 if( isReadWrite ) openFlags |= O_RDWR;
4652 if( isCreate ) openFlags |= O_CREAT;
4653 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4654 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004655
danielk1977b4b47412007-08-17 15:53:36 +00004656 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004657 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4658 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004659 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004660 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4661 /* Failed to open the file for read/write access. Try read-only. */
4662 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004663 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004664 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004665 openFlags |= O_RDONLY;
4666 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004667 }
4668 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004669 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004670 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004671 }
danielk1977b4b47412007-08-17 15:53:36 +00004672 }
dan08da86a2009-08-21 17:18:03 +00004673 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004674 if( pOutFlags ){
4675 *pOutFlags = flags;
4676 }
4677
dane946c392009-08-22 11:39:46 +00004678 if( p->pUnused ){
4679 p->pUnused->fd = fd;
4680 p->pUnused->flags = flags;
4681 }
4682
danielk1977b4b47412007-08-17 15:53:36 +00004683 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004684#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004685 zPath = zName;
4686#else
danielk197717b90b52008-06-06 11:11:25 +00004687 unlink(zName);
chw97185482008-11-17 08:05:31 +00004688#endif
danielk1977b4b47412007-08-17 15:53:36 +00004689 }
drh41022642008-11-21 00:24:42 +00004690#if SQLITE_ENABLE_LOCKING_STYLE
4691 else{
dan08da86a2009-08-21 17:18:03 +00004692 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004693 }
4694#endif
4695
danielk1977fee2d252007-08-18 10:59:19 +00004696 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004697 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004698 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004699 /* It is safe to close fd at this point, because it is guaranteed not
4700 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004701 ** it would not be safe to close as this would release any locks held
4702 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004703 assert( eType!=SQLITE_OPEN_MAIN_DB );
4704 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004705 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004706 }
4707 }
danielk1977e339d652008-06-28 11:23:00 +00004708
4709#ifdef FD_CLOEXEC
4710 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4711#endif
4712
drhda0e7682008-07-30 15:27:54 +00004713 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004714
drh7ed97b92010-01-20 13:07:21 +00004715
4716#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4717 struct statfs fsInfo;
4718 if( fstatfs(fd, &fsInfo) == -1 ){
4719 ((unixFile*)pFile)->lastErrno = errno;
4720 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4721 close(fd); /* silently leak if fail, in error */
4722 return SQLITE_IOERR_ACCESS;
4723 }
4724 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4725 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4726 }
4727#endif
4728
4729#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004730#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004731 isAutoProxy = 1;
4732#endif
4733 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004734 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4735 int useProxy = 0;
4736
dan08da86a2009-08-21 17:18:03 +00004737 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4738 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004739 if( envforce!=NULL ){
4740 useProxy = atoi(envforce)>0;
4741 }else{
4742 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004743 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004744 /* In theory, the close(fd) call is sub-optimal. If the file opened
4745 ** with fd is a database file, and there are other connections open
4746 ** on that file that are currently holding advisory locks on it,
4747 ** then the call to close() will cancel those locks. In practice,
4748 ** we're assuming that statfs() doesn't fail very often. At least
4749 ** not while other file descriptors opened by the same process on
4750 ** the same file are working. */
4751 p->lastErrno = errno;
4752 if( dirfd>=0 ){
4753 close(dirfd); /* silently leak if fail, in error */
4754 }
aswiftaebf4132008-11-21 00:10:35 +00004755 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004756 rc = SQLITE_IOERR_ACCESS;
4757 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004758 }
4759 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4760 }
4761 if( useProxy ){
4762 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4763 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004764 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004765 if( rc!=SQLITE_OK ){
4766 /* Use unixClose to clean up the resources added in fillInUnixFile
4767 ** and clear all the structure's references. Specifically,
4768 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4769 */
4770 unixClose(pFile);
4771 return rc;
4772 }
aswiftaebf4132008-11-21 00:10:35 +00004773 }
dane946c392009-08-22 11:39:46 +00004774 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004775 }
4776 }
4777#endif
4778
dane946c392009-08-22 11:39:46 +00004779 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4780open_finished:
4781 if( rc!=SQLITE_OK ){
4782 sqlite3_free(p->pUnused);
4783 }
4784 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004785}
4786
dane946c392009-08-22 11:39:46 +00004787
danielk1977b4b47412007-08-17 15:53:36 +00004788/*
danielk1977fee2d252007-08-18 10:59:19 +00004789** Delete the file at zPath. If the dirSync argument is true, fsync()
4790** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004791*/
drh6b9d6dd2008-12-03 19:34:47 +00004792static int unixDelete(
4793 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4794 const char *zPath, /* Name of file to be deleted */
4795 int dirSync /* If true, fsync() directory after deleting file */
4796){
danielk1977fee2d252007-08-18 10:59:19 +00004797 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004798 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004799 SimulateIOError(return SQLITE_IOERR_DELETE);
4800 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004801#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004802 if( dirSync ){
4803 int fd;
4804 rc = openDirectory(zPath, &fd);
4805 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004806#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004807 if( fsync(fd)==-1 )
4808#else
4809 if( fsync(fd) )
4810#endif
4811 {
danielk1977fee2d252007-08-18 10:59:19 +00004812 rc = SQLITE_IOERR_DIR_FSYNC;
4813 }
aswiftaebf4132008-11-21 00:10:35 +00004814 if( close(fd)&&!rc ){
4815 rc = SQLITE_IOERR_DIR_CLOSE;
4816 }
danielk1977fee2d252007-08-18 10:59:19 +00004817 }
4818 }
danielk1977d138dd82008-10-15 16:02:48 +00004819#endif
danielk1977fee2d252007-08-18 10:59:19 +00004820 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004821}
4822
danielk197790949c22007-08-17 16:50:38 +00004823/*
4824** Test the existance of or access permissions of file zPath. The
4825** test performed depends on the value of flags:
4826**
4827** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4828** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4829** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4830**
4831** Otherwise return 0.
4832*/
danielk1977861f7452008-06-05 11:39:11 +00004833static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004834 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4835 const char *zPath, /* Path of the file to examine */
4836 int flags, /* What do we want to learn about the zPath file? */
4837 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004838){
rse25c0d1a2007-09-20 08:38:14 +00004839 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004840 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004841 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004842 switch( flags ){
4843 case SQLITE_ACCESS_EXISTS:
4844 amode = F_OK;
4845 break;
4846 case SQLITE_ACCESS_READWRITE:
4847 amode = W_OK|R_OK;
4848 break;
drh50d3f902007-08-27 21:10:36 +00004849 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004850 amode = R_OK;
4851 break;
4852
4853 default:
4854 assert(!"Invalid flags argument");
4855 }
danielk1977861f7452008-06-05 11:39:11 +00004856 *pResOut = (access(zPath, amode)==0);
4857 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004858}
4859
danielk1977b4b47412007-08-17 15:53:36 +00004860
4861/*
4862** Turn a relative pathname into a full pathname. The relative path
4863** is stored as a nul-terminated string in the buffer pointed to by
4864** zPath.
4865**
4866** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4867** (in this case, MAX_PATHNAME bytes). The full-path is written to
4868** this buffer before returning.
4869*/
danielk1977adfb9b02007-09-17 07:02:56 +00004870static int unixFullPathname(
4871 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4872 const char *zPath, /* Possibly relative input path */
4873 int nOut, /* Size of output buffer in bytes */
4874 char *zOut /* Output buffer */
4875){
danielk1977843e65f2007-09-01 16:16:15 +00004876
4877 /* It's odd to simulate an io-error here, but really this is just
4878 ** using the io-error infrastructure to test that SQLite handles this
4879 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004880 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004881 */
4882 SimulateIOError( return SQLITE_ERROR );
4883
drh153c62c2007-08-24 03:51:33 +00004884 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004885 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004886
drh3c7f2dc2007-12-06 13:26:20 +00004887 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004888 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004889 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004890 }else{
4891 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004892 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004893 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004894 }
drhea678832008-12-10 19:26:22 +00004895 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004896 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004897 }
4898 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004899}
4900
drh0ccebe72005-06-07 22:22:50 +00004901
drh761df872006-12-21 01:29:22 +00004902#ifndef SQLITE_OMIT_LOAD_EXTENSION
4903/*
4904** Interfaces for opening a shared library, finding entry points
4905** within the shared library, and closing the shared library.
4906*/
4907#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004908static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4909 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004910 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4911}
danielk197795c8a542007-09-01 06:51:27 +00004912
4913/*
4914** SQLite calls this function immediately after a call to unixDlSym() or
4915** unixDlOpen() fails (returns a null pointer). If a more detailed error
4916** message is available, it is written to zBufOut. If no error message
4917** is available, zBufOut is left unmodified and SQLite uses a default
4918** error message.
4919*/
danielk1977397d65f2008-11-19 11:35:39 +00004920static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004921 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004922 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004923 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004924 zErr = dlerror();
4925 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004926 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004927 }
drh6c7d5c52008-11-21 20:32:33 +00004928 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004929}
drh1875f7a2008-12-08 18:19:17 +00004930static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4931 /*
4932 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4933 ** cast into a pointer to a function. And yet the library dlsym() routine
4934 ** returns a void* which is really a pointer to a function. So how do we
4935 ** use dlsym() with -pedantic-errors?
4936 **
4937 ** Variable x below is defined to be a pointer to a function taking
4938 ** parameters void* and const char* and returning a pointer to a function.
4939 ** We initialize x by assigning it a pointer to the dlsym() function.
4940 ** (That assignment requires a cast.) Then we call the function that
4941 ** x points to.
4942 **
4943 ** This work-around is unlikely to work correctly on any system where
4944 ** you really cannot cast a function pointer into void*. But then, on the
4945 ** other hand, dlsym() will not work on such a system either, so we have
4946 ** not really lost anything.
4947 */
4948 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004949 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004950 x = (void(*(*)(void*,const char*))(void))dlsym;
4951 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004952}
danielk1977397d65f2008-11-19 11:35:39 +00004953static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4954 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004955 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004956}
danielk1977b4b47412007-08-17 15:53:36 +00004957#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4958 #define unixDlOpen 0
4959 #define unixDlError 0
4960 #define unixDlSym 0
4961 #define unixDlClose 0
4962#endif
4963
4964/*
danielk197790949c22007-08-17 16:50:38 +00004965** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004966*/
danielk1977397d65f2008-11-19 11:35:39 +00004967static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4968 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004969 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004970
drhbbd42a62004-05-22 17:41:58 +00004971 /* We have to initialize zBuf to prevent valgrind from reporting
4972 ** errors. The reports issued by valgrind are incorrect - we would
4973 ** prefer that the randomness be increased by making use of the
4974 ** uninitialized space in zBuf - but valgrind errors tend to worry
4975 ** some users. Rather than argue, it seems easier just to initialize
4976 ** the whole array and silence valgrind, even if that means less randomness
4977 ** in the random seed.
4978 **
4979 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004980 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004981 ** tests repeatable.
4982 */
danielk1977b4b47412007-08-17 15:53:36 +00004983 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004984#if !defined(SQLITE_TEST)
4985 {
drh842b8642005-01-21 17:53:17 +00004986 int pid, fd;
4987 fd = open("/dev/urandom", O_RDONLY);
4988 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004989 time_t t;
4990 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004991 memcpy(zBuf, &t, sizeof(t));
4992 pid = getpid();
4993 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004994 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004995 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004996 }else{
drh72cbd072008-10-14 17:58:38 +00004997 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004998 close(fd);
4999 }
drhbbd42a62004-05-22 17:41:58 +00005000 }
5001#endif
drh72cbd072008-10-14 17:58:38 +00005002 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005003}
5004
danielk1977b4b47412007-08-17 15:53:36 +00005005
drhbbd42a62004-05-22 17:41:58 +00005006/*
5007** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005008** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005009** The return value is the number of microseconds of sleep actually
5010** requested from the underlying operating system, a number which
5011** might be greater than or equal to the argument, but not less
5012** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005013*/
danielk1977397d65f2008-11-19 11:35:39 +00005014static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005015#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005016 struct timespec sp;
5017
5018 sp.tv_sec = microseconds / 1000000;
5019 sp.tv_nsec = (microseconds % 1000000) * 1000;
5020 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005021 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005022 return microseconds;
5023#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005024 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005025 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005026 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005027#else
danielk1977b4b47412007-08-17 15:53:36 +00005028 int seconds = (microseconds+999999)/1000000;
5029 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005030 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005031 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005032#endif
drh88f474a2006-01-02 20:00:12 +00005033}
5034
5035/*
drh6b9d6dd2008-12-03 19:34:47 +00005036** The following variable, if set to a non-zero value, is interpreted as
5037** the number of seconds since 1970 and is used to set the result of
5038** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005039*/
5040#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005041int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005042#endif
5043
5044/*
drhb7e8ea22010-05-03 14:32:30 +00005045** Find the current time (in Universal Coordinated Time). Write into *piNow
5046** the current time and date as a Julian Day number times 86_400_000. In
5047** other words, write into *piNow the number of milliseconds since the Julian
5048** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5049** proleptic Gregorian calendar.
5050**
5051** On success, return 0. Return 1 if the time and date cannot be found.
5052*/
5053static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5054 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5055#if defined(NO_GETTOD)
5056 time_t t;
5057 time(&t);
5058 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
5059#elif OS_VXWORKS
5060 struct timespec sNow;
5061 clock_gettime(CLOCK_REALTIME, &sNow);
5062 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5063#else
5064 struct timeval sNow;
5065 gettimeofday(&sNow, 0);
5066 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5067#endif
5068
5069#ifdef SQLITE_TEST
5070 if( sqlite3_current_time ){
5071 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5072 }
5073#endif
5074 UNUSED_PARAMETER(NotUsed);
5075 return 0;
5076}
5077
5078/*
drhbbd42a62004-05-22 17:41:58 +00005079** Find the current time (in Universal Coordinated Time). Write the
5080** current time and date as a Julian Day number into *prNow and
5081** return 0. Return 1 if the time and date cannot be found.
5082*/
danielk1977397d65f2008-11-19 11:35:39 +00005083static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005084 sqlite3_int64 i;
5085 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005086 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005087 return 0;
5088}
danielk1977b4b47412007-08-17 15:53:36 +00005089
drh6b9d6dd2008-12-03 19:34:47 +00005090/*
5091** We added the xGetLastError() method with the intention of providing
5092** better low-level error messages when operating-system problems come up
5093** during SQLite operation. But so far, none of that has been implemented
5094** in the core. So this routine is never called. For now, it is merely
5095** a place-holder.
5096*/
danielk1977397d65f2008-11-19 11:35:39 +00005097static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5098 UNUSED_PARAMETER(NotUsed);
5099 UNUSED_PARAMETER(NotUsed2);
5100 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005101 return 0;
5102}
5103
drhf2424c52010-04-26 00:04:55 +00005104
5105/*
drh734c9862008-11-28 15:37:20 +00005106************************ End of sqlite3_vfs methods ***************************
5107******************************************************************************/
5108
drh715ff302008-12-03 22:32:44 +00005109/******************************************************************************
5110************************** Begin Proxy Locking ********************************
5111**
5112** Proxy locking is a "uber-locking-method" in this sense: It uses the
5113** other locking methods on secondary lock files. Proxy locking is a
5114** meta-layer over top of the primitive locking implemented above. For
5115** this reason, the division that implements of proxy locking is deferred
5116** until late in the file (here) after all of the other I/O methods have
5117** been defined - so that the primitive locking methods are available
5118** as services to help with the implementation of proxy locking.
5119**
5120****
5121**
5122** The default locking schemes in SQLite use byte-range locks on the
5123** database file to coordinate safe, concurrent access by multiple readers
5124** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5125** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5126** as POSIX read & write locks over fixed set of locations (via fsctl),
5127** on AFP and SMB only exclusive byte-range locks are available via fsctl
5128** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5129** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5130** address in the shared range is taken for a SHARED lock, the entire
5131** shared range is taken for an EXCLUSIVE lock):
5132**
5133** PENDING_BYTE 0x40000000
5134** RESERVED_BYTE 0x40000001
5135** SHARED_RANGE 0x40000002 -> 0x40000200
5136**
5137** This works well on the local file system, but shows a nearly 100x
5138** slowdown in read performance on AFP because the AFP client disables
5139** the read cache when byte-range locks are present. Enabling the read
5140** cache exposes a cache coherency problem that is present on all OS X
5141** supported network file systems. NFS and AFP both observe the
5142** close-to-open semantics for ensuring cache coherency
5143** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5144** address the requirements for concurrent database access by multiple
5145** readers and writers
5146** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5147**
5148** To address the performance and cache coherency issues, proxy file locking
5149** changes the way database access is controlled by limiting access to a
5150** single host at a time and moving file locks off of the database file
5151** and onto a proxy file on the local file system.
5152**
5153**
5154** Using proxy locks
5155** -----------------
5156**
5157** C APIs
5158**
5159** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5160** <proxy_path> | ":auto:");
5161** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5162**
5163**
5164** SQL pragmas
5165**
5166** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5167** PRAGMA [database.]lock_proxy_file
5168**
5169** Specifying ":auto:" means that if there is a conch file with a matching
5170** host ID in it, the proxy path in the conch file will be used, otherwise
5171** a proxy path based on the user's temp dir
5172** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5173** actual proxy file name is generated from the name and path of the
5174** database file. For example:
5175**
5176** For database path "/Users/me/foo.db"
5177** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5178**
5179** Once a lock proxy is configured for a database connection, it can not
5180** be removed, however it may be switched to a different proxy path via
5181** the above APIs (assuming the conch file is not being held by another
5182** connection or process).
5183**
5184**
5185** How proxy locking works
5186** -----------------------
5187**
5188** Proxy file locking relies primarily on two new supporting files:
5189**
5190** * conch file to limit access to the database file to a single host
5191** at a time
5192**
5193** * proxy file to act as a proxy for the advisory locks normally
5194** taken on the database
5195**
5196** The conch file - to use a proxy file, sqlite must first "hold the conch"
5197** by taking an sqlite-style shared lock on the conch file, reading the
5198** contents and comparing the host's unique host ID (see below) and lock
5199** proxy path against the values stored in the conch. The conch file is
5200** stored in the same directory as the database file and the file name
5201** is patterned after the database file name as ".<databasename>-conch".
5202** If the conch file does not exist, or it's contents do not match the
5203** host ID and/or proxy path, then the lock is escalated to an exclusive
5204** lock and the conch file contents is updated with the host ID and proxy
5205** path and the lock is downgraded to a shared lock again. If the conch
5206** is held by another process (with a shared lock), the exclusive lock
5207** will fail and SQLITE_BUSY is returned.
5208**
5209** The proxy file - a single-byte file used for all advisory file locks
5210** normally taken on the database file. This allows for safe sharing
5211** of the database file for multiple readers and writers on the same
5212** host (the conch ensures that they all use the same local lock file).
5213**
drh715ff302008-12-03 22:32:44 +00005214** Requesting the lock proxy does not immediately take the conch, it is
5215** only taken when the first request to lock database file is made.
5216** This matches the semantics of the traditional locking behavior, where
5217** opening a connection to a database file does not take a lock on it.
5218** The shared lock and an open file descriptor are maintained until
5219** the connection to the database is closed.
5220**
5221** The proxy file and the lock file are never deleted so they only need
5222** to be created the first time they are used.
5223**
5224** Configuration options
5225** ---------------------
5226**
5227** SQLITE_PREFER_PROXY_LOCKING
5228**
5229** Database files accessed on non-local file systems are
5230** automatically configured for proxy locking, lock files are
5231** named automatically using the same logic as
5232** PRAGMA lock_proxy_file=":auto:"
5233**
5234** SQLITE_PROXY_DEBUG
5235**
5236** Enables the logging of error messages during host id file
5237** retrieval and creation
5238**
drh715ff302008-12-03 22:32:44 +00005239** LOCKPROXYDIR
5240**
5241** Overrides the default directory used for lock proxy files that
5242** are named automatically via the ":auto:" setting
5243**
5244** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5245**
5246** Permissions to use when creating a directory for storing the
5247** lock proxy files, only used when LOCKPROXYDIR is not set.
5248**
5249**
5250** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5251** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5252** force proxy locking to be used for every database file opened, and 0
5253** will force automatic proxy locking to be disabled for all database
5254** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5255** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5256*/
5257
5258/*
5259** Proxy locking is only available on MacOSX
5260*/
drhd2cb50b2009-01-09 21:41:17 +00005261#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005262
drh715ff302008-12-03 22:32:44 +00005263/*
5264** The proxyLockingContext has the path and file structures for the remote
5265** and local proxy files in it
5266*/
5267typedef struct proxyLockingContext proxyLockingContext;
5268struct proxyLockingContext {
5269 unixFile *conchFile; /* Open conch file */
5270 char *conchFilePath; /* Name of the conch file */
5271 unixFile *lockProxy; /* Open proxy lock file */
5272 char *lockProxyPath; /* Name of the proxy lock file */
5273 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005274 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005275 void *oldLockingContext; /* Original lockingcontext to restore on close */
5276 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5277};
5278
drh7ed97b92010-01-20 13:07:21 +00005279/*
5280** The proxy lock file path for the database at dbPath is written into lPath,
5281** which must point to valid, writable memory large enough for a maxLen length
5282** file path.
drh715ff302008-12-03 22:32:44 +00005283*/
drh715ff302008-12-03 22:32:44 +00005284static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5285 int len;
5286 int dbLen;
5287 int i;
5288
5289#ifdef LOCKPROXYDIR
5290 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5291#else
5292# ifdef _CS_DARWIN_USER_TEMP_DIR
5293 {
drh7ed97b92010-01-20 13:07:21 +00005294 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005295 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5296 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005297 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005298 }
drh7ed97b92010-01-20 13:07:21 +00005299 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005300 }
5301# else
5302 len = strlcpy(lPath, "/tmp/", maxLen);
5303# endif
5304#endif
5305
5306 if( lPath[len-1]!='/' ){
5307 len = strlcat(lPath, "/", maxLen);
5308 }
5309
5310 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005311 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00005312 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
5313 char c = dbPath[i];
5314 lPath[i+len] = (c=='/')?'_':c;
5315 }
5316 lPath[i+len]='\0';
5317 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005318 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005319 return SQLITE_OK;
5320}
5321
drh7ed97b92010-01-20 13:07:21 +00005322/*
5323 ** Creates the lock file and any missing directories in lockPath
5324 */
5325static int proxyCreateLockPath(const char *lockPath){
5326 int i, len;
5327 char buf[MAXPATHLEN];
5328 int start = 0;
5329
5330 assert(lockPath!=NULL);
5331 /* try to create all the intermediate directories */
5332 len = (int)strlen(lockPath);
5333 buf[0] = lockPath[0];
5334 for( i=1; i<len; i++ ){
5335 if( lockPath[i] == '/' && (i - start > 0) ){
5336 /* only mkdir if leaf dir != "." or "/" or ".." */
5337 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5338 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5339 buf[i]='\0';
5340 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5341 int err=errno;
5342 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005343 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005344 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005345 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005346 return err;
5347 }
5348 }
5349 }
5350 start=i+1;
5351 }
5352 buf[i] = lockPath[i];
5353 }
drh308c2a52010-05-14 11:30:18 +00005354 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005355 return 0;
5356}
5357
drh715ff302008-12-03 22:32:44 +00005358/*
5359** Create a new VFS file descriptor (stored in memory obtained from
5360** sqlite3_malloc) and open the file named "path" in the file descriptor.
5361**
5362** The caller is responsible not only for closing the file descriptor
5363** but also for freeing the memory associated with the file descriptor.
5364*/
drh7ed97b92010-01-20 13:07:21 +00005365static int proxyCreateUnixFile(
5366 const char *path, /* path for the new unixFile */
5367 unixFile **ppFile, /* unixFile created and returned by ref */
5368 int islockfile /* if non zero missing dirs will be created */
5369) {
5370 int fd = -1;
5371 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005372 unixFile *pNew;
5373 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005374 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005375 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005376 int terrno = 0;
5377 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005378
drh7ed97b92010-01-20 13:07:21 +00005379 /* 1. first try to open/create the file
5380 ** 2. if that fails, and this is a lock file (not-conch), try creating
5381 ** the parent directories and then try again.
5382 ** 3. if that fails, try to open the file read-only
5383 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5384 */
5385 pUnused = findReusableFd(path, openFlags);
5386 if( pUnused ){
5387 fd = pUnused->fd;
5388 }else{
5389 pUnused = sqlite3_malloc(sizeof(*pUnused));
5390 if( !pUnused ){
5391 return SQLITE_NOMEM;
5392 }
5393 }
5394 if( fd<0 ){
5395 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5396 terrno = errno;
5397 if( fd<0 && errno==ENOENT && islockfile ){
5398 if( proxyCreateLockPath(path) == SQLITE_OK ){
5399 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5400 }
5401 }
5402 }
5403 if( fd<0 ){
5404 openFlags = O_RDONLY;
5405 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5406 terrno = errno;
5407 }
5408 if( fd<0 ){
5409 if( islockfile ){
5410 return SQLITE_BUSY;
5411 }
5412 switch (terrno) {
5413 case EACCES:
5414 return SQLITE_PERM;
5415 case EIO:
5416 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5417 default:
drh9978c972010-02-23 17:36:32 +00005418 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005419 }
5420 }
5421
5422 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5423 if( pNew==NULL ){
5424 rc = SQLITE_NOMEM;
5425 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005426 }
5427 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005428 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005429 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005430 pUnused->fd = fd;
5431 pUnused->flags = openFlags;
5432 pNew->pUnused = pUnused;
5433
5434 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5435 if( rc==SQLITE_OK ){
5436 *ppFile = pNew;
5437 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005438 }
drh7ed97b92010-01-20 13:07:21 +00005439end_create_proxy:
5440 close(fd); /* silently leak fd if error, we're already in error */
5441 sqlite3_free(pNew);
5442 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005443 return rc;
5444}
5445
drh7ed97b92010-01-20 13:07:21 +00005446#ifdef SQLITE_TEST
5447/* simulate multiple hosts by creating unique hostid file paths */
5448int sqlite3_hostid_num = 0;
5449#endif
5450
5451#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5452
5453/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5454** bytes of writable memory.
5455*/
5456static int proxyGetHostID(unsigned char *pHostID, int *pError){
5457 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5458
5459 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5460 memset(pHostID, 0, PROXY_HOSTIDLEN);
5461 if( gethostuuid(pHostID, &timeout) ){
5462 int err = errno;
5463 if( pError ){
5464 *pError = err;
5465 }
5466 return SQLITE_IOERR;
5467 }
5468#ifdef SQLITE_TEST
5469 /* simulate multiple hosts by creating unique hostid file paths */
5470 if( sqlite3_hostid_num != 0){
5471 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5472 }
5473#endif
5474
5475 return SQLITE_OK;
5476}
5477
5478/* The conch file contains the header, host id and lock file path
5479 */
5480#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5481#define PROXY_HEADERLEN 1 /* conch file header length */
5482#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5483#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5484
5485/*
5486** Takes an open conch file, copies the contents to a new path and then moves
5487** it back. The newly created file's file descriptor is assigned to the
5488** conch file structure and finally the original conch file descriptor is
5489** closed. Returns zero if successful.
5490*/
5491static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5492 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5493 unixFile *conchFile = pCtx->conchFile;
5494 char tPath[MAXPATHLEN];
5495 char buf[PROXY_MAXCONCHLEN];
5496 char *cPath = pCtx->conchFilePath;
5497 size_t readLen = 0;
5498 size_t pathLen = 0;
5499 char errmsg[64] = "";
5500 int fd = -1;
5501 int rc = -1;
5502
5503 /* create a new path by replace the trailing '-conch' with '-break' */
5504 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5505 if( pathLen>MAXPATHLEN || pathLen<6 ||
5506 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5507 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5508 goto end_breaklock;
5509 }
5510 /* read the conch content */
5511 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5512 if( readLen<PROXY_PATHINDEX ){
5513 sprintf(errmsg, "read error (len %d)", (int)readLen);
5514 goto end_breaklock;
5515 }
5516 /* write it out to the temporary break file */
5517 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5518 if( fd<0 ){
5519 sprintf(errmsg, "create failed (%d)", errno);
5520 goto end_breaklock;
5521 }
5522 if( pwrite(fd, buf, readLen, 0) != readLen ){
5523 sprintf(errmsg, "write failed (%d)", errno);
5524 goto end_breaklock;
5525 }
5526 if( rename(tPath, cPath) ){
5527 sprintf(errmsg, "rename failed (%d)", errno);
5528 goto end_breaklock;
5529 }
5530 rc = 0;
5531 fprintf(stderr, "broke stale lock on %s\n", cPath);
5532 close(conchFile->h);
5533 conchFile->h = fd;
5534 conchFile->openFlags = O_RDWR | O_CREAT;
5535
5536end_breaklock:
5537 if( rc ){
5538 if( fd>=0 ){
5539 unlink(tPath);
5540 close(fd);
5541 }
5542 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5543 }
5544 return rc;
5545}
5546
5547/* Take the requested lock on the conch file and break a stale lock if the
5548** host id matches.
5549*/
5550static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5551 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5552 unixFile *conchFile = pCtx->conchFile;
5553 int rc = SQLITE_OK;
5554 int nTries = 0;
5555 struct timespec conchModTime;
5556
5557 do {
5558 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5559 nTries ++;
5560 if( rc==SQLITE_BUSY ){
5561 /* If the lock failed (busy):
5562 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5563 * 2nd try: fail if the mod time changed or host id is different, wait
5564 * 10 sec and try again
5565 * 3rd try: break the lock unless the mod time has changed.
5566 */
5567 struct stat buf;
5568 if( fstat(conchFile->h, &buf) ){
5569 pFile->lastErrno = errno;
5570 return SQLITE_IOERR_LOCK;
5571 }
5572
5573 if( nTries==1 ){
5574 conchModTime = buf.st_mtimespec;
5575 usleep(500000); /* wait 0.5 sec and try the lock again*/
5576 continue;
5577 }
5578
5579 assert( nTries>1 );
5580 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5581 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5582 return SQLITE_BUSY;
5583 }
5584
5585 if( nTries==2 ){
5586 char tBuf[PROXY_MAXCONCHLEN];
5587 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5588 if( len<0 ){
5589 pFile->lastErrno = errno;
5590 return SQLITE_IOERR_LOCK;
5591 }
5592 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5593 /* don't break the lock if the host id doesn't match */
5594 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5595 return SQLITE_BUSY;
5596 }
5597 }else{
5598 /* don't break the lock on short read or a version mismatch */
5599 return SQLITE_BUSY;
5600 }
5601 usleep(10000000); /* wait 10 sec and try the lock again */
5602 continue;
5603 }
5604
5605 assert( nTries==3 );
5606 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5607 rc = SQLITE_OK;
5608 if( lockType==EXCLUSIVE_LOCK ){
5609 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5610 }
5611 if( !rc ){
5612 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5613 }
5614 }
5615 }
5616 } while( rc==SQLITE_BUSY && nTries<3 );
5617
5618 return rc;
5619}
5620
5621/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005622** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5623** lockPath means that the lockPath in the conch file will be used if the
5624** host IDs match, or a new lock path will be generated automatically
5625** and written to the conch file.
5626*/
5627static int proxyTakeConch(unixFile *pFile){
5628 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5629
drh7ed97b92010-01-20 13:07:21 +00005630 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005631 return SQLITE_OK;
5632 }else{
5633 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005634 uuid_t myHostID;
5635 int pError = 0;
5636 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005637 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005638 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005639 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005640 int createConch = 0;
5641 int hostIdMatch = 0;
5642 int readLen = 0;
5643 int tryOldLockPath = 0;
5644 int forceNewLockPath = 0;
5645
drh308c2a52010-05-14 11:30:18 +00005646 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5647 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005648
drh7ed97b92010-01-20 13:07:21 +00005649 rc = proxyGetHostID(myHostID, &pError);
5650 if( (rc&0xff)==SQLITE_IOERR ){
5651 pFile->lastErrno = pError;
5652 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005653 }
drh7ed97b92010-01-20 13:07:21 +00005654 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005655 if( rc!=SQLITE_OK ){
5656 goto end_takeconch;
5657 }
drh7ed97b92010-01-20 13:07:21 +00005658 /* read the existing conch file */
5659 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5660 if( readLen<0 ){
5661 /* I/O error: lastErrno set by seekAndRead */
5662 pFile->lastErrno = conchFile->lastErrno;
5663 rc = SQLITE_IOERR_READ;
5664 goto end_takeconch;
5665 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5666 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5667 /* a short read or version format mismatch means we need to create a new
5668 ** conch file.
5669 */
5670 createConch = 1;
5671 }
5672 /* if the host id matches and the lock path already exists in the conch
5673 ** we'll try to use the path there, if we can't open that path, we'll
5674 ** retry with a new auto-generated path
5675 */
5676 do { /* in case we need to try again for an :auto: named lock file */
5677
5678 if( !createConch && !forceNewLockPath ){
5679 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5680 PROXY_HOSTIDLEN);
5681 /* if the conch has data compare the contents */
5682 if( !pCtx->lockProxyPath ){
5683 /* for auto-named local lock file, just check the host ID and we'll
5684 ** use the local lock file path that's already in there
5685 */
5686 if( hostIdMatch ){
5687 size_t pathLen = (readLen - PROXY_PATHINDEX);
5688
5689 if( pathLen>=MAXPATHLEN ){
5690 pathLen=MAXPATHLEN-1;
5691 }
5692 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5693 lockPath[pathLen] = 0;
5694 tempLockPath = lockPath;
5695 tryOldLockPath = 1;
5696 /* create a copy of the lock path if the conch is taken */
5697 goto end_takeconch;
5698 }
5699 }else if( hostIdMatch
5700 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5701 readLen-PROXY_PATHINDEX)
5702 ){
5703 /* conch host and lock path match */
5704 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005705 }
drh7ed97b92010-01-20 13:07:21 +00005706 }
5707
5708 /* if the conch isn't writable and doesn't match, we can't take it */
5709 if( (conchFile->openFlags&O_RDWR) == 0 ){
5710 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005711 goto end_takeconch;
5712 }
drh7ed97b92010-01-20 13:07:21 +00005713
5714 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005715 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005716 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5717 tempLockPath = lockPath;
5718 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005719 }
drh7ed97b92010-01-20 13:07:21 +00005720
5721 /* update conch with host and path (this will fail if other process
5722 ** has a shared lock already), if the host id matches, use the big
5723 ** stick.
drh715ff302008-12-03 22:32:44 +00005724 */
drh7ed97b92010-01-20 13:07:21 +00005725 futimes(conchFile->h, NULL);
5726 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005727 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005728 /* We are trying for an exclusive lock but another thread in this
5729 ** same process is still holding a shared lock. */
5730 rc = SQLITE_BUSY;
5731 } else {
5732 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005733 }
drh715ff302008-12-03 22:32:44 +00005734 }else{
drh7ed97b92010-01-20 13:07:21 +00005735 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005736 }
drh7ed97b92010-01-20 13:07:21 +00005737 if( rc==SQLITE_OK ){
5738 char writeBuffer[PROXY_MAXCONCHLEN];
5739 int writeSize = 0;
5740
5741 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5742 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5743 if( pCtx->lockProxyPath!=NULL ){
5744 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5745 }else{
5746 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5747 }
5748 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5749 ftruncate(conchFile->h, writeSize);
5750 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5751 fsync(conchFile->h);
5752 /* If we created a new conch file (not just updated the contents of a
5753 ** valid conch file), try to match the permissions of the database
5754 */
5755 if( rc==SQLITE_OK && createConch ){
5756 struct stat buf;
5757 int err = fstat(pFile->h, &buf);
5758 if( err==0 ){
5759 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5760 S_IROTH|S_IWOTH);
5761 /* try to match the database file R/W permissions, ignore failure */
5762#ifndef SQLITE_PROXY_DEBUG
5763 fchmod(conchFile->h, cmode);
5764#else
5765 if( fchmod(conchFile->h, cmode)!=0 ){
5766 int code = errno;
5767 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5768 cmode, code, strerror(code));
5769 } else {
5770 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5771 }
5772 }else{
5773 int code = errno;
5774 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5775 err, code, strerror(code));
5776#endif
5777 }
drh715ff302008-12-03 22:32:44 +00005778 }
5779 }
drh7ed97b92010-01-20 13:07:21 +00005780 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5781
5782 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005783 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005784 if( rc==SQLITE_OK && pFile->openFlags ){
5785 if( pFile->h>=0 ){
5786#ifdef STRICT_CLOSE_ERROR
5787 if( close(pFile->h) ){
5788 pFile->lastErrno = errno;
5789 return SQLITE_IOERR_CLOSE;
5790 }
5791#else
5792 close(pFile->h); /* silently leak fd if fail */
5793#endif
5794 }
5795 pFile->h = -1;
5796 int fd = open(pCtx->dbPath, pFile->openFlags,
5797 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005798 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005799 if( fd>=0 ){
5800 pFile->h = fd;
5801 }else{
drh9978c972010-02-23 17:36:32 +00005802 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005803 during locking */
5804 }
5805 }
5806 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5807 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5808 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5809 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5810 /* we couldn't create the proxy lock file with the old lock file path
5811 ** so try again via auto-naming
5812 */
5813 forceNewLockPath = 1;
5814 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005815 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005816 }
5817 }
5818 if( rc==SQLITE_OK ){
5819 /* Need to make a copy of path if we extracted the value
5820 ** from the conch file or the path was allocated on the stack
5821 */
5822 if( tempLockPath ){
5823 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5824 if( !pCtx->lockProxyPath ){
5825 rc = SQLITE_NOMEM;
5826 }
5827 }
5828 }
5829 if( rc==SQLITE_OK ){
5830 pCtx->conchHeld = 1;
5831
5832 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5833 afpLockingContext *afpCtx;
5834 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5835 afpCtx->dbPath = pCtx->lockProxyPath;
5836 }
5837 } else {
5838 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5839 }
drh308c2a52010-05-14 11:30:18 +00005840 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5841 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005842 return rc;
drh308c2a52010-05-14 11:30:18 +00005843 } while (1); /* in case we need to retry the :auto: lock file -
5844 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005845 }
5846}
5847
5848/*
5849** If pFile holds a lock on a conch file, then release that lock.
5850*/
5851static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005852 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005853 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5854 unixFile *conchFile; /* Name of the conch file */
5855
5856 pCtx = (proxyLockingContext *)pFile->lockingContext;
5857 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005858 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005859 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005860 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005861 if( pCtx->conchHeld>0 ){
5862 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5863 }
drh715ff302008-12-03 22:32:44 +00005864 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005865 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5866 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005867 return rc;
5868}
5869
5870/*
5871** Given the name of a database file, compute the name of its conch file.
5872** Store the conch filename in memory obtained from sqlite3_malloc().
5873** Make *pConchPath point to the new name. Return SQLITE_OK on success
5874** or SQLITE_NOMEM if unable to obtain memory.
5875**
5876** The caller is responsible for ensuring that the allocated memory
5877** space is eventually freed.
5878**
5879** *pConchPath is set to NULL if a memory allocation error occurs.
5880*/
5881static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5882 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005883 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005884 char *conchPath; /* buffer in which to construct conch name */
5885
5886 /* Allocate space for the conch filename and initialize the name to
5887 ** the name of the original database file. */
5888 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5889 if( conchPath==0 ){
5890 return SQLITE_NOMEM;
5891 }
5892 memcpy(conchPath, dbPath, len+1);
5893
5894 /* now insert a "." before the last / character */
5895 for( i=(len-1); i>=0; i-- ){
5896 if( conchPath[i]=='/' ){
5897 i++;
5898 break;
5899 }
5900 }
5901 conchPath[i]='.';
5902 while ( i<len ){
5903 conchPath[i+1]=dbPath[i];
5904 i++;
5905 }
5906
5907 /* append the "-conch" suffix to the file */
5908 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005909 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005910
5911 return SQLITE_OK;
5912}
5913
5914
5915/* Takes a fully configured proxy locking-style unix file and switches
5916** the local lock file path
5917*/
5918static int switchLockProxyPath(unixFile *pFile, const char *path) {
5919 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5920 char *oldPath = pCtx->lockProxyPath;
5921 int rc = SQLITE_OK;
5922
drh308c2a52010-05-14 11:30:18 +00005923 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005924 return SQLITE_BUSY;
5925 }
5926
5927 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5928 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5929 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5930 return SQLITE_OK;
5931 }else{
5932 unixFile *lockProxy = pCtx->lockProxy;
5933 pCtx->lockProxy=NULL;
5934 pCtx->conchHeld = 0;
5935 if( lockProxy!=NULL ){
5936 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5937 if( rc ) return rc;
5938 sqlite3_free(lockProxy);
5939 }
5940 sqlite3_free(oldPath);
5941 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5942 }
5943
5944 return rc;
5945}
5946
5947/*
5948** pFile is a file that has been opened by a prior xOpen call. dbPath
5949** is a string buffer at least MAXPATHLEN+1 characters in size.
5950**
5951** This routine find the filename associated with pFile and writes it
5952** int dbPath.
5953*/
5954static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005955#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005956 if( pFile->pMethod == &afpIoMethods ){
5957 /* afp style keeps a reference to the db path in the filePath field
5958 ** of the struct */
drhea678832008-12-10 19:26:22 +00005959 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005960 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5961 } else
drh715ff302008-12-03 22:32:44 +00005962#endif
5963 if( pFile->pMethod == &dotlockIoMethods ){
5964 /* dot lock style uses the locking context to store the dot lock
5965 ** file path */
5966 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5967 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5968 }else{
5969 /* all other styles use the locking context to store the db file path */
5970 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005971 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005972 }
5973 return SQLITE_OK;
5974}
5975
5976/*
5977** Takes an already filled in unix file and alters it so all file locking
5978** will be performed on the local proxy lock file. The following fields
5979** are preserved in the locking context so that they can be restored and
5980** the unix structure properly cleaned up at close time:
5981** ->lockingContext
5982** ->pMethod
5983*/
5984static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5985 proxyLockingContext *pCtx;
5986 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5987 char *lockPath=NULL;
5988 int rc = SQLITE_OK;
5989
drh308c2a52010-05-14 11:30:18 +00005990 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005991 return SQLITE_BUSY;
5992 }
5993 proxyGetDbPathForUnixFile(pFile, dbPath);
5994 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5995 lockPath=NULL;
5996 }else{
5997 lockPath=(char *)path;
5998 }
5999
drh308c2a52010-05-14 11:30:18 +00006000 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6001 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006002
6003 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6004 if( pCtx==0 ){
6005 return SQLITE_NOMEM;
6006 }
6007 memset(pCtx, 0, sizeof(*pCtx));
6008
6009 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6010 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006011 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6012 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6013 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6014 ** (c) the file system is read-only, then enable no-locking access.
6015 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6016 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6017 */
6018 struct statfs fsInfo;
6019 struct stat conchInfo;
6020 int goLockless = 0;
6021
6022 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6023 int err = errno;
6024 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6025 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6026 }
6027 }
6028 if( goLockless ){
6029 pCtx->conchHeld = -1; /* read only FS/ lockless */
6030 rc = SQLITE_OK;
6031 }
6032 }
drh715ff302008-12-03 22:32:44 +00006033 }
6034 if( rc==SQLITE_OK && lockPath ){
6035 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6036 }
6037
6038 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006039 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6040 if( pCtx->dbPath==NULL ){
6041 rc = SQLITE_NOMEM;
6042 }
6043 }
6044 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006045 /* all memory is allocated, proxys are created and assigned,
6046 ** switch the locking context and pMethod then return.
6047 */
drh715ff302008-12-03 22:32:44 +00006048 pCtx->oldLockingContext = pFile->lockingContext;
6049 pFile->lockingContext = pCtx;
6050 pCtx->pOldMethod = pFile->pMethod;
6051 pFile->pMethod = &proxyIoMethods;
6052 }else{
6053 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006054 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006055 sqlite3_free(pCtx->conchFile);
6056 }
drh7ed97b92010-01-20 13:07:21 +00006057 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006058 sqlite3_free(pCtx->conchFilePath);
6059 sqlite3_free(pCtx);
6060 }
drh308c2a52010-05-14 11:30:18 +00006061 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6062 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006063 return rc;
6064}
6065
6066
6067/*
6068** This routine handles sqlite3_file_control() calls that are specific
6069** to proxy locking.
6070*/
6071static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6072 switch( op ){
6073 case SQLITE_GET_LOCKPROXYFILE: {
6074 unixFile *pFile = (unixFile*)id;
6075 if( pFile->pMethod == &proxyIoMethods ){
6076 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6077 proxyTakeConch(pFile);
6078 if( pCtx->lockProxyPath ){
6079 *(const char **)pArg = pCtx->lockProxyPath;
6080 }else{
6081 *(const char **)pArg = ":auto: (not held)";
6082 }
6083 } else {
6084 *(const char **)pArg = NULL;
6085 }
6086 return SQLITE_OK;
6087 }
6088 case SQLITE_SET_LOCKPROXYFILE: {
6089 unixFile *pFile = (unixFile*)id;
6090 int rc = SQLITE_OK;
6091 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6092 if( pArg==NULL || (const char *)pArg==0 ){
6093 if( isProxyStyle ){
6094 /* turn off proxy locking - not supported */
6095 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6096 }else{
6097 /* turn off proxy locking - already off - NOOP */
6098 rc = SQLITE_OK;
6099 }
6100 }else{
6101 const char *proxyPath = (const char *)pArg;
6102 if( isProxyStyle ){
6103 proxyLockingContext *pCtx =
6104 (proxyLockingContext*)pFile->lockingContext;
6105 if( !strcmp(pArg, ":auto:")
6106 || (pCtx->lockProxyPath &&
6107 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6108 ){
6109 rc = SQLITE_OK;
6110 }else{
6111 rc = switchLockProxyPath(pFile, proxyPath);
6112 }
6113 }else{
6114 /* turn on proxy file locking */
6115 rc = proxyTransformUnixFile(pFile, proxyPath);
6116 }
6117 }
6118 return rc;
6119 }
6120 default: {
6121 assert( 0 ); /* The call assures that only valid opcodes are sent */
6122 }
6123 }
6124 /*NOTREACHED*/
6125 return SQLITE_ERROR;
6126}
6127
6128/*
6129** Within this division (the proxying locking implementation) the procedures
6130** above this point are all utilities. The lock-related methods of the
6131** proxy-locking sqlite3_io_method object follow.
6132*/
6133
6134
6135/*
6136** This routine checks if there is a RESERVED lock held on the specified
6137** file by this or any other process. If such a lock is held, set *pResOut
6138** to a non-zero value otherwise *pResOut is set to zero. The return value
6139** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6140*/
6141static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6142 unixFile *pFile = (unixFile*)id;
6143 int rc = proxyTakeConch(pFile);
6144 if( rc==SQLITE_OK ){
6145 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006146 if( pCtx->conchHeld>0 ){
6147 unixFile *proxy = pCtx->lockProxy;
6148 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6149 }else{ /* conchHeld < 0 is lockless */
6150 pResOut=0;
6151 }
drh715ff302008-12-03 22:32:44 +00006152 }
6153 return rc;
6154}
6155
6156/*
drh308c2a52010-05-14 11:30:18 +00006157** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006158** of the following:
6159**
6160** (1) SHARED_LOCK
6161** (2) RESERVED_LOCK
6162** (3) PENDING_LOCK
6163** (4) EXCLUSIVE_LOCK
6164**
6165** Sometimes when requesting one lock state, additional lock states
6166** are inserted in between. The locking might fail on one of the later
6167** transitions leaving the lock state different from what it started but
6168** still short of its goal. The following chart shows the allowed
6169** transitions and the inserted intermediate states:
6170**
6171** UNLOCKED -> SHARED
6172** SHARED -> RESERVED
6173** SHARED -> (PENDING) -> EXCLUSIVE
6174** RESERVED -> (PENDING) -> EXCLUSIVE
6175** PENDING -> EXCLUSIVE
6176**
6177** This routine will only increase a lock. Use the sqlite3OsUnlock()
6178** routine to lower a locking level.
6179*/
drh308c2a52010-05-14 11:30:18 +00006180static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006181 unixFile *pFile = (unixFile*)id;
6182 int rc = proxyTakeConch(pFile);
6183 if( rc==SQLITE_OK ){
6184 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006185 if( pCtx->conchHeld>0 ){
6186 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006187 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6188 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006189 }else{
6190 /* conchHeld < 0 is lockless */
6191 }
drh715ff302008-12-03 22:32:44 +00006192 }
6193 return rc;
6194}
6195
6196
6197/*
drh308c2a52010-05-14 11:30:18 +00006198** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006199** must be either NO_LOCK or SHARED_LOCK.
6200**
6201** If the locking level of the file descriptor is already at or below
6202** the requested locking level, this routine is a no-op.
6203*/
drh308c2a52010-05-14 11:30:18 +00006204static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006205 unixFile *pFile = (unixFile*)id;
6206 int rc = proxyTakeConch(pFile);
6207 if( rc==SQLITE_OK ){
6208 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006209 if( pCtx->conchHeld>0 ){
6210 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006211 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6212 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006213 }else{
6214 /* conchHeld < 0 is lockless */
6215 }
drh715ff302008-12-03 22:32:44 +00006216 }
6217 return rc;
6218}
6219
6220/*
6221** Close a file that uses proxy locks.
6222*/
6223static int proxyClose(sqlite3_file *id) {
6224 if( id ){
6225 unixFile *pFile = (unixFile*)id;
6226 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6227 unixFile *lockProxy = pCtx->lockProxy;
6228 unixFile *conchFile = pCtx->conchFile;
6229 int rc = SQLITE_OK;
6230
6231 if( lockProxy ){
6232 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6233 if( rc ) return rc;
6234 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6235 if( rc ) return rc;
6236 sqlite3_free(lockProxy);
6237 pCtx->lockProxy = 0;
6238 }
6239 if( conchFile ){
6240 if( pCtx->conchHeld ){
6241 rc = proxyReleaseConch(pFile);
6242 if( rc ) return rc;
6243 }
6244 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6245 if( rc ) return rc;
6246 sqlite3_free(conchFile);
6247 }
6248 sqlite3_free(pCtx->lockProxyPath);
6249 sqlite3_free(pCtx->conchFilePath);
6250 sqlite3_free(pCtx->dbPath);
6251 /* restore the original locking context and pMethod then close it */
6252 pFile->lockingContext = pCtx->oldLockingContext;
6253 pFile->pMethod = pCtx->pOldMethod;
6254 sqlite3_free(pCtx);
6255 return pFile->pMethod->xClose(id);
6256 }
6257 return SQLITE_OK;
6258}
6259
6260
6261
drhd2cb50b2009-01-09 21:41:17 +00006262#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006263/*
6264** The proxy locking style is intended for use with AFP filesystems.
6265** And since AFP is only supported on MacOSX, the proxy locking is also
6266** restricted to MacOSX.
6267**
6268**
6269******************* End of the proxy lock implementation **********************
6270******************************************************************************/
6271
drh734c9862008-11-28 15:37:20 +00006272/*
danielk1977e339d652008-06-28 11:23:00 +00006273** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006274**
6275** This routine registers all VFS implementations for unix-like operating
6276** systems. This routine, and the sqlite3_os_end() routine that follows,
6277** should be the only routines in this file that are visible from other
6278** files.
drh6b9d6dd2008-12-03 19:34:47 +00006279**
6280** This routine is called once during SQLite initialization and by a
6281** single thread. The memory allocation and mutex subsystems have not
6282** necessarily been initialized when this routine is called, and so they
6283** should not be used.
drh153c62c2007-08-24 03:51:33 +00006284*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006285int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006286 /*
6287 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006288 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6289 ** to the "finder" function. (pAppData is a pointer to a pointer because
6290 ** silly C90 rules prohibit a void* from being cast to a function pointer
6291 ** and so we have to go through the intermediate pointer to avoid problems
6292 ** when compiling with -pedantic-errors on GCC.)
6293 **
6294 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006295 ** finder-function. The finder-function returns a pointer to the
6296 ** sqlite_io_methods object that implements the desired locking
6297 ** behaviors. See the division above that contains the IOMETHODS
6298 ** macro for addition information on finder-functions.
6299 **
6300 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6301 ** object. But the "autolockIoFinder" available on MacOSX does a little
6302 ** more than that; it looks at the filesystem type that hosts the
6303 ** database file and tries to choose an locking method appropriate for
6304 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006305 */
drh7708e972008-11-29 00:56:52 +00006306 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006307 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006308 sizeof(unixFile), /* szOsFile */ \
6309 MAX_PATHNAME, /* mxPathname */ \
6310 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006311 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006312 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006313 unixOpen, /* xOpen */ \
6314 unixDelete, /* xDelete */ \
6315 unixAccess, /* xAccess */ \
6316 unixFullPathname, /* xFullPathname */ \
6317 unixDlOpen, /* xDlOpen */ \
6318 unixDlError, /* xDlError */ \
6319 unixDlSym, /* xDlSym */ \
6320 unixDlClose, /* xDlClose */ \
6321 unixRandomness, /* xRandomness */ \
6322 unixSleep, /* xSleep */ \
6323 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006324 unixGetLastError, /* xGetLastError */ \
drhf2424c52010-04-26 00:04:55 +00006325 0, /* xRename */ \
drhb7e8ea22010-05-03 14:32:30 +00006326 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006327 }
6328
drh6b9d6dd2008-12-03 19:34:47 +00006329 /*
6330 ** All default VFSes for unix are contained in the following array.
6331 **
6332 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6333 ** by the SQLite core when the VFS is registered. So the following
6334 ** array cannot be const.
6335 */
danielk1977e339d652008-06-28 11:23:00 +00006336 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006337#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006338 UNIXVFS("unix", autolockIoFinder ),
6339#else
6340 UNIXVFS("unix", posixIoFinder ),
6341#endif
6342 UNIXVFS("unix-none", nolockIoFinder ),
6343 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006344#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006345 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006346#endif
6347#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006348 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006349#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006350 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006351#endif
chw78a13182009-04-07 05:35:03 +00006352#endif
drhd2cb50b2009-01-09 21:41:17 +00006353#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006354 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006355 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006356 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006357#endif
drh153c62c2007-08-24 03:51:33 +00006358 };
drh6b9d6dd2008-12-03 19:34:47 +00006359 unsigned int i; /* Loop counter */
6360
6361 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006362 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006363 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006364 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006365 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006366}
danielk1977e339d652008-06-28 11:23:00 +00006367
6368/*
drh6b9d6dd2008-12-03 19:34:47 +00006369** Shutdown the operating system interface.
6370**
6371** Some operating systems might need to do some cleanup in this routine,
6372** to release dynamically allocated objects. But not on unix.
6373** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006374*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006375int sqlite3_os_end(void){
6376 return SQLITE_OK;
6377}
drhdce8bdb2007-08-16 13:01:44 +00006378
danielk197729bafea2008-06-26 10:41:19 +00006379#endif /* SQLITE_OS_UNIX */