blob: d522f99000b0442a9f73f0c09f95735ca32dd1bf [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
drhd9e5c4f2010-05-12 18:01:39 +0000178/* Forward reference */
179typedef struct unixShm unixShm;
180typedef struct unixShmFile unixShmFile;
drh9cbe6352005-11-29 03:13:21 +0000181
182/*
dane946c392009-08-22 11:39:46 +0000183** Sometimes, after a file handle is closed by SQLite, the file descriptor
184** cannot be closed immediately. In these cases, instances of the following
185** structure are used to store the file descriptor while waiting for an
186** opportunity to either close or reuse it.
187*/
188typedef struct UnixUnusedFd UnixUnusedFd;
189struct UnixUnusedFd {
190 int fd; /* File descriptor to close */
191 int flags; /* Flags this file descriptor was opened with */
192 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
193};
194
195/*
drh9b35ea62008-11-29 02:20:26 +0000196** The unixFile structure is subclass of sqlite3_file specific to the unix
197** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000198*/
drh054889e2005-11-30 03:20:31 +0000199typedef struct unixFile unixFile;
200struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000201 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000202 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
203 struct unixLockInfo *pLock; /* Info about locks on this inode */
204 int h; /* The file descriptor */
205 int dirfd; /* File descriptor for the directory */
drh308c2a52010-05-14 11:30:18 +0000206 unsigned char eFileLock; /* The type of lock held on this fd */
drh6c7d5c52008-11-21 20:32:33 +0000207 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000208 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000209 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000210 int fileFlags; /* Miscellanous flags */
drhd9e5c4f2010-05-12 18:01:39 +0000211 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
214 int openFlags; /* The flags specified at open() */
215#endif
drh7ed97b92010-01-20 13:07:21 +0000216#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
217 unsigned fsFlags; /* cached details from statfs() */
218#endif
drh734c9862008-11-28 15:37:20 +0000219#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000220 pthread_t tid; /* The thread that "owns" this unixFile */
221#endif
222#if OS_VXWORKS
223 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drh0c2694b2009-09-03 16:23:44 +0000247** The following macros define bits in unixFile.fileFlags
248*/
249#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
250
251/*
drh198bf392006-01-06 21:52:49 +0000252** Include code that is common to all os_*.c files
253*/
254#include "os_common.h"
255
256/*
drh0ccebe72005-06-07 22:22:50 +0000257** Define various macros that are missing from some systems.
258*/
drhbbd42a62004-05-22 17:41:58 +0000259#ifndef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifdef SQLITE_DISABLE_LFS
263# undef O_LARGEFILE
264# define O_LARGEFILE 0
265#endif
266#ifndef O_NOFOLLOW
267# define O_NOFOLLOW 0
268#endif
269#ifndef O_BINARY
270# define O_BINARY 0
271#endif
272
273/*
274** The DJGPP compiler environment looks mostly like Unix, but it
275** lacks the fcntl() system call. So redefine fcntl() to be something
276** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000277** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000278*/
279#ifdef __DJGPP__
280# define fcntl(A,B,C) 0
281#endif
282
283/*
drh2b4b5962005-06-15 17:47:55 +0000284** The threadid macro resolves to the thread-id or to 0. Used for
285** testing and debugging only.
286*/
drhd677b3d2007-08-20 22:48:41 +0000287#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000288#define threadid pthread_self()
289#else
290#define threadid 0
291#endif
292
danielk197713adf8a2004-06-03 16:08:41 +0000293
drh107886a2008-11-21 22:21:50 +0000294/*
dan9359c7b2009-08-21 08:29:10 +0000295** Helper functions to obtain and relinquish the global mutex. The
296** global mutex is used to protect the unixOpenCnt, unixLockInfo and
297** vxworksFileId objects used by this file, all of which may be
298** shared by multiple threads.
299**
300** Function unixMutexHeld() is used to assert() that the global mutex
301** is held when required. This function is only used as part of assert()
302** statements. e.g.
303**
304** unixEnterMutex()
305** assert( unixMutexHeld() );
306** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000307*/
308static void unixEnterMutex(void){
309 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
310}
311static void unixLeaveMutex(void){
312 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
313}
dan9359c7b2009-08-21 08:29:10 +0000314#ifdef SQLITE_DEBUG
315static int unixMutexHeld(void) {
316 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
317}
318#endif
drh107886a2008-11-21 22:21:50 +0000319
drh734c9862008-11-28 15:37:20 +0000320
321#ifdef SQLITE_DEBUG
322/*
323** Helper function for printing out trace information from debugging
324** binaries. This returns the string represetation of the supplied
325** integer lock-type.
326*/
drh308c2a52010-05-14 11:30:18 +0000327static const char *azFileLock(int eFileLock){
328 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000329 case NO_LOCK: return "NONE";
330 case SHARED_LOCK: return "SHARED";
331 case RESERVED_LOCK: return "RESERVED";
332 case PENDING_LOCK: return "PENDING";
333 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000334 }
335 return "ERROR";
336}
337#endif
338
339#ifdef SQLITE_LOCK_TRACE
340/*
341** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000342**
drh734c9862008-11-28 15:37:20 +0000343** This routine is used for troubleshooting locks on multithreaded
344** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
345** command-line option on the compiler. This code is normally
346** turned off.
347*/
348static int lockTrace(int fd, int op, struct flock *p){
349 char *zOpName, *zType;
350 int s;
351 int savedErrno;
352 if( op==F_GETLK ){
353 zOpName = "GETLK";
354 }else if( op==F_SETLK ){
355 zOpName = "SETLK";
356 }else{
357 s = fcntl(fd, op, p);
358 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
359 return s;
360 }
361 if( p->l_type==F_RDLCK ){
362 zType = "RDLCK";
363 }else if( p->l_type==F_WRLCK ){
364 zType = "WRLCK";
365 }else if( p->l_type==F_UNLCK ){
366 zType = "UNLCK";
367 }else{
368 assert( 0 );
369 }
370 assert( p->l_whence==SEEK_SET );
371 s = fcntl(fd, op, p);
372 savedErrno = errno;
373 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
374 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
375 (int)p->l_pid, s);
376 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
377 struct flock l2;
378 l2 = *p;
379 fcntl(fd, F_GETLK, &l2);
380 if( l2.l_type==F_RDLCK ){
381 zType = "RDLCK";
382 }else if( l2.l_type==F_WRLCK ){
383 zType = "WRLCK";
384 }else if( l2.l_type==F_UNLCK ){
385 zType = "UNLCK";
386 }else{
387 assert( 0 );
388 }
389 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
390 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
391 }
392 errno = savedErrno;
393 return s;
394}
395#define fcntl lockTrace
396#endif /* SQLITE_LOCK_TRACE */
397
398
399
400/*
401** This routine translates a standard POSIX errno code into something
402** useful to the clients of the sqlite3 functions. Specifically, it is
403** intended to translate a variety of "try again" errors into SQLITE_BUSY
404** and a variety of "please close the file descriptor NOW" errors into
405** SQLITE_IOERR
406**
407** Errors during initialization of locks, or file system support for locks,
408** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
409*/
410static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
411 switch (posixError) {
412 case 0:
413 return SQLITE_OK;
414
415 case EAGAIN:
416 case ETIMEDOUT:
417 case EBUSY:
418 case EINTR:
419 case ENOLCK:
420 /* random NFS retry error, unless during file system support
421 * introspection, in which it actually means what it says */
422 return SQLITE_BUSY;
423
424 case EACCES:
425 /* EACCES is like EAGAIN during locking operations, but not any other time*/
426 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
427 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
428 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
429 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
430 return SQLITE_BUSY;
431 }
432 /* else fall through */
433 case EPERM:
434 return SQLITE_PERM;
435
436 case EDEADLK:
437 return SQLITE_IOERR_BLOCKED;
438
439#if EOPNOTSUPP!=ENOTSUP
440 case EOPNOTSUPP:
441 /* something went terribly awry, unless during file system support
442 * introspection, in which it actually means what it says */
443#endif
444#ifdef ENOTSUP
445 case ENOTSUP:
446 /* invalid fd, unless during file system support introspection, in which
447 * it actually means what it says */
448#endif
449 case EIO:
450 case EBADF:
451 case EINVAL:
452 case ENOTCONN:
453 case ENODEV:
454 case ENXIO:
455 case ENOENT:
456 case ESTALE:
457 case ENOSYS:
458 /* these should force the client to close the file and reconnect */
459
460 default:
461 return sqliteIOErr;
462 }
463}
464
465
466
467/******************************************************************************
468****************** Begin Unique File ID Utility Used By VxWorks ***************
469**
470** On most versions of unix, we can get a unique ID for a file by concatenating
471** the device number and the inode number. But this does not work on VxWorks.
472** On VxWorks, a unique file id must be based on the canonical filename.
473**
474** A pointer to an instance of the following structure can be used as a
475** unique file ID in VxWorks. Each instance of this structure contains
476** a copy of the canonical filename. There is also a reference count.
477** The structure is reclaimed when the number of pointers to it drops to
478** zero.
479**
480** There are never very many files open at one time and lookups are not
481** a performance-critical path, so it is sufficient to put these
482** structures on a linked list.
483*/
484struct vxworksFileId {
485 struct vxworksFileId *pNext; /* Next in a list of them all */
486 int nRef; /* Number of references to this one */
487 int nName; /* Length of the zCanonicalName[] string */
488 char *zCanonicalName; /* Canonical filename */
489};
490
491#if OS_VXWORKS
492/*
drh9b35ea62008-11-29 02:20:26 +0000493** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000494** variable:
495*/
496static struct vxworksFileId *vxworksFileList = 0;
497
498/*
499** Simplify a filename into its canonical form
500** by making the following changes:
501**
502** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000503** * convert /./ into just /
504** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000505**
506** Changes are made in-place. Return the new name length.
507**
508** The original filename is in z[0..n-1]. Return the number of
509** characters in the simplified name.
510*/
511static int vxworksSimplifyName(char *z, int n){
512 int i, j;
513 while( n>1 && z[n-1]=='/' ){ n--; }
514 for(i=j=0; i<n; i++){
515 if( z[i]=='/' ){
516 if( z[i+1]=='/' ) continue;
517 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
518 i += 1;
519 continue;
520 }
521 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
522 while( j>0 && z[j-1]!='/' ){ j--; }
523 if( j>0 ){ j--; }
524 i += 2;
525 continue;
526 }
527 }
528 z[j++] = z[i];
529 }
530 z[j] = 0;
531 return j;
532}
533
534/*
535** Find a unique file ID for the given absolute pathname. Return
536** a pointer to the vxworksFileId object. This pointer is the unique
537** file ID.
538**
539** The nRef field of the vxworksFileId object is incremented before
540** the object is returned. A new vxworksFileId object is created
541** and added to the global list if necessary.
542**
543** If a memory allocation error occurs, return NULL.
544*/
545static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
546 struct vxworksFileId *pNew; /* search key and new file ID */
547 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
548 int n; /* Length of zAbsoluteName string */
549
550 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000551 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000552 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
553 if( pNew==0 ) return 0;
554 pNew->zCanonicalName = (char*)&pNew[1];
555 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
556 n = vxworksSimplifyName(pNew->zCanonicalName, n);
557
558 /* Search for an existing entry that matching the canonical name.
559 ** If found, increment the reference count and return a pointer to
560 ** the existing file ID.
561 */
562 unixEnterMutex();
563 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
564 if( pCandidate->nName==n
565 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
566 ){
567 sqlite3_free(pNew);
568 pCandidate->nRef++;
569 unixLeaveMutex();
570 return pCandidate;
571 }
572 }
573
574 /* No match was found. We will make a new file ID */
575 pNew->nRef = 1;
576 pNew->nName = n;
577 pNew->pNext = vxworksFileList;
578 vxworksFileList = pNew;
579 unixLeaveMutex();
580 return pNew;
581}
582
583/*
584** Decrement the reference count on a vxworksFileId object. Free
585** the object when the reference count reaches zero.
586*/
587static void vxworksReleaseFileId(struct vxworksFileId *pId){
588 unixEnterMutex();
589 assert( pId->nRef>0 );
590 pId->nRef--;
591 if( pId->nRef==0 ){
592 struct vxworksFileId **pp;
593 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
594 assert( *pp==pId );
595 *pp = pId->pNext;
596 sqlite3_free(pId);
597 }
598 unixLeaveMutex();
599}
600#endif /* OS_VXWORKS */
601/*************** End of Unique File ID Utility Used By VxWorks ****************
602******************************************************************************/
603
604
605/******************************************************************************
606*************************** Posix Advisory Locking ****************************
607**
drh9b35ea62008-11-29 02:20:26 +0000608** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000609** section 6.5.2.2 lines 483 through 490 specify that when a process
610** sets or clears a lock, that operation overrides any prior locks set
611** by the same process. It does not explicitly say so, but this implies
612** that it overrides locks set by the same process using a different
613** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000614**
615** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000616** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
617**
618** Suppose ./file1 and ./file2 are really the same file (because
619** one is a hard or symbolic link to the other) then if you set
620** an exclusive lock on fd1, then try to get an exclusive lock
621** on fd2, it works. I would have expected the second lock to
622** fail since there was already a lock on the file due to fd1.
623** But not so. Since both locks came from the same process, the
624** second overrides the first, even though they were on different
625** file descriptors opened on different file names.
626**
drh734c9862008-11-28 15:37:20 +0000627** This means that we cannot use POSIX locks to synchronize file access
628** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000629** to synchronize access for threads in separate processes, but not
630** threads within the same process.
631**
632** To work around the problem, SQLite has to manage file locks internally
633** on its own. Whenever a new database is opened, we have to find the
634** specific inode of the database file (the inode is determined by the
635** st_dev and st_ino fields of the stat structure that fstat() fills in)
636** and check for locks already existing on that inode. When locks are
637** created or removed, we have to look at our own internal record of the
638** locks to see if another thread has previously set a lock on that same
639** inode.
640**
drh9b35ea62008-11-29 02:20:26 +0000641** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
642** For VxWorks, we have to use the alternative unique ID system based on
643** canonical filename and implemented in the previous division.)
644**
danielk1977ad94b582007-08-20 06:44:22 +0000645** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000646** descriptor. It is now a structure that holds the integer file
647** descriptor and a pointer to a structure that describes the internal
648** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000649** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000650** point to the same locking structure. The locking structure keeps
651** a reference count (so we will know when to delete it) and a "cnt"
652** field that tells us its internal lock status. cnt==0 means the
653** file is unlocked. cnt==-1 means the file has an exclusive lock.
654** cnt>0 means there are cnt shared locks on the file.
655**
656** Any attempt to lock or unlock a file first checks the locking
657** structure. The fcntl() system call is only invoked to set a
658** POSIX lock if the internal lock structure transitions between
659** a locked and an unlocked state.
660**
drh734c9862008-11-28 15:37:20 +0000661** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000662**
663** If you close a file descriptor that points to a file that has locks,
664** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000665** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000666** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000667** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000668** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000669** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000670** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000671** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000672** be closed and that list is walked (and cleared) when the last lock
673** clears.
674**
drh9b35ea62008-11-29 02:20:26 +0000675** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000676**
drh9b35ea62008-11-29 02:20:26 +0000677** Many older versions of linux use the LinuxThreads library which is
678** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000679** A cannot be modified or overridden by a different thread B.
680** Only thread A can modify the lock. Locking behavior is correct
681** if the appliation uses the newer Native Posix Thread Library (NPTL)
682** on linux - with NPTL a lock created by thread A can override locks
683** in thread B. But there is no way to know at compile-time which
684** threading library is being used. So there is no way to know at
685** compile-time whether or not thread A can override locks on thread B.
686** We have to do a run-time check to discover the behavior of the
687** current process.
drh5fdae772004-06-29 03:29:00 +0000688**
drh734c9862008-11-28 15:37:20 +0000689** On systems where thread A is unable to modify locks created by
690** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000691** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000692** structure to record this information. And on those systems it
693** is illegal to begin a transaction in one thread and finish it
694** in another. For this latter restriction, there is no work-around.
695** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000696*/
697
698/*
drh6c7d5c52008-11-21 20:32:33 +0000699** Set or check the unixFile.tid field. This field is set when an unixFile
700** is first opened. All subsequent uses of the unixFile verify that the
701** same thread is operating on the unixFile. Some operating systems do
702** not allow locks to be overridden by other threads and that restriction
703** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000704** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000705**
706** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
707** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000708** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000709** or if no locks are held. But the unixFile.pLock field needs to be
710** recomputed because its key includes the thread-id. See the
711** transferOwnership() function below for additional information
712*/
drh734c9862008-11-28 15:37:20 +0000713#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000714# define SET_THREADID(X) (X)->tid = pthread_self()
715# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
716 !pthread_equal((X)->tid, pthread_self()))
717#else
718# define SET_THREADID(X)
719# define CHECK_THREADID(X) 0
720#endif
721
722/*
drhbbd42a62004-05-22 17:41:58 +0000723** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000724** to locate a particular unixOpenCnt structure given its inode. This
725** is the same as the unixLockKey except that the thread ID is omitted.
726*/
727struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000728 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000729#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000730 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000731#else
drh107886a2008-11-21 22:21:50 +0000732 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000733#endif
734};
735
736/*
737** An instance of the following structure serves as the key used
738** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000739**
drh734c9862008-11-28 15:37:20 +0000740** If threads cannot override each others locks (LinuxThreads), then we
741** set the unixLockKey.tid field to the thread ID. If threads can override
742** each others locks (Posix and NPTL) then tid is always set to zero.
743** tid is omitted if we compile without threading support or on an OS
744** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000745*/
drh6c7d5c52008-11-21 20:32:33 +0000746struct unixLockKey {
747 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000748#if SQLITE_THREADSAFE && defined(__linux__)
749 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000750#endif
drhbbd42a62004-05-22 17:41:58 +0000751};
752
753/*
754** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000755** inode. Or, on LinuxThreads, there is one of these structures for
756** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000757**
danielk1977ad94b582007-08-20 06:44:22 +0000758** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000759** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000760** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000761*/
drh6c7d5c52008-11-21 20:32:33 +0000762struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000763 struct unixLockKey lockKey; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000764 int nShared; /* Number of SHARED locks held */
765 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000766 int nRef; /* Number of pointers to this structure */
drh7ed97b92010-01-20 13:07:21 +0000767#if defined(SQLITE_ENABLE_LOCKING_STYLE)
768 unsigned long long sharedByte; /* for AFP simulated shared lock */
769#endif
drh734c9862008-11-28 15:37:20 +0000770 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
771 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000772};
773
774/*
775** An instance of the following structure is allocated for each open
776** inode. This structure keeps track of the number of locks on that
777** inode. If a close is attempted against an inode that is holding
778** locks, the close is deferred until all locks clear by adding the
779** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000780**
781** TODO: Consider changing this so that there is only a single file
782** descriptor for each open file, even when it is opened multiple times.
783** The close() system call would only occur when the last database
784** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000785*/
drh6c7d5c52008-11-21 20:32:33 +0000786struct unixOpenCnt {
787 struct unixFileId fileId; /* The lookup key */
788 int nRef; /* Number of pointers to this structure */
789 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000790 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000791#if OS_VXWORKS
792 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000793 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000794#endif
drh6c7d5c52008-11-21 20:32:33 +0000795 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000796};
797
drhda0e7682008-07-30 15:27:54 +0000798/*
drh9b35ea62008-11-29 02:20:26 +0000799** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
800** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000801** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000802** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000803*/
drh6c7d5c52008-11-21 20:32:33 +0000804static struct unixLockInfo *lockList = 0;
805static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000806
drh5fdae772004-06-29 03:29:00 +0000807/*
drh9b35ea62008-11-29 02:20:26 +0000808** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000809** locks.
810**
drh9b35ea62008-11-29 02:20:26 +0000811** 0: No. Threads cannot override each others locks. (LinuxThreads)
812** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000813** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000814**
drh5062d3a2006-01-31 23:03:35 +0000815** On some systems, we know at compile-time if threads can override each
816** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
817** will be set appropriately. On other systems, we have to check at
818** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
819** undefined.
820**
drhf1a221e2006-01-15 17:27:17 +0000821** This variable normally has file scope only. But during testing, we make
822** it a global so that the test code can change its value in order to verify
823** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000824*/
drh715ff302008-12-03 22:32:44 +0000825#if SQLITE_THREADSAFE && defined(__linux__)
826# ifndef SQLITE_THREAD_OVERRIDE_LOCK
827# define SQLITE_THREAD_OVERRIDE_LOCK -1
828# endif
829# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000830int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000831# else
drh5062d3a2006-01-31 23:03:35 +0000832static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000833# endif
drh029b44b2006-01-15 00:13:15 +0000834#endif
drh5fdae772004-06-29 03:29:00 +0000835
836/*
837** This structure holds information passed into individual test
838** threads by the testThreadLockingBehavior() routine.
839*/
840struct threadTestData {
841 int fd; /* File to be locked */
842 struct flock lock; /* The locking operation */
843 int result; /* Result of the locking operation */
844};
845
drh6c7d5c52008-11-21 20:32:33 +0000846#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000847/*
danielk197741a6a612008-11-11 18:34:35 +0000848** This function is used as the main routine for a thread launched by
849** testThreadLockingBehavior(). It tests whether the shared-lock obtained
850** by the main thread in testThreadLockingBehavior() conflicts with a
851** hypothetical write-lock obtained by this thread on the same file.
852**
853** The write-lock is not actually acquired, as this is not possible if
854** the file is open in read-only mode (see ticket #3472).
855*/
drh5fdae772004-06-29 03:29:00 +0000856static void *threadLockingTest(void *pArg){
857 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000858 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000859 return pArg;
860}
drh6c7d5c52008-11-21 20:32:33 +0000861#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000862
drh6c7d5c52008-11-21 20:32:33 +0000863
864#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000865/*
866** This procedure attempts to determine whether or not threads
867** can override each others locks then sets the
868** threadsOverrideEachOthersLocks variable appropriately.
869*/
danielk19774d5238f2006-01-27 06:32:00 +0000870static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000871 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000872 int rc;
873 struct threadTestData d;
874 struct flock l;
875 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000876
877 fd = dup(fd_orig);
878 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000879 memset(&l, 0, sizeof(l));
880 l.l_type = F_RDLCK;
881 l.l_len = 1;
882 l.l_start = 0;
883 l.l_whence = SEEK_SET;
884 rc = fcntl(fd_orig, F_SETLK, &l);
885 if( rc!=0 ) return;
886 memset(&d, 0, sizeof(d));
887 d.fd = fd;
888 d.lock = l;
889 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000890 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
891 pthread_join(t, 0);
892 }
drh5fdae772004-06-29 03:29:00 +0000893 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000894 if( d.result!=0 ) return;
895 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000896}
drh06150f92009-07-03 12:57:58 +0000897#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000898
drhbbd42a62004-05-22 17:41:58 +0000899/*
drh6c7d5c52008-11-21 20:32:33 +0000900** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000901**
902** The mutex entered using the unixEnterMutex() function must be held
903** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000904*/
905static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000906 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000907 if( pLock ){
908 pLock->nRef--;
909 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000910 if( pLock->pPrev ){
911 assert( pLock->pPrev->pNext==pLock );
912 pLock->pPrev->pNext = pLock->pNext;
913 }else{
914 assert( lockList==pLock );
915 lockList = pLock->pNext;
916 }
917 if( pLock->pNext ){
918 assert( pLock->pNext->pPrev==pLock );
919 pLock->pNext->pPrev = pLock->pPrev;
920 }
danielk1977e339d652008-06-28 11:23:00 +0000921 sqlite3_free(pLock);
922 }
drhbbd42a62004-05-22 17:41:58 +0000923 }
924}
925
926/*
drh6c7d5c52008-11-21 20:32:33 +0000927** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000928**
929** The mutex entered using the unixEnterMutex() function must be held
930** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000931*/
drh6c7d5c52008-11-21 20:32:33 +0000932static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000933 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000934 if( pOpen ){
935 pOpen->nRef--;
936 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000937 if( pOpen->pPrev ){
938 assert( pOpen->pPrev->pNext==pOpen );
939 pOpen->pPrev->pNext = pOpen->pNext;
940 }else{
941 assert( openList==pOpen );
942 openList = pOpen->pNext;
943 }
944 if( pOpen->pNext ){
945 assert( pOpen->pNext->pPrev==pOpen );
946 pOpen->pNext->pPrev = pOpen->pPrev;
947 }
drh08da4bb2009-09-10 19:20:03 +0000948#if SQLITE_THREADSAFE && defined(__linux__)
dan11b38792009-09-09 18:46:52 +0000949 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
drh08da4bb2009-09-10 19:20:03 +0000950#endif
dan11b38792009-09-09 18:46:52 +0000951
952 /* If pOpen->pUnused is not null, then memory and file-descriptors
953 ** are leaked.
954 **
955 ** This will only happen if, under Linuxthreads, the user has opened
956 ** a transaction in one thread, then attempts to close the database
957 ** handle from another thread (without first unlocking the db file).
958 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000959 sqlite3_free(pOpen);
960 }
drhbbd42a62004-05-22 17:41:58 +0000961 }
962}
963
drh6c7d5c52008-11-21 20:32:33 +0000964/*
965** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
966** describes that file descriptor. Create new ones if necessary. The
967** return values might be uninitialized if an error occurs.
968**
dan9359c7b2009-08-21 08:29:10 +0000969** The mutex entered using the unixEnterMutex() function must be held
970** when this function is called.
971**
drh6c7d5c52008-11-21 20:32:33 +0000972** Return an appropriate error code.
973*/
974static int findLockInfo(
975 unixFile *pFile, /* Unix file with file desc used in the key */
976 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
977 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
978){
979 int rc; /* System call return code */
980 int fd; /* The file descriptor for pFile */
981 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
982 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
983 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000984 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000985 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
986
dan9359c7b2009-08-21 08:29:10 +0000987 assert( unixMutexHeld() );
988
drh6c7d5c52008-11-21 20:32:33 +0000989 /* Get low-level information about the file that we can used to
990 ** create a unique name for the file.
991 */
992 fd = pFile->h;
993 rc = fstat(fd, &statbuf);
994 if( rc!=0 ){
995 pFile->lastErrno = errno;
996#ifdef EOVERFLOW
997 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
998#endif
999 return SQLITE_IOERR;
1000 }
1001
drheb0d74f2009-02-03 15:27:02 +00001002#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001003 /* On OS X on an msdos filesystem, the inode number is reported
1004 ** incorrectly for zero-size files. See ticket #3260. To work
1005 ** around this problem (we consider it a bug in OS X, not SQLite)
1006 ** we always increase the file size to 1 by writing a single byte
1007 ** prior to accessing the inode number. The one byte written is
1008 ** an ASCII 'S' character which also happens to be the first byte
1009 ** in the header of every SQLite database. In this way, if there
1010 ** is a race condition such that another thread has already populated
1011 ** the first page of the database, no damage is done.
1012 */
drh7ed97b92010-01-20 13:07:21 +00001013 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +00001014 rc = write(fd, "S", 1);
1015 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001016 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001017 return SQLITE_IOERR;
1018 }
drh6c7d5c52008-11-21 20:32:33 +00001019 rc = fstat(fd, &statbuf);
1020 if( rc!=0 ){
1021 pFile->lastErrno = errno;
1022 return SQLITE_IOERR;
1023 }
1024 }
drheb0d74f2009-02-03 15:27:02 +00001025#endif
drh6c7d5c52008-11-21 20:32:33 +00001026
1027 memset(&lockKey, 0, sizeof(lockKey));
1028 lockKey.fid.dev = statbuf.st_dev;
1029#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001030 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001031#else
1032 lockKey.fid.ino = statbuf.st_ino;
1033#endif
drh734c9862008-11-28 15:37:20 +00001034#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001035 if( threadsOverrideEachOthersLocks<0 ){
1036 testThreadLockingBehavior(fd);
1037 }
1038 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1039#endif
1040 fileId = lockKey.fid;
1041 if( ppLock!=0 ){
1042 pLock = lockList;
1043 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1044 pLock = pLock->pNext;
1045 }
1046 if( pLock==0 ){
1047 pLock = sqlite3_malloc( sizeof(*pLock) );
1048 if( pLock==0 ){
1049 rc = SQLITE_NOMEM;
1050 goto exit_findlockinfo;
1051 }
drh9b5db1d2009-10-07 23:42:25 +00001052 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
drh6c7d5c52008-11-21 20:32:33 +00001053 pLock->nRef = 1;
drh308c2a52010-05-14 11:30:18 +00001054 pLock->nShared = 0;
1055 pLock->eFileLock = 0;
drh7ed97b92010-01-20 13:07:21 +00001056#if defined(SQLITE_ENABLE_LOCKING_STYLE)
1057 pLock->sharedByte = 0;
1058#endif
drh6c7d5c52008-11-21 20:32:33 +00001059 pLock->pNext = lockList;
1060 pLock->pPrev = 0;
1061 if( lockList ) lockList->pPrev = pLock;
1062 lockList = pLock;
1063 }else{
1064 pLock->nRef++;
1065 }
1066 *ppLock = pLock;
1067 }
1068 if( ppOpen!=0 ){
1069 pOpen = openList;
1070 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1071 pOpen = pOpen->pNext;
1072 }
1073 if( pOpen==0 ){
1074 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1075 if( pOpen==0 ){
1076 releaseLockInfo(pLock);
1077 rc = SQLITE_NOMEM;
1078 goto exit_findlockinfo;
1079 }
dane946c392009-08-22 11:39:46 +00001080 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001081 pOpen->fileId = fileId;
1082 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001083 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001084 if( openList ) openList->pPrev = pOpen;
1085 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001086 }else{
1087 pOpen->nRef++;
1088 }
1089 *ppOpen = pOpen;
1090 }
1091
1092exit_findlockinfo:
1093 return rc;
1094}
drh6c7d5c52008-11-21 20:32:33 +00001095
drh7708e972008-11-29 00:56:52 +00001096/*
1097** If we are currently in a different thread than the thread that the
1098** unixFile argument belongs to, then transfer ownership of the unixFile
1099** over to the current thread.
1100**
1101** A unixFile is only owned by a thread on systems that use LinuxThreads.
1102**
1103** Ownership transfer is only allowed if the unixFile is currently unlocked.
1104** If the unixFile is locked and an ownership is wrong, then return
1105** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1106*/
1107#if SQLITE_THREADSAFE && defined(__linux__)
1108static int transferOwnership(unixFile *pFile){
1109 int rc;
1110 pthread_t hSelf;
1111 if( threadsOverrideEachOthersLocks ){
1112 /* Ownership transfers not needed on this system */
1113 return SQLITE_OK;
1114 }
1115 hSelf = pthread_self();
1116 if( pthread_equal(pFile->tid, hSelf) ){
1117 /* We are still in the same thread */
drh308c2a52010-05-14 11:30:18 +00001118 OSTRACE(("No-transfer, same thread\n"));
drh7708e972008-11-29 00:56:52 +00001119 return SQLITE_OK;
1120 }
drh308c2a52010-05-14 11:30:18 +00001121 if( pFile->eFileLock!=NO_LOCK ){
drh7708e972008-11-29 00:56:52 +00001122 /* We cannot change ownership while we are holding a lock! */
drh413c3d32010-02-23 20:11:56 +00001123 return SQLITE_MISUSE_BKPT;
drh7708e972008-11-29 00:56:52 +00001124 }
drh308c2a52010-05-14 11:30:18 +00001125 OSTRACE(("Transfer ownership of %d from %d to %d\n",
1126 pFile->h, pFile->tid, hSelf));
drh7708e972008-11-29 00:56:52 +00001127 pFile->tid = hSelf;
1128 if (pFile->pLock != NULL) {
1129 releaseLockInfo(pFile->pLock);
1130 rc = findLockInfo(pFile, &pFile->pLock, 0);
drh308c2a52010-05-14 11:30:18 +00001131 OSTRACE(("LOCK %d is now %s(%s,%d)\n", pFile->h,
1132 azFileLock(pFile->eFileLock),
1133 azFileLock(pFile->pLock->eFileLock), pFile->pLock->nShared));
drh7708e972008-11-29 00:56:52 +00001134 return rc;
1135 } else {
1136 return SQLITE_OK;
1137 }
1138}
1139#else /* if not SQLITE_THREADSAFE */
1140 /* On single-threaded builds, ownership transfer is a no-op */
1141# define transferOwnership(X) SQLITE_OK
1142#endif /* SQLITE_THREADSAFE */
1143
aswift5b1a2562008-08-22 00:22:35 +00001144
1145/*
danielk197713adf8a2004-06-03 16:08:41 +00001146** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001147** file by this or any other process. If such a lock is held, set *pResOut
1148** to a non-zero value otherwise *pResOut is set to zero. The return value
1149** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001150*/
danielk1977861f7452008-06-05 11:39:11 +00001151static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001152 int rc = SQLITE_OK;
1153 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001154 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001155
danielk1977861f7452008-06-05 11:39:11 +00001156 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1157
drh054889e2005-11-30 03:20:31 +00001158 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001159 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001160
1161 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001162 if( pFile->pLock->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001163 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001164 }
1165
drh2ac3ee92004-06-07 16:27:46 +00001166 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001167 */
danielk197709480a92009-02-09 05:32:32 +00001168#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001169 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001170 struct flock lock;
1171 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001172 lock.l_start = RESERVED_BYTE;
1173 lock.l_len = 1;
1174 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001175 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1176 int tErrno = errno;
1177 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1178 pFile->lastErrno = tErrno;
1179 } else if( lock.l_type!=F_UNLCK ){
1180 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001181 }
1182 }
danielk197709480a92009-02-09 05:32:32 +00001183#endif
danielk197713adf8a2004-06-03 16:08:41 +00001184
drh6c7d5c52008-11-21 20:32:33 +00001185 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001186 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001187
aswift5b1a2562008-08-22 00:22:35 +00001188 *pResOut = reserved;
1189 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001190}
1191
1192/*
drh308c2a52010-05-14 11:30:18 +00001193** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001194** of the following:
1195**
drh2ac3ee92004-06-07 16:27:46 +00001196** (1) SHARED_LOCK
1197** (2) RESERVED_LOCK
1198** (3) PENDING_LOCK
1199** (4) EXCLUSIVE_LOCK
1200**
drhb3e04342004-06-08 00:47:47 +00001201** Sometimes when requesting one lock state, additional lock states
1202** are inserted in between. The locking might fail on one of the later
1203** transitions leaving the lock state different from what it started but
1204** still short of its goal. The following chart shows the allowed
1205** transitions and the inserted intermediate states:
1206**
1207** UNLOCKED -> SHARED
1208** SHARED -> RESERVED
1209** SHARED -> (PENDING) -> EXCLUSIVE
1210** RESERVED -> (PENDING) -> EXCLUSIVE
1211** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001212**
drha6abd042004-06-09 17:37:22 +00001213** This routine will only increase a lock. Use the sqlite3OsUnlock()
1214** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001215*/
drh308c2a52010-05-14 11:30:18 +00001216static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001217 /* The following describes the implementation of the various locks and
1218 ** lock transitions in terms of the POSIX advisory shared and exclusive
1219 ** lock primitives (called read-locks and write-locks below, to avoid
1220 ** confusion with SQLite lock names). The algorithms are complicated
1221 ** slightly in order to be compatible with windows systems simultaneously
1222 ** accessing the same database file, in case that is ever required.
1223 **
1224 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1225 ** byte', each single bytes at well known offsets, and the 'shared byte
1226 ** range', a range of 510 bytes at a well known offset.
1227 **
1228 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1229 ** byte'. If this is successful, a random byte from the 'shared byte
1230 ** range' is read-locked and the lock on the 'pending byte' released.
1231 **
danielk197790ba3bd2004-06-25 08:32:25 +00001232 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1233 ** A RESERVED lock is implemented by grabbing a write-lock on the
1234 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001235 **
1236 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001237 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1238 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1239 ** obtained, but existing SHARED locks are allowed to persist. A process
1240 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1241 ** This property is used by the algorithm for rolling back a journal file
1242 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001243 **
danielk197790ba3bd2004-06-25 08:32:25 +00001244 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1245 ** implemented by obtaining a write-lock on the entire 'shared byte
1246 ** range'. Since all other locks require a read-lock on one of the bytes
1247 ** within this range, this ensures that no other locks are held on the
1248 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001249 **
1250 ** The reason a single byte cannot be used instead of the 'shared byte
1251 ** range' is that some versions of windows do not support read-locks. By
1252 ** locking a random byte from a range, concurrent SHARED locks may exist
1253 ** even if the locking primitive used is always a write-lock.
1254 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001255 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001256 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001257 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001258 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001259 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001260 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001261
drh054889e2005-11-30 03:20:31 +00001262 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001263 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1264 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1265 azFileLock(pLock->eFileLock), pLock->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001266
1267 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001268 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001269 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001270 */
drh308c2a52010-05-14 11:30:18 +00001271 if( pFile->eFileLock>=eFileLock ){
1272 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1273 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001274 return SQLITE_OK;
1275 }
1276
drh0c2694b2009-09-03 16:23:44 +00001277 /* Make sure the locking sequence is correct.
1278 ** (1) We never move from unlocked to anything higher than shared lock.
1279 ** (2) SQLite never explicitly requests a pendig lock.
1280 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001281 */
drh308c2a52010-05-14 11:30:18 +00001282 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1283 assert( eFileLock!=PENDING_LOCK );
1284 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001285
drh054889e2005-11-30 03:20:31 +00001286 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001287 */
drh6c7d5c52008-11-21 20:32:33 +00001288 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001289
drh029b44b2006-01-15 00:13:15 +00001290 /* Make sure the current thread owns the pFile.
1291 */
1292 rc = transferOwnership(pFile);
1293 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001294 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001295 return rc;
1296 }
drh64b1bea2006-01-15 02:30:57 +00001297 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001298
danielk1977ad94b582007-08-20 06:44:22 +00001299 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001300 ** handle that precludes the requested lock, return BUSY.
1301 */
drh308c2a52010-05-14 11:30:18 +00001302 if( (pFile->eFileLock!=pLock->eFileLock &&
1303 (pLock->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001304 ){
1305 rc = SQLITE_BUSY;
1306 goto end_lock;
1307 }
1308
1309 /* If a SHARED lock is requested, and some thread using this PID already
1310 ** has a SHARED or RESERVED lock, then increment reference counts and
1311 ** return SQLITE_OK.
1312 */
drh308c2a52010-05-14 11:30:18 +00001313 if( eFileLock==SHARED_LOCK &&
1314 (pLock->eFileLock==SHARED_LOCK || pLock->eFileLock==RESERVED_LOCK) ){
1315 assert( eFileLock==SHARED_LOCK );
1316 assert( pFile->eFileLock==0 );
1317 assert( pLock->nShared>0 );
1318 pFile->eFileLock = SHARED_LOCK;
1319 pLock->nShared++;
drh054889e2005-11-30 03:20:31 +00001320 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001321 goto end_lock;
1322 }
1323
danielk19779a1d0ab2004-06-01 14:09:28 +00001324
drh3cde3bb2004-06-12 02:17:14 +00001325 /* A PENDING lock is needed before acquiring a SHARED lock and before
1326 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1327 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001328 */
drh0c2694b2009-09-03 16:23:44 +00001329 lock.l_len = 1L;
1330 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001331 if( eFileLock==SHARED_LOCK
1332 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001333 ){
drh308c2a52010-05-14 11:30:18 +00001334 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001335 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001336 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001337 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001338 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001339 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1340 if( IS_LOCK_ERROR(rc) ){
1341 pFile->lastErrno = tErrno;
1342 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001343 goto end_lock;
1344 }
drh3cde3bb2004-06-12 02:17:14 +00001345 }
1346
1347
1348 /* If control gets to this point, then actually go ahead and make
1349 ** operating system calls for the specified lock.
1350 */
drh308c2a52010-05-14 11:30:18 +00001351 if( eFileLock==SHARED_LOCK ){
1352 assert( pLock->nShared==0 );
1353 assert( pLock->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001354
drh2ac3ee92004-06-07 16:27:46 +00001355 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001356 lock.l_start = SHARED_FIRST;
1357 lock.l_len = SHARED_SIZE;
1358 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1359 tErrno = errno;
1360 }
drh2ac3ee92004-06-07 16:27:46 +00001361 /* Drop the temporary PENDING lock */
1362 lock.l_start = PENDING_BYTE;
1363 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001364 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001365 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001366 if( s != -1 ){
1367 /* This could happen with a network mount */
1368 tErrno = errno;
1369 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1370 if( IS_LOCK_ERROR(rc) ){
1371 pFile->lastErrno = tErrno;
1372 }
1373 goto end_lock;
1374 }
drh2b4b5962005-06-15 17:47:55 +00001375 }
drhe2396a12007-03-29 20:19:58 +00001376 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001377 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1378 if( IS_LOCK_ERROR(rc) ){
1379 pFile->lastErrno = tErrno;
1380 }
drhbbd42a62004-05-22 17:41:58 +00001381 }else{
drh308c2a52010-05-14 11:30:18 +00001382 pFile->eFileLock = SHARED_LOCK;
drh054889e2005-11-30 03:20:31 +00001383 pFile->pOpen->nLock++;
drh308c2a52010-05-14 11:30:18 +00001384 pLock->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001385 }
drh308c2a52010-05-14 11:30:18 +00001386 }else if( eFileLock==EXCLUSIVE_LOCK && pLock->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001387 /* We are trying for an exclusive lock but another thread in this
1388 ** same process is still holding a shared lock. */
1389 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001390 }else{
drh3cde3bb2004-06-12 02:17:14 +00001391 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001392 ** assumed that there is a SHARED or greater lock on the file
1393 ** already.
1394 */
drh308c2a52010-05-14 11:30:18 +00001395 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001397 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001398 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001399 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001400 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001401 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001402 lock.l_start = SHARED_FIRST;
1403 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001404 break;
1405 default:
1406 assert(0);
1407 }
drh7ed97b92010-01-20 13:07:21 +00001408 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001409 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001410 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001411 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1412 if( IS_LOCK_ERROR(rc) ){
1413 pFile->lastErrno = tErrno;
1414 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001415 }
drhbbd42a62004-05-22 17:41:58 +00001416 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001417
drh8f941bc2009-01-14 23:03:40 +00001418
1419#ifndef NDEBUG
1420 /* Set up the transaction-counter change checking flags when
1421 ** transitioning from a SHARED to a RESERVED lock. The change
1422 ** from SHARED to RESERVED marks the beginning of a normal
1423 ** write operation (not a hot journal rollback).
1424 */
1425 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001426 && pFile->eFileLock<=SHARED_LOCK
1427 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001428 ){
1429 pFile->transCntrChng = 0;
1430 pFile->dbUpdate = 0;
1431 pFile->inNormalWrite = 1;
1432 }
1433#endif
1434
1435
danielk1977ecb2a962004-06-02 06:30:16 +00001436 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001437 pFile->eFileLock = eFileLock;
1438 pLock->eFileLock = eFileLock;
1439 }else if( eFileLock==EXCLUSIVE_LOCK ){
1440 pFile->eFileLock = PENDING_LOCK;
1441 pLock->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001442 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001443
1444end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001445 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001446 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1447 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001448 return rc;
1449}
1450
1451/*
dane946c392009-08-22 11:39:46 +00001452** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1453** If all such file descriptors are closed without error, the list is
1454** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001455**
1456** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001457** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001458** not deleted and SQLITE_IOERR_CLOSE returned.
1459*/
1460static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001461 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001462 struct unixOpenCnt *pOpen = pFile->pOpen;
1463 UnixUnusedFd *pError = 0;
1464 UnixUnusedFd *p;
1465 UnixUnusedFd *pNext;
1466 for(p=pOpen->pUnused; p; p=pNext){
1467 pNext = p->pNext;
1468 if( close(p->fd) ){
1469 pFile->lastErrno = errno;
1470 rc = SQLITE_IOERR_CLOSE;
1471 p->pNext = pError;
1472 pError = p;
dane946c392009-08-22 11:39:46 +00001473 }else{
1474 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001475 }
1476 }
dane946c392009-08-22 11:39:46 +00001477 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001478 return rc;
1479}
1480
1481/*
1482** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001483** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001484*/
1485static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001486 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001487 UnixUnusedFd *p = pFile->pUnused;
1488 p->pNext = pOpen->pUnused;
1489 pOpen->pUnused = p;
1490 pFile->h = -1;
1491 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001492}
1493
1494/*
drh308c2a52010-05-14 11:30:18 +00001495** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001496** must be either NO_LOCK or SHARED_LOCK.
1497**
1498** If the locking level of the file descriptor is already at or below
1499** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001500**
1501** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1502** the byte range is divided into 2 parts and the first part is unlocked then
1503** set to a read lock, then the other part is simply unlocked. This works
1504** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1505** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001506*/
drh308c2a52010-05-14 11:30:18 +00001507static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001508 unixFile *pFile = (unixFile*)id;
1509 struct unixLockInfo *pLock;
1510 struct flock lock;
1511 int rc = SQLITE_OK;
1512 int h;
drh0c2694b2009-09-03 16:23:44 +00001513 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001514
drh054889e2005-11-30 03:20:31 +00001515 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001516 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1517 pFile->eFileLock, pFile->pLock->eFileLock, pFile->pLock->nShared,
1518 getpid()));
drha6abd042004-06-09 17:37:22 +00001519
drh308c2a52010-05-14 11:30:18 +00001520 assert( eFileLock<=SHARED_LOCK );
1521 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001522 return SQLITE_OK;
1523 }
drhf1a221e2006-01-15 17:27:17 +00001524 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00001525 return SQLITE_MISUSE_BKPT;
drhf1a221e2006-01-15 17:27:17 +00001526 }
drh6c7d5c52008-11-21 20:32:33 +00001527 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001528 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001529 pLock = pFile->pLock;
drh308c2a52010-05-14 11:30:18 +00001530 assert( pLock->nShared!=0 );
1531 if( pFile->eFileLock>SHARED_LOCK ){
1532 assert( pLock->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001533 SimulateIOErrorBenign(1);
1534 SimulateIOError( h=(-1) )
1535 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001536
1537#ifndef NDEBUG
1538 /* When reducing a lock such that other processes can start
1539 ** reading the database file again, make sure that the
1540 ** transaction counter was updated if any part of the database
1541 ** file changed. If the transaction counter is not updated,
1542 ** other connections to the same file might not realize that
1543 ** the file has changed and hence might not know to flush their
1544 ** cache. The use of a stale cache can lead to database corruption.
1545 */
dan7c246102010-04-12 19:00:29 +00001546#if 0
drh8f941bc2009-01-14 23:03:40 +00001547 assert( pFile->inNormalWrite==0
1548 || pFile->dbUpdate==0
1549 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001550#endif
drh8f941bc2009-01-14 23:03:40 +00001551 pFile->inNormalWrite = 0;
1552#endif
1553
drh7ed97b92010-01-20 13:07:21 +00001554 /* downgrading to a shared lock on NFS involves clearing the write lock
1555 ** before establishing the readlock - to avoid a race condition we downgrade
1556 ** the lock in 2 blocks, so that part of the range will be covered by a
1557 ** write lock until the rest is covered by a read lock:
1558 ** 1: [WWWWW]
1559 ** 2: [....W]
1560 ** 3: [RRRRW]
1561 ** 4: [RRRR.]
1562 */
drh308c2a52010-05-14 11:30:18 +00001563 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001564 if( handleNFSUnlock ){
1565 off_t divSize = SHARED_SIZE - 1;
1566
1567 lock.l_type = F_UNLCK;
1568 lock.l_whence = SEEK_SET;
1569 lock.l_start = SHARED_FIRST;
1570 lock.l_len = divSize;
1571 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001572 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001573 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1574 if( IS_LOCK_ERROR(rc) ){
1575 pFile->lastErrno = tErrno;
1576 }
1577 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001578 }
drh7ed97b92010-01-20 13:07:21 +00001579 lock.l_type = F_RDLCK;
1580 lock.l_whence = SEEK_SET;
1581 lock.l_start = SHARED_FIRST;
1582 lock.l_len = divSize;
1583 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001584 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001585 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1586 if( IS_LOCK_ERROR(rc) ){
1587 pFile->lastErrno = tErrno;
1588 }
1589 goto end_unlock;
1590 }
1591 lock.l_type = F_UNLCK;
1592 lock.l_whence = SEEK_SET;
1593 lock.l_start = SHARED_FIRST+divSize;
1594 lock.l_len = SHARED_SIZE-divSize;
1595 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001596 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001597 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1598 if( IS_LOCK_ERROR(rc) ){
1599 pFile->lastErrno = tErrno;
1600 }
1601 goto end_unlock;
1602 }
1603 }else{
1604 lock.l_type = F_RDLCK;
1605 lock.l_whence = SEEK_SET;
1606 lock.l_start = SHARED_FIRST;
1607 lock.l_len = SHARED_SIZE;
1608 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001609 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001610 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1611 if( IS_LOCK_ERROR(rc) ){
1612 pFile->lastErrno = tErrno;
1613 }
1614 goto end_unlock;
1615 }
drh9c105bb2004-10-02 20:38:28 +00001616 }
1617 }
drhbbd42a62004-05-22 17:41:58 +00001618 lock.l_type = F_UNLCK;
1619 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001620 lock.l_start = PENDING_BYTE;
1621 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001622 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh308c2a52010-05-14 11:30:18 +00001623 pLock->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001624 }else{
drh0c2694b2009-09-03 16:23:44 +00001625 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001626 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1627 if( IS_LOCK_ERROR(rc) ){
1628 pFile->lastErrno = tErrno;
1629 }
drhcd731cf2009-03-28 23:23:02 +00001630 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001631 }
drhbbd42a62004-05-22 17:41:58 +00001632 }
drh308c2a52010-05-14 11:30:18 +00001633 if( eFileLock==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001634 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001635
drha6abd042004-06-09 17:37:22 +00001636 /* Decrement the shared lock counter. Release the lock using an
1637 ** OS call only when all threads in this same process have released
1638 ** the lock.
1639 */
drh308c2a52010-05-14 11:30:18 +00001640 pLock->nShared--;
1641 if( pLock->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001642 lock.l_type = F_UNLCK;
1643 lock.l_whence = SEEK_SET;
1644 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001645 SimulateIOErrorBenign(1);
1646 SimulateIOError( h=(-1) )
1647 SimulateIOErrorBenign(0);
1648 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh308c2a52010-05-14 11:30:18 +00001649 pLock->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001650 }else{
drh0c2694b2009-09-03 16:23:44 +00001651 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001652 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001653 if( IS_LOCK_ERROR(rc) ){
1654 pFile->lastErrno = tErrno;
1655 }
drh308c2a52010-05-14 11:30:18 +00001656 pLock->eFileLock = NO_LOCK;
1657 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001658 }
drha6abd042004-06-09 17:37:22 +00001659 }
1660
drhbbd42a62004-05-22 17:41:58 +00001661 /* Decrement the count of locks against this same file. When the
1662 ** count reaches zero, close any other file descriptors whose close
1663 ** was deferred because of outstanding locks.
1664 */
danielk197764a54c52009-03-30 07:39:35 +00001665 pOpen = pFile->pOpen;
1666 pOpen->nLock--;
1667 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001668 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001669 int rc2 = closePendingFds(pFile);
1670 if( rc==SQLITE_OK ){
1671 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001672 }
drhbbd42a62004-05-22 17:41:58 +00001673 }
1674 }
aswift5b1a2562008-08-22 00:22:35 +00001675
1676end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001677 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001678 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001679 return rc;
drhbbd42a62004-05-22 17:41:58 +00001680}
1681
1682/*
drh308c2a52010-05-14 11:30:18 +00001683** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001684** must be either NO_LOCK or SHARED_LOCK.
1685**
1686** If the locking level of the file descriptor is already at or below
1687** the requested locking level, this routine is a no-op.
1688*/
drh308c2a52010-05-14 11:30:18 +00001689static int unixUnlock(sqlite3_file *id, int eFileLock){
1690 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001691}
1692
1693/*
danielk1977e339d652008-06-28 11:23:00 +00001694** This function performs the parts of the "close file" operation
1695** common to all locking schemes. It closes the directory and file
1696** handles, if they are valid, and sets all fields of the unixFile
1697** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001698**
1699** It is *not* necessary to hold the mutex when this routine is called,
1700** even on VxWorks. A mutex will be acquired on VxWorks by the
1701** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001702*/
1703static int closeUnixFile(sqlite3_file *id){
1704 unixFile *pFile = (unixFile*)id;
1705 if( pFile ){
1706 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001707 int err = close(pFile->dirfd);
1708 if( err ){
1709 pFile->lastErrno = errno;
1710 return SQLITE_IOERR_DIR_CLOSE;
1711 }else{
1712 pFile->dirfd=-1;
1713 }
danielk1977e339d652008-06-28 11:23:00 +00001714 }
1715 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001716 int err = close(pFile->h);
1717 if( err ){
1718 pFile->lastErrno = errno;
1719 return SQLITE_IOERR_CLOSE;
1720 }
danielk1977e339d652008-06-28 11:23:00 +00001721 }
drh6c7d5c52008-11-21 20:32:33 +00001722#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001723 if( pFile->pId ){
1724 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001725 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001726 }
drh107886a2008-11-21 22:21:50 +00001727 vxworksReleaseFileId(pFile->pId);
1728 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001729 }
1730#endif
drh308c2a52010-05-14 11:30:18 +00001731 OSTRACE(("CLOSE %-3d\n", pFile->h);
danielk1977e339d652008-06-28 11:23:00 +00001732 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001733 sqlite3_free(pFile->pUnused);
drh308c2a52010-05-14 11:30:18 +00001734 memset(pFile, 0, sizeof(unixFile)));
danielk1977e339d652008-06-28 11:23:00 +00001735 }
1736 return SQLITE_OK;
1737}
1738
1739/*
danielk1977e3026632004-06-22 11:29:02 +00001740** Close a file.
1741*/
danielk197762079062007-08-15 17:08:46 +00001742static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001743 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001744 if( id ){
1745 unixFile *pFile = (unixFile *)id;
1746 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001747 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001748 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001749 /* If there are outstanding locks, do not actually close the file just
1750 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001751 ** descriptor to pOpen->pUnused list. It will be automatically closed
1752 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001753 */
dan08da86a2009-08-21 17:18:03 +00001754 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001755 }
danielk1977e339d652008-06-28 11:23:00 +00001756 releaseLockInfo(pFile->pLock);
1757 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001758 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001759 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001760 }
aswiftaebf4132008-11-21 00:10:35 +00001761 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001762}
1763
drh734c9862008-11-28 15:37:20 +00001764/************** End of the posix advisory lock implementation *****************
1765******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001766
drh734c9862008-11-28 15:37:20 +00001767/******************************************************************************
1768****************************** No-op Locking **********************************
1769**
1770** Of the various locking implementations available, this is by far the
1771** simplest: locking is ignored. No attempt is made to lock the database
1772** file for reading or writing.
1773**
1774** This locking mode is appropriate for use on read-only databases
1775** (ex: databases that are burned into CD-ROM, for example.) It can
1776** also be used if the application employs some external mechanism to
1777** prevent simultaneous access of the same database by two or more
1778** database connections. But there is a serious risk of database
1779** corruption if this locking mode is used in situations where multiple
1780** database connections are accessing the same database file at the same
1781** time and one or more of those connections are writing.
1782*/
drhbfe66312006-10-03 17:40:40 +00001783
drh734c9862008-11-28 15:37:20 +00001784static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1785 UNUSED_PARAMETER(NotUsed);
1786 *pResOut = 0;
1787 return SQLITE_OK;
1788}
drh734c9862008-11-28 15:37:20 +00001789static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1790 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1791 return SQLITE_OK;
1792}
drh734c9862008-11-28 15:37:20 +00001793static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1794 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1795 return SQLITE_OK;
1796}
1797
1798/*
drh9b35ea62008-11-29 02:20:26 +00001799** Close the file.
drh734c9862008-11-28 15:37:20 +00001800*/
1801static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001802 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001803}
1804
1805/******************* End of the no-op lock implementation *********************
1806******************************************************************************/
1807
1808/******************************************************************************
1809************************* Begin dot-file Locking ******************************
1810**
drh0c2694b2009-09-03 16:23:44 +00001811** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001812** files in order to control access to the database. This works on just
1813** about every filesystem imaginable. But there are serious downsides:
1814**
1815** (1) There is zero concurrency. A single reader blocks all other
1816** connections from reading or writing the database.
1817**
1818** (2) An application crash or power loss can leave stale lock files
1819** sitting around that need to be cleared manually.
1820**
1821** Nevertheless, a dotlock is an appropriate locking mode for use if no
1822** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001823**
1824** Dotfile locking works by creating a file in the same directory as the
1825** database and with the same name but with a ".lock" extension added.
1826** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1827** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001828*/
1829
1830/*
1831** The file suffix added to the data base filename in order to create the
1832** lock file.
1833*/
1834#define DOTLOCK_SUFFIX ".lock"
1835
drh7708e972008-11-29 00:56:52 +00001836/*
1837** This routine checks if there is a RESERVED lock held on the specified
1838** file by this or any other process. If such a lock is held, set *pResOut
1839** to a non-zero value otherwise *pResOut is set to zero. The return value
1840** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1841**
1842** In dotfile locking, either a lock exists or it does not. So in this
1843** variation of CheckReservedLock(), *pResOut is set to true if any lock
1844** is held on the file and false if the file is unlocked.
1845*/
drh734c9862008-11-28 15:37:20 +00001846static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1847 int rc = SQLITE_OK;
1848 int reserved = 0;
1849 unixFile *pFile = (unixFile*)id;
1850
1851 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1852
1853 assert( pFile );
1854
1855 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001856 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001857 /* Either this connection or some other connection in the same process
1858 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001859 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001860 }else{
1861 /* The lock is held if and only if the lockfile exists */
1862 const char *zLockFile = (const char*)pFile->lockingContext;
1863 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001864 }
drh308c2a52010-05-14 11:30:18 +00001865 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001866 *pResOut = reserved;
1867 return rc;
1868}
1869
drh7708e972008-11-29 00:56:52 +00001870/*
drh308c2a52010-05-14 11:30:18 +00001871** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001872** of the following:
1873**
1874** (1) SHARED_LOCK
1875** (2) RESERVED_LOCK
1876** (3) PENDING_LOCK
1877** (4) EXCLUSIVE_LOCK
1878**
1879** Sometimes when requesting one lock state, additional lock states
1880** are inserted in between. The locking might fail on one of the later
1881** transitions leaving the lock state different from what it started but
1882** still short of its goal. The following chart shows the allowed
1883** transitions and the inserted intermediate states:
1884**
1885** UNLOCKED -> SHARED
1886** SHARED -> RESERVED
1887** SHARED -> (PENDING) -> EXCLUSIVE
1888** RESERVED -> (PENDING) -> EXCLUSIVE
1889** PENDING -> EXCLUSIVE
1890**
1891** This routine will only increase a lock. Use the sqlite3OsUnlock()
1892** routine to lower a locking level.
1893**
1894** With dotfile locking, we really only support state (4): EXCLUSIVE.
1895** But we track the other locking levels internally.
1896*/
drh308c2a52010-05-14 11:30:18 +00001897static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001898 unixFile *pFile = (unixFile*)id;
1899 int fd;
1900 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001901 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001902
drh7708e972008-11-29 00:56:52 +00001903
1904 /* If we have any lock, then the lock file already exists. All we have
1905 ** to do is adjust our internal record of the lock level.
1906 */
drh308c2a52010-05-14 11:30:18 +00001907 if( pFile->eFileLock > NO_LOCK ){
1908 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001909#if !OS_VXWORKS
1910 /* Always update the timestamp on the old file */
1911 utimes(zLockFile, NULL);
1912#endif
drh7708e972008-11-29 00:56:52 +00001913 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001914 }
1915
1916 /* grab an exclusive lock */
1917 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1918 if( fd<0 ){
1919 /* failed to open/create the file, someone else may have stolen the lock */
1920 int tErrno = errno;
1921 if( EEXIST == tErrno ){
1922 rc = SQLITE_BUSY;
1923 } else {
1924 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1925 if( IS_LOCK_ERROR(rc) ){
1926 pFile->lastErrno = tErrno;
1927 }
1928 }
drh7708e972008-11-29 00:56:52 +00001929 return rc;
drh734c9862008-11-28 15:37:20 +00001930 }
1931 if( close(fd) ){
1932 pFile->lastErrno = errno;
1933 rc = SQLITE_IOERR_CLOSE;
1934 }
1935
1936 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001937 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001938 return rc;
1939}
1940
drh7708e972008-11-29 00:56:52 +00001941/*
drh308c2a52010-05-14 11:30:18 +00001942** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001943** must be either NO_LOCK or SHARED_LOCK.
1944**
1945** If the locking level of the file descriptor is already at or below
1946** the requested locking level, this routine is a no-op.
1947**
1948** When the locking level reaches NO_LOCK, delete the lock file.
1949*/
drh308c2a52010-05-14 11:30:18 +00001950static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001951 unixFile *pFile = (unixFile*)id;
1952 char *zLockFile = (char *)pFile->lockingContext;
1953
1954 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001955 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1956 pFile->eFileLock, getpid()));
1957 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001958
1959 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001960 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001961 return SQLITE_OK;
1962 }
drh7708e972008-11-29 00:56:52 +00001963
1964 /* To downgrade to shared, simply update our internal notion of the
1965 ** lock state. No need to mess with the file on disk.
1966 */
drh308c2a52010-05-14 11:30:18 +00001967 if( eFileLock==SHARED_LOCK ){
1968 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001969 return SQLITE_OK;
1970 }
1971
drh7708e972008-11-29 00:56:52 +00001972 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001973 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001974 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001975 int rc = 0;
1976 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001977 if( ENOENT != tErrno ){
1978 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1979 }
1980 if( IS_LOCK_ERROR(rc) ){
1981 pFile->lastErrno = tErrno;
1982 }
1983 return rc;
1984 }
drh308c2a52010-05-14 11:30:18 +00001985 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001986 return SQLITE_OK;
1987}
1988
1989/*
drh9b35ea62008-11-29 02:20:26 +00001990** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001991*/
1992static int dotlockClose(sqlite3_file *id) {
1993 int rc;
1994 if( id ){
1995 unixFile *pFile = (unixFile*)id;
1996 dotlockUnlock(id, NO_LOCK);
1997 sqlite3_free(pFile->lockingContext);
1998 }
drh734c9862008-11-28 15:37:20 +00001999 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002000 return rc;
2001}
2002/****************** End of the dot-file lock implementation *******************
2003******************************************************************************/
2004
2005/******************************************************************************
2006************************** Begin flock Locking ********************************
2007**
2008** Use the flock() system call to do file locking.
2009**
drh6b9d6dd2008-12-03 19:34:47 +00002010** flock() locking is like dot-file locking in that the various
2011** fine-grain locking levels supported by SQLite are collapsed into
2012** a single exclusive lock. In other words, SHARED, RESERVED, and
2013** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2014** still works when you do this, but concurrency is reduced since
2015** only a single process can be reading the database at a time.
2016**
drh734c9862008-11-28 15:37:20 +00002017** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2018** compiling for VXWORKS.
2019*/
2020#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002021
drh6b9d6dd2008-12-03 19:34:47 +00002022/*
2023** This routine checks if there is a RESERVED lock held on the specified
2024** file by this or any other process. If such a lock is held, set *pResOut
2025** to a non-zero value otherwise *pResOut is set to zero. The return value
2026** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2027*/
drh734c9862008-11-28 15:37:20 +00002028static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2029 int rc = SQLITE_OK;
2030 int reserved = 0;
2031 unixFile *pFile = (unixFile*)id;
2032
2033 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2034
2035 assert( pFile );
2036
2037 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002038 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002039 reserved = 1;
2040 }
2041
2042 /* Otherwise see if some other process holds it. */
2043 if( !reserved ){
2044 /* attempt to get the lock */
2045 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2046 if( !lrc ){
2047 /* got the lock, unlock it */
2048 lrc = flock(pFile->h, LOCK_UN);
2049 if ( lrc ) {
2050 int tErrno = errno;
2051 /* unlock failed with an error */
2052 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2053 if( IS_LOCK_ERROR(lrc) ){
2054 pFile->lastErrno = tErrno;
2055 rc = lrc;
2056 }
2057 }
2058 } else {
2059 int tErrno = errno;
2060 reserved = 1;
2061 /* someone else might have it reserved */
2062 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2063 if( IS_LOCK_ERROR(lrc) ){
2064 pFile->lastErrno = tErrno;
2065 rc = lrc;
2066 }
2067 }
2068 }
drh308c2a52010-05-14 11:30:18 +00002069 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002070
2071#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2072 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2073 rc = SQLITE_OK;
2074 reserved=1;
2075 }
2076#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2077 *pResOut = reserved;
2078 return rc;
2079}
2080
drh6b9d6dd2008-12-03 19:34:47 +00002081/*
drh308c2a52010-05-14 11:30:18 +00002082** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002083** of the following:
2084**
2085** (1) SHARED_LOCK
2086** (2) RESERVED_LOCK
2087** (3) PENDING_LOCK
2088** (4) EXCLUSIVE_LOCK
2089**
2090** Sometimes when requesting one lock state, additional lock states
2091** are inserted in between. The locking might fail on one of the later
2092** transitions leaving the lock state different from what it started but
2093** still short of its goal. The following chart shows the allowed
2094** transitions and the inserted intermediate states:
2095**
2096** UNLOCKED -> SHARED
2097** SHARED -> RESERVED
2098** SHARED -> (PENDING) -> EXCLUSIVE
2099** RESERVED -> (PENDING) -> EXCLUSIVE
2100** PENDING -> EXCLUSIVE
2101**
2102** flock() only really support EXCLUSIVE locks. We track intermediate
2103** lock states in the sqlite3_file structure, but all locks SHARED or
2104** above are really EXCLUSIVE locks and exclude all other processes from
2105** access the file.
2106**
2107** This routine will only increase a lock. Use the sqlite3OsUnlock()
2108** routine to lower a locking level.
2109*/
drh308c2a52010-05-14 11:30:18 +00002110static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002111 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002112 unixFile *pFile = (unixFile*)id;
2113
2114 assert( pFile );
2115
2116 /* if we already have a lock, it is exclusive.
2117 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002118 if (pFile->eFileLock > NO_LOCK) {
2119 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002120 return SQLITE_OK;
2121 }
2122
2123 /* grab an exclusive lock */
2124
2125 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2126 int tErrno = errno;
2127 /* didn't get, must be busy */
2128 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2129 if( IS_LOCK_ERROR(rc) ){
2130 pFile->lastErrno = tErrno;
2131 }
2132 } else {
2133 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002134 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002135 }
drh308c2a52010-05-14 11:30:18 +00002136 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2137 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002138#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2139 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2140 rc = SQLITE_BUSY;
2141 }
2142#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2143 return rc;
2144}
2145
drh6b9d6dd2008-12-03 19:34:47 +00002146
2147/*
drh308c2a52010-05-14 11:30:18 +00002148** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002149** must be either NO_LOCK or SHARED_LOCK.
2150**
2151** If the locking level of the file descriptor is already at or below
2152** the requested locking level, this routine is a no-op.
2153*/
drh308c2a52010-05-14 11:30:18 +00002154static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002155 unixFile *pFile = (unixFile*)id;
2156
2157 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002158 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2159 pFile->eFileLock, getpid()));
2160 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002161
2162 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002163 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002164 return SQLITE_OK;
2165 }
2166
2167 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002168 if (eFileLock==SHARED_LOCK) {
2169 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002170 return SQLITE_OK;
2171 }
2172
2173 /* no, really, unlock. */
2174 int rc = flock(pFile->h, LOCK_UN);
2175 if (rc) {
2176 int r, tErrno = errno;
2177 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2178 if( IS_LOCK_ERROR(r) ){
2179 pFile->lastErrno = tErrno;
2180 }
2181#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2182 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2183 r = SQLITE_BUSY;
2184 }
2185#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2186
2187 return r;
2188 } else {
drh308c2a52010-05-14 11:30:18 +00002189 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002190 return SQLITE_OK;
2191 }
2192}
2193
2194/*
2195** Close a file.
2196*/
2197static int flockClose(sqlite3_file *id) {
2198 if( id ){
2199 flockUnlock(id, NO_LOCK);
2200 }
2201 return closeUnixFile(id);
2202}
2203
2204#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2205
2206/******************* End of the flock lock implementation *********************
2207******************************************************************************/
2208
2209/******************************************************************************
2210************************ Begin Named Semaphore Locking ************************
2211**
2212** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002213**
2214** Semaphore locking is like dot-lock and flock in that it really only
2215** supports EXCLUSIVE locking. Only a single process can read or write
2216** the database file at a time. This reduces potential concurrency, but
2217** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002218*/
2219#if OS_VXWORKS
2220
drh6b9d6dd2008-12-03 19:34:47 +00002221/*
2222** This routine checks if there is a RESERVED lock held on the specified
2223** file by this or any other process. If such a lock is held, set *pResOut
2224** to a non-zero value otherwise *pResOut is set to zero. The return value
2225** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2226*/
drh734c9862008-11-28 15:37:20 +00002227static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2228 int rc = SQLITE_OK;
2229 int reserved = 0;
2230 unixFile *pFile = (unixFile*)id;
2231
2232 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2233
2234 assert( pFile );
2235
2236 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002237 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002238 reserved = 1;
2239 }
2240
2241 /* Otherwise see if some other process holds it. */
2242 if( !reserved ){
2243 sem_t *pSem = pFile->pOpen->pSem;
2244 struct stat statBuf;
2245
2246 if( sem_trywait(pSem)==-1 ){
2247 int tErrno = errno;
2248 if( EAGAIN != tErrno ){
2249 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2250 pFile->lastErrno = tErrno;
2251 } else {
2252 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002253 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002254 }
2255 }else{
2256 /* we could have it if we want it */
2257 sem_post(pSem);
2258 }
2259 }
drh308c2a52010-05-14 11:30:18 +00002260 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002261
2262 *pResOut = reserved;
2263 return rc;
2264}
2265
drh6b9d6dd2008-12-03 19:34:47 +00002266/*
drh308c2a52010-05-14 11:30:18 +00002267** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002268** of the following:
2269**
2270** (1) SHARED_LOCK
2271** (2) RESERVED_LOCK
2272** (3) PENDING_LOCK
2273** (4) EXCLUSIVE_LOCK
2274**
2275** Sometimes when requesting one lock state, additional lock states
2276** are inserted in between. The locking might fail on one of the later
2277** transitions leaving the lock state different from what it started but
2278** still short of its goal. The following chart shows the allowed
2279** transitions and the inserted intermediate states:
2280**
2281** UNLOCKED -> SHARED
2282** SHARED -> RESERVED
2283** SHARED -> (PENDING) -> EXCLUSIVE
2284** RESERVED -> (PENDING) -> EXCLUSIVE
2285** PENDING -> EXCLUSIVE
2286**
2287** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2288** lock states in the sqlite3_file structure, but all locks SHARED or
2289** above are really EXCLUSIVE locks and exclude all other processes from
2290** access the file.
2291**
2292** This routine will only increase a lock. Use the sqlite3OsUnlock()
2293** routine to lower a locking level.
2294*/
drh308c2a52010-05-14 11:30:18 +00002295static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002296 unixFile *pFile = (unixFile*)id;
2297 int fd;
2298 sem_t *pSem = pFile->pOpen->pSem;
2299 int rc = SQLITE_OK;
2300
2301 /* if we already have a lock, it is exclusive.
2302 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002303 if (pFile->eFileLock > NO_LOCK) {
2304 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002305 rc = SQLITE_OK;
2306 goto sem_end_lock;
2307 }
2308
2309 /* lock semaphore now but bail out when already locked. */
2310 if( sem_trywait(pSem)==-1 ){
2311 rc = SQLITE_BUSY;
2312 goto sem_end_lock;
2313 }
2314
2315 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002316 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002317
2318 sem_end_lock:
2319 return rc;
2320}
2321
drh6b9d6dd2008-12-03 19:34:47 +00002322/*
drh308c2a52010-05-14 11:30:18 +00002323** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002324** must be either NO_LOCK or SHARED_LOCK.
2325**
2326** If the locking level of the file descriptor is already at or below
2327** the requested locking level, this routine is a no-op.
2328*/
drh308c2a52010-05-14 11:30:18 +00002329static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002330 unixFile *pFile = (unixFile*)id;
2331 sem_t *pSem = pFile->pOpen->pSem;
2332
2333 assert( pFile );
2334 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002335 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2336 pFile->eFileLock, getpid()));
2337 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002338
2339 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002340 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002341 return SQLITE_OK;
2342 }
2343
2344 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002345 if (eFileLock==SHARED_LOCK) {
2346 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002347 return SQLITE_OK;
2348 }
2349
2350 /* no, really unlock. */
2351 if ( sem_post(pSem)==-1 ) {
2352 int rc, tErrno = errno;
2353 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2354 if( IS_LOCK_ERROR(rc) ){
2355 pFile->lastErrno = tErrno;
2356 }
2357 return rc;
2358 }
drh308c2a52010-05-14 11:30:18 +00002359 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002360 return SQLITE_OK;
2361}
2362
2363/*
2364 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002365 */
drh734c9862008-11-28 15:37:20 +00002366static int semClose(sqlite3_file *id) {
2367 if( id ){
2368 unixFile *pFile = (unixFile*)id;
2369 semUnlock(id, NO_LOCK);
2370 assert( pFile );
2371 unixEnterMutex();
2372 releaseLockInfo(pFile->pLock);
2373 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002374 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002375 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002376 }
2377 return SQLITE_OK;
2378}
2379
2380#endif /* OS_VXWORKS */
2381/*
2382** Named semaphore locking is only available on VxWorks.
2383**
2384*************** End of the named semaphore lock implementation ****************
2385******************************************************************************/
2386
2387
2388/******************************************************************************
2389*************************** Begin AFP Locking *********************************
2390**
2391** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2392** on Apple Macintosh computers - both OS9 and OSX.
2393**
2394** Third-party implementations of AFP are available. But this code here
2395** only works on OSX.
2396*/
2397
drhd2cb50b2009-01-09 21:41:17 +00002398#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002399/*
2400** The afpLockingContext structure contains all afp lock specific state
2401*/
drhbfe66312006-10-03 17:40:40 +00002402typedef struct afpLockingContext afpLockingContext;
2403struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002404 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002405 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002406};
2407
2408struct ByteRangeLockPB2
2409{
2410 unsigned long long offset; /* offset to first byte to lock */
2411 unsigned long long length; /* nbr of bytes to lock */
2412 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2413 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2414 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2415 int fd; /* file desc to assoc this lock with */
2416};
2417
drhfd131da2007-08-07 17:13:03 +00002418#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002419
drh6b9d6dd2008-12-03 19:34:47 +00002420/*
2421** This is a utility for setting or clearing a bit-range lock on an
2422** AFP filesystem.
2423**
2424** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2425*/
2426static int afpSetLock(
2427 const char *path, /* Name of the file to be locked or unlocked */
2428 unixFile *pFile, /* Open file descriptor on path */
2429 unsigned long long offset, /* First byte to be locked */
2430 unsigned long long length, /* Number of bytes to lock */
2431 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002432){
drh6b9d6dd2008-12-03 19:34:47 +00002433 struct ByteRangeLockPB2 pb;
2434 int err;
drhbfe66312006-10-03 17:40:40 +00002435
2436 pb.unLockFlag = setLockFlag ? 0 : 1;
2437 pb.startEndFlag = 0;
2438 pb.offset = offset;
2439 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002440 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002441
drh308c2a52010-05-14 11:30:18 +00002442 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002443 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002444 offset, length));
drhbfe66312006-10-03 17:40:40 +00002445 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2446 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002447 int rc;
2448 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002449 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2450 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002451#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2452 rc = SQLITE_BUSY;
2453#else
drh734c9862008-11-28 15:37:20 +00002454 rc = sqliteErrorFromPosixError(tErrno,
2455 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002456#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002457 if( IS_LOCK_ERROR(rc) ){
2458 pFile->lastErrno = tErrno;
2459 }
2460 return rc;
drhbfe66312006-10-03 17:40:40 +00002461 } else {
aswift5b1a2562008-08-22 00:22:35 +00002462 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002463 }
2464}
2465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
2467** This routine checks if there is a RESERVED lock held on the specified
2468** file by this or any other process. If such a lock is held, set *pResOut
2469** to a non-zero value otherwise *pResOut is set to zero. The return value
2470** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2471*/
danielk1977e339d652008-06-28 11:23:00 +00002472static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002473 int rc = SQLITE_OK;
2474 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002475 unixFile *pFile = (unixFile*)id;
2476
aswift5b1a2562008-08-22 00:22:35 +00002477 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2478
2479 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002480 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002481 if( context->reserved ){
2482 *pResOut = 1;
2483 return SQLITE_OK;
2484 }
2485 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002486
2487 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002488 if( pFile->pLock->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002489 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002490 }
2491
2492 /* Otherwise see if some other process holds it.
2493 */
aswift5b1a2562008-08-22 00:22:35 +00002494 if( !reserved ){
2495 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002496 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002497 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002498 /* if we succeeded in taking the reserved lock, unlock it to restore
2499 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002500 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002501 } else {
2502 /* if we failed to get the lock then someone else must have it */
2503 reserved = 1;
2504 }
2505 if( IS_LOCK_ERROR(lrc) ){
2506 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002507 }
2508 }
drhbfe66312006-10-03 17:40:40 +00002509
drh7ed97b92010-01-20 13:07:21 +00002510 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002511 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002512
2513 *pResOut = reserved;
2514 return rc;
drhbfe66312006-10-03 17:40:40 +00002515}
2516
drh6b9d6dd2008-12-03 19:34:47 +00002517/*
drh308c2a52010-05-14 11:30:18 +00002518** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002519** of the following:
2520**
2521** (1) SHARED_LOCK
2522** (2) RESERVED_LOCK
2523** (3) PENDING_LOCK
2524** (4) EXCLUSIVE_LOCK
2525**
2526** Sometimes when requesting one lock state, additional lock states
2527** are inserted in between. The locking might fail on one of the later
2528** transitions leaving the lock state different from what it started but
2529** still short of its goal. The following chart shows the allowed
2530** transitions and the inserted intermediate states:
2531**
2532** UNLOCKED -> SHARED
2533** SHARED -> RESERVED
2534** SHARED -> (PENDING) -> EXCLUSIVE
2535** RESERVED -> (PENDING) -> EXCLUSIVE
2536** PENDING -> EXCLUSIVE
2537**
2538** This routine will only increase a lock. Use the sqlite3OsUnlock()
2539** routine to lower a locking level.
2540*/
drh308c2a52010-05-14 11:30:18 +00002541static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002542 int rc = SQLITE_OK;
2543 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002544 struct unixLockInfo *pLock = pFile->pLock;
drhbfe66312006-10-03 17:40:40 +00002545 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002546
2547 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002548 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2549 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2550 azFileLock(pLock->eFileLock), pLock->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002551
drhbfe66312006-10-03 17:40:40 +00002552 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002553 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002554 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002555 */
drh308c2a52010-05-14 11:30:18 +00002556 if( pFile->eFileLock>=eFileLock ){
2557 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2558 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002559 return SQLITE_OK;
2560 }
2561
2562 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002563 ** (1) We never move from unlocked to anything higher than shared lock.
2564 ** (2) SQLite never explicitly requests a pendig lock.
2565 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002566 */
drh308c2a52010-05-14 11:30:18 +00002567 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2568 assert( eFileLock!=PENDING_LOCK );
2569 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002570
2571 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002572 */
drh6c7d5c52008-11-21 20:32:33 +00002573 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002574
2575 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002576 */
drhbfe66312006-10-03 17:40:40 +00002577 rc = transferOwnership(pFile);
2578 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002579 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002580 return rc;
2581 }
drh7ed97b92010-01-20 13:07:21 +00002582 pLock = pFile->pLock;
2583
2584 /* If some thread using this PID has a lock via a different unixFile*
2585 ** handle that precludes the requested lock, return BUSY.
2586 */
drh308c2a52010-05-14 11:30:18 +00002587 if( (pFile->eFileLock!=pLock->eFileLock &&
2588 (pLock->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002589 ){
2590 rc = SQLITE_BUSY;
2591 goto afp_end_lock;
2592 }
2593
2594 /* If a SHARED lock is requested, and some thread using this PID already
2595 ** has a SHARED or RESERVED lock, then increment reference counts and
2596 ** return SQLITE_OK.
2597 */
drh308c2a52010-05-14 11:30:18 +00002598 if( eFileLock==SHARED_LOCK &&
2599 (pLock->eFileLock==SHARED_LOCK || pLock->eFileLock==RESERVED_LOCK) ){
2600 assert( eFileLock==SHARED_LOCK );
2601 assert( pFile->eFileLock==0 );
2602 assert( pLock->nShared>0 );
2603 pFile->eFileLock = SHARED_LOCK;
2604 pLock->nShared++;
drh7ed97b92010-01-20 13:07:21 +00002605 pFile->pOpen->nLock++;
2606 goto afp_end_lock;
2607 }
drhbfe66312006-10-03 17:40:40 +00002608
2609 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002610 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2611 ** be released.
2612 */
drh308c2a52010-05-14 11:30:18 +00002613 if( eFileLock==SHARED_LOCK
2614 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002615 ){
2616 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002617 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002618 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002619 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002620 goto afp_end_lock;
2621 }
2622 }
2623
2624 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002625 ** operating system calls for the specified lock.
2626 */
drh308c2a52010-05-14 11:30:18 +00002627 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002628 int lrc1, lrc2, lrc1Errno;
2629 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002630
drh308c2a52010-05-14 11:30:18 +00002631 assert( pLock->nShared==0 );
2632 assert( pLock->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002633
2634 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002635 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002636 /* note that the quality of the randomness doesn't matter that much */
2637 lk = random();
drh7ed97b92010-01-20 13:07:21 +00002638 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002639 lrc1 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002640 SHARED_FIRST+pLock->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002641 if( IS_LOCK_ERROR(lrc1) ){
2642 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002643 }
aswift5b1a2562008-08-22 00:22:35 +00002644 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002645 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002646
aswift5b1a2562008-08-22 00:22:35 +00002647 if( IS_LOCK_ERROR(lrc1) ) {
2648 pFile->lastErrno = lrc1Errno;
2649 rc = lrc1;
2650 goto afp_end_lock;
2651 } else if( IS_LOCK_ERROR(lrc2) ){
2652 rc = lrc2;
2653 goto afp_end_lock;
2654 } else if( lrc1 != SQLITE_OK ) {
2655 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002656 } else {
drh308c2a52010-05-14 11:30:18 +00002657 pFile->eFileLock = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002658 pFile->pOpen->nLock++;
drh308c2a52010-05-14 11:30:18 +00002659 pLock->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002660 }
drh308c2a52010-05-14 11:30:18 +00002661 }else if( eFileLock==EXCLUSIVE_LOCK && pLock->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002662 /* We are trying for an exclusive lock but another thread in this
2663 ** same process is still holding a shared lock. */
2664 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002665 }else{
2666 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2667 ** assumed that there is a SHARED or greater lock on the file
2668 ** already.
2669 */
2670 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002671 assert( 0!=pFile->eFileLock );
2672 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002673 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002674 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002675 if( !failed ){
2676 context->reserved = 1;
2677 }
drhbfe66312006-10-03 17:40:40 +00002678 }
drh308c2a52010-05-14 11:30:18 +00002679 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002680 /* Acquire an EXCLUSIVE lock */
2681
2682 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002683 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002684 */
drh6b9d6dd2008-12-03 19:34:47 +00002685 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh7ed97b92010-01-20 13:07:21 +00002686 pLock->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002687 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002688 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002689 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002690 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002691 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002692 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002693 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2694 ** a critical I/O error
2695 */
2696 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2697 SQLITE_IOERR_LOCK;
2698 goto afp_end_lock;
2699 }
2700 }else{
aswift5b1a2562008-08-22 00:22:35 +00002701 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002702 }
2703 }
aswift5b1a2562008-08-22 00:22:35 +00002704 if( failed ){
2705 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002706 }
2707 }
2708
2709 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002710 pFile->eFileLock = eFileLock;
2711 pLock->eFileLock = eFileLock;
2712 }else if( eFileLock==EXCLUSIVE_LOCK ){
2713 pFile->eFileLock = PENDING_LOCK;
2714 pLock->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002715 }
2716
2717afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002718 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002719 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2720 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002721 return rc;
2722}
2723
2724/*
drh308c2a52010-05-14 11:30:18 +00002725** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002726** must be either NO_LOCK or SHARED_LOCK.
2727**
2728** If the locking level of the file descriptor is already at or below
2729** the requested locking level, this routine is a no-op.
2730*/
drh308c2a52010-05-14 11:30:18 +00002731static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002732 int rc = SQLITE_OK;
2733 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002734 struct unixLockInfo *pLock;
2735 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2736 int skipShared = 0;
2737#ifdef SQLITE_TEST
2738 int h = pFile->h;
2739#endif
drhbfe66312006-10-03 17:40:40 +00002740
2741 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002742 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
2743 pFile->eFileLock, pFile->pLock->eFileLock, pFile->pLock->nShared,
2744 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002745
drh308c2a52010-05-14 11:30:18 +00002746 assert( eFileLock<=SHARED_LOCK );
2747 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002748 return SQLITE_OK;
2749 }
2750 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00002751 return SQLITE_MISUSE_BKPT;
drhbfe66312006-10-03 17:40:40 +00002752 }
drh6c7d5c52008-11-21 20:32:33 +00002753 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00002754 pLock = pFile->pLock;
drh308c2a52010-05-14 11:30:18 +00002755 assert( pLock->nShared!=0 );
2756 if( pFile->eFileLock>SHARED_LOCK ){
2757 assert( pLock->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002758 SimulateIOErrorBenign(1);
2759 SimulateIOError( h=(-1) )
2760 SimulateIOErrorBenign(0);
2761
2762#ifndef NDEBUG
2763 /* When reducing a lock such that other processes can start
2764 ** reading the database file again, make sure that the
2765 ** transaction counter was updated if any part of the database
2766 ** file changed. If the transaction counter is not updated,
2767 ** other connections to the same file might not realize that
2768 ** the file has changed and hence might not know to flush their
2769 ** cache. The use of a stale cache can lead to database corruption.
2770 */
2771 assert( pFile->inNormalWrite==0
2772 || pFile->dbUpdate==0
2773 || pFile->transCntrChng==1 );
2774 pFile->inNormalWrite = 0;
2775#endif
aswiftaebf4132008-11-21 00:10:35 +00002776
drh308c2a52010-05-14 11:30:18 +00002777 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002778 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh308c2a52010-05-14 11:30:18 +00002779 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pLock->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002780 /* only re-establish the shared lock if necessary */
drh7ed97b92010-01-20 13:07:21 +00002781 int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2782 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2783 } else {
2784 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002785 }
2786 }
drh308c2a52010-05-14 11:30:18 +00002787 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002788 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002789 }
drh308c2a52010-05-14 11:30:18 +00002790 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002791 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2792 if( !rc ){
2793 context->reserved = 0;
2794 }
aswiftaebf4132008-11-21 00:10:35 +00002795 }
drh308c2a52010-05-14 11:30:18 +00002796 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pLock->nShared>1)){
2797 pLock->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002798 }
aswiftaebf4132008-11-21 00:10:35 +00002799 }
drh308c2a52010-05-14 11:30:18 +00002800 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002801
drh7ed97b92010-01-20 13:07:21 +00002802 /* Decrement the shared lock counter. Release the lock using an
2803 ** OS call only when all threads in this same process have released
2804 ** the lock.
2805 */
2806 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
drh308c2a52010-05-14 11:30:18 +00002807 pLock->nShared--;
2808 if( pLock->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002809 SimulateIOErrorBenign(1);
2810 SimulateIOError( h=(-1) )
2811 SimulateIOErrorBenign(0);
2812 if( !skipShared ){
2813 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2814 }
2815 if( !rc ){
drh308c2a52010-05-14 11:30:18 +00002816 pLock->eFileLock = NO_LOCK;
2817 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002818 }
2819 }
2820 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002821 struct unixOpenCnt *pOpen = pFile->pOpen;
drh7ed97b92010-01-20 13:07:21 +00002822
aswiftaebf4132008-11-21 00:10:35 +00002823 pOpen->nLock--;
2824 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002825 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002826 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002827 }
2828 }
drhbfe66312006-10-03 17:40:40 +00002829 }
drh7ed97b92010-01-20 13:07:21 +00002830
drh6c7d5c52008-11-21 20:32:33 +00002831 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002832 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002833 return rc;
2834}
2835
2836/*
drh339eb0b2008-03-07 15:34:11 +00002837** Close a file & cleanup AFP specific locking context
2838*/
danielk1977e339d652008-06-28 11:23:00 +00002839static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002840 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002841 if( id ){
2842 unixFile *pFile = (unixFile*)id;
2843 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002844 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002845 if( pFile->pOpen && pFile->pOpen->nLock ){
2846 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002847 ** yet because that would clear those locks. Instead, add the file
2848 ** descriptor to pOpen->aPending. It will be automatically closed when
2849 ** the last lock is cleared.
2850 */
dan08da86a2009-08-21 17:18:03 +00002851 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002852 }
drh7ed97b92010-01-20 13:07:21 +00002853 releaseLockInfo(pFile->pLock);
aswiftaebf4132008-11-21 00:10:35 +00002854 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002855 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002856 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002857 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002858 }
drh7ed97b92010-01-20 13:07:21 +00002859 return rc;
drhbfe66312006-10-03 17:40:40 +00002860}
2861
drhd2cb50b2009-01-09 21:41:17 +00002862#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002863/*
2864** The code above is the AFP lock implementation. The code is specific
2865** to MacOSX and does not work on other unix platforms. No alternative
2866** is available. If you don't compile for a mac, then the "unix-afp"
2867** VFS is not available.
2868**
2869********************* End of the AFP lock implementation **********************
2870******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002871
drh7ed97b92010-01-20 13:07:21 +00002872/******************************************************************************
2873*************************** Begin NFS Locking ********************************/
2874
2875#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2876/*
drh308c2a52010-05-14 11:30:18 +00002877 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002878 ** must be either NO_LOCK or SHARED_LOCK.
2879 **
2880 ** If the locking level of the file descriptor is already at or below
2881 ** the requested locking level, this routine is a no-op.
2882 */
drh308c2a52010-05-14 11:30:18 +00002883static int nfsUnlock(sqlite3_file *id, int eFileLock){
2884 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002885}
2886
2887#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2888/*
2889** The code above is the NFS lock implementation. The code is specific
2890** to MacOSX and does not work on other unix platforms. No alternative
2891** is available.
2892**
2893********************* End of the NFS lock implementation **********************
2894******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002895
2896/******************************************************************************
2897**************** Non-locking sqlite3_file methods *****************************
2898**
2899** The next division contains implementations for all methods of the
2900** sqlite3_file object other than the locking methods. The locking
2901** methods were defined in divisions above (one locking method per
2902** division). Those methods that are common to all locking modes
2903** are gather together into this division.
2904*/
drhbfe66312006-10-03 17:40:40 +00002905
2906/*
drh734c9862008-11-28 15:37:20 +00002907** Seek to the offset passed as the second argument, then read cnt
2908** bytes into pBuf. Return the number of bytes actually read.
2909**
2910** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2911** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2912** one system to another. Since SQLite does not define USE_PREAD
2913** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2914** See tickets #2741 and #2681.
2915**
2916** To avoid stomping the errno value on a failed read the lastErrno value
2917** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002918*/
drh734c9862008-11-28 15:37:20 +00002919static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2920 int got;
drh7ed97b92010-01-20 13:07:21 +00002921#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002922 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002923#endif
drh734c9862008-11-28 15:37:20 +00002924 TIMER_START;
2925#if defined(USE_PREAD)
2926 got = pread(id->h, pBuf, cnt, offset);
2927 SimulateIOError( got = -1 );
2928#elif defined(USE_PREAD64)
2929 got = pread64(id->h, pBuf, cnt, offset);
2930 SimulateIOError( got = -1 );
2931#else
2932 newOffset = lseek(id->h, offset, SEEK_SET);
2933 SimulateIOError( newOffset-- );
2934 if( newOffset!=offset ){
2935 if( newOffset == -1 ){
2936 ((unixFile*)id)->lastErrno = errno;
2937 }else{
2938 ((unixFile*)id)->lastErrno = 0;
2939 }
2940 return -1;
2941 }
2942 got = read(id->h, pBuf, cnt);
2943#endif
2944 TIMER_END;
2945 if( got<0 ){
2946 ((unixFile*)id)->lastErrno = errno;
2947 }
drh308c2a52010-05-14 11:30:18 +00002948 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002949 return got;
drhbfe66312006-10-03 17:40:40 +00002950}
2951
2952/*
drh734c9862008-11-28 15:37:20 +00002953** Read data from a file into a buffer. Return SQLITE_OK if all
2954** bytes were read successfully and SQLITE_IOERR if anything goes
2955** wrong.
drh339eb0b2008-03-07 15:34:11 +00002956*/
drh734c9862008-11-28 15:37:20 +00002957static int unixRead(
2958 sqlite3_file *id,
2959 void *pBuf,
2960 int amt,
2961 sqlite3_int64 offset
2962){
dan08da86a2009-08-21 17:18:03 +00002963 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002964 int got;
2965 assert( id );
drh08c6d442009-02-09 17:34:07 +00002966
dan08da86a2009-08-21 17:18:03 +00002967 /* If this is a database file (not a journal, master-journal or temp
2968 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002969#if 0
dane946c392009-08-22 11:39:46 +00002970 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002971 || offset>=PENDING_BYTE+512
2972 || offset+amt<=PENDING_BYTE
2973 );
dan7c246102010-04-12 19:00:29 +00002974#endif
drh08c6d442009-02-09 17:34:07 +00002975
dan08da86a2009-08-21 17:18:03 +00002976 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002977 if( got==amt ){
2978 return SQLITE_OK;
2979 }else if( got<0 ){
2980 /* lastErrno set by seekAndRead */
2981 return SQLITE_IOERR_READ;
2982 }else{
dan08da86a2009-08-21 17:18:03 +00002983 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002984 /* Unread parts of the buffer must be zero-filled */
2985 memset(&((char*)pBuf)[got], 0, amt-got);
2986 return SQLITE_IOERR_SHORT_READ;
2987 }
2988}
2989
2990/*
2991** Seek to the offset in id->offset then read cnt bytes into pBuf.
2992** Return the number of bytes actually read. Update the offset.
2993**
2994** To avoid stomping the errno value on a failed write the lastErrno value
2995** is set before returning.
2996*/
2997static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2998 int got;
drh7ed97b92010-01-20 13:07:21 +00002999#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003000 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003001#endif
drh734c9862008-11-28 15:37:20 +00003002 TIMER_START;
3003#if defined(USE_PREAD)
3004 got = pwrite(id->h, pBuf, cnt, offset);
3005#elif defined(USE_PREAD64)
3006 got = pwrite64(id->h, pBuf, cnt, offset);
3007#else
3008 newOffset = lseek(id->h, offset, SEEK_SET);
3009 if( newOffset!=offset ){
3010 if( newOffset == -1 ){
3011 ((unixFile*)id)->lastErrno = errno;
3012 }else{
3013 ((unixFile*)id)->lastErrno = 0;
3014 }
3015 return -1;
3016 }
3017 got = write(id->h, pBuf, cnt);
3018#endif
3019 TIMER_END;
3020 if( got<0 ){
3021 ((unixFile*)id)->lastErrno = errno;
3022 }
3023
drh308c2a52010-05-14 11:30:18 +00003024 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003025 return got;
3026}
3027
3028
3029/*
3030** Write data from a buffer into a file. Return SQLITE_OK on success
3031** or some other error code on failure.
3032*/
3033static int unixWrite(
3034 sqlite3_file *id,
3035 const void *pBuf,
3036 int amt,
3037 sqlite3_int64 offset
3038){
dan08da86a2009-08-21 17:18:03 +00003039 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003040 int wrote = 0;
3041 assert( id );
3042 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003043
dan08da86a2009-08-21 17:18:03 +00003044 /* If this is a database file (not a journal, master-journal or temp
3045 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003046#if 0
dane946c392009-08-22 11:39:46 +00003047 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003048 || offset>=PENDING_BYTE+512
3049 || offset+amt<=PENDING_BYTE
3050 );
dan7c246102010-04-12 19:00:29 +00003051#endif
drh08c6d442009-02-09 17:34:07 +00003052
drh8f941bc2009-01-14 23:03:40 +00003053#ifndef NDEBUG
3054 /* If we are doing a normal write to a database file (as opposed to
3055 ** doing a hot-journal rollback or a write to some file other than a
3056 ** normal database file) then record the fact that the database
3057 ** has changed. If the transaction counter is modified, record that
3058 ** fact too.
3059 */
dan08da86a2009-08-21 17:18:03 +00003060 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003061 pFile->dbUpdate = 1; /* The database has been modified */
3062 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003063 int rc;
drh8f941bc2009-01-14 23:03:40 +00003064 char oldCntr[4];
3065 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003066 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003067 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003068 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003069 pFile->transCntrChng = 1; /* The transaction counter has changed */
3070 }
3071 }
3072 }
3073#endif
3074
dan08da86a2009-08-21 17:18:03 +00003075 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003076 amt -= wrote;
3077 offset += wrote;
3078 pBuf = &((char*)pBuf)[wrote];
3079 }
3080 SimulateIOError(( wrote=(-1), amt=1 ));
3081 SimulateDiskfullError(( wrote=0, amt=1 ));
3082 if( amt>0 ){
3083 if( wrote<0 ){
3084 /* lastErrno set by seekAndWrite */
3085 return SQLITE_IOERR_WRITE;
3086 }else{
dan08da86a2009-08-21 17:18:03 +00003087 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003088 return SQLITE_FULL;
3089 }
3090 }
3091 return SQLITE_OK;
3092}
3093
3094#ifdef SQLITE_TEST
3095/*
3096** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003097** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003098*/
3099int sqlite3_sync_count = 0;
3100int sqlite3_fullsync_count = 0;
3101#endif
3102
3103/*
drh89240432009-03-25 01:06:01 +00003104** We do not trust systems to provide a working fdatasync(). Some do.
3105** Others do no. To be safe, we will stick with the (slower) fsync().
3106** If you know that your system does support fdatasync() correctly,
3107** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003108*/
drh89240432009-03-25 01:06:01 +00003109#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003110# define fdatasync fsync
3111#endif
3112
3113/*
3114** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3115** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3116** only available on Mac OS X. But that could change.
3117*/
3118#ifdef F_FULLFSYNC
3119# define HAVE_FULLFSYNC 1
3120#else
3121# define HAVE_FULLFSYNC 0
3122#endif
3123
3124
3125/*
3126** The fsync() system call does not work as advertised on many
3127** unix systems. The following procedure is an attempt to make
3128** it work better.
3129**
3130** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3131** for testing when we want to run through the test suite quickly.
3132** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3133** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3134** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003135**
3136** SQLite sets the dataOnly flag if the size of the file is unchanged.
3137** The idea behind dataOnly is that it should only write the file content
3138** to disk, not the inode. We only set dataOnly if the file size is
3139** unchanged since the file size is part of the inode. However,
3140** Ted Ts'o tells us that fdatasync() will also write the inode if the
3141** file size has changed. The only real difference between fdatasync()
3142** and fsync(), Ted tells us, is that fdatasync() will not flush the
3143** inode if the mtime or owner or other inode attributes have changed.
3144** We only care about the file size, not the other file attributes, so
3145** as far as SQLite is concerned, an fdatasync() is always adequate.
3146** So, we always use fdatasync() if it is available, regardless of
3147** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003148*/
3149static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003150 int rc;
drh734c9862008-11-28 15:37:20 +00003151
3152 /* The following "ifdef/elif/else/" block has the same structure as
3153 ** the one below. It is replicated here solely to avoid cluttering
3154 ** up the real code with the UNUSED_PARAMETER() macros.
3155 */
3156#ifdef SQLITE_NO_SYNC
3157 UNUSED_PARAMETER(fd);
3158 UNUSED_PARAMETER(fullSync);
3159 UNUSED_PARAMETER(dataOnly);
3160#elif HAVE_FULLFSYNC
3161 UNUSED_PARAMETER(dataOnly);
3162#else
3163 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003164 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003165#endif
3166
3167 /* Record the number of times that we do a normal fsync() and
3168 ** FULLSYNC. This is used during testing to verify that this procedure
3169 ** gets called with the correct arguments.
3170 */
3171#ifdef SQLITE_TEST
3172 if( fullSync ) sqlite3_fullsync_count++;
3173 sqlite3_sync_count++;
3174#endif
3175
3176 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3177 ** no-op
3178 */
3179#ifdef SQLITE_NO_SYNC
3180 rc = SQLITE_OK;
3181#elif HAVE_FULLFSYNC
3182 if( fullSync ){
3183 rc = fcntl(fd, F_FULLFSYNC, 0);
3184 }else{
3185 rc = 1;
3186 }
3187 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003188 ** It shouldn't be possible for fullfsync to fail on the local
3189 ** file system (on OSX), so failure indicates that FULLFSYNC
3190 ** isn't supported for this file system. So, attempt an fsync
3191 ** and (for now) ignore the overhead of a superfluous fcntl call.
3192 ** It'd be better to detect fullfsync support once and avoid
3193 ** the fcntl call every time sync is called.
3194 */
drh734c9862008-11-28 15:37:20 +00003195 if( rc ) rc = fsync(fd);
3196
drh7ed97b92010-01-20 13:07:21 +00003197#elif defined(__APPLE__)
3198 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3199 ** so currently we default to the macro that redefines fdatasync to fsync
3200 */
3201 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003202#else
drh0b647ff2009-03-21 14:41:04 +00003203 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003204#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003205 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003206 rc = fsync(fd);
3207 }
drh0b647ff2009-03-21 14:41:04 +00003208#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003209#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3210
3211 if( OS_VXWORKS && rc!= -1 ){
3212 rc = 0;
3213 }
chw97185482008-11-17 08:05:31 +00003214 return rc;
drhbfe66312006-10-03 17:40:40 +00003215}
3216
drh734c9862008-11-28 15:37:20 +00003217/*
3218** Make sure all writes to a particular file are committed to disk.
3219**
3220** If dataOnly==0 then both the file itself and its metadata (file
3221** size, access time, etc) are synced. If dataOnly!=0 then only the
3222** file data is synced.
3223**
3224** Under Unix, also make sure that the directory entry for the file
3225** has been created by fsync-ing the directory that contains the file.
3226** If we do not do this and we encounter a power failure, the directory
3227** entry for the journal might not exist after we reboot. The next
3228** SQLite to access the file will not know that the journal exists (because
3229** the directory entry for the journal was never created) and the transaction
3230** will not roll back - possibly leading to database corruption.
3231*/
3232static int unixSync(sqlite3_file *id, int flags){
3233 int rc;
3234 unixFile *pFile = (unixFile*)id;
3235
3236 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3237 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3238
3239 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3240 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3241 || (flags&0x0F)==SQLITE_SYNC_FULL
3242 );
3243
3244 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3245 ** line is to test that doing so does not cause any problems.
3246 */
3247 SimulateDiskfullError( return SQLITE_FULL );
3248
3249 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003250 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003251 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3252 SimulateIOError( rc=1 );
3253 if( rc ){
3254 pFile->lastErrno = errno;
3255 return SQLITE_IOERR_FSYNC;
3256 }
3257 if( pFile->dirfd>=0 ){
3258 int err;
drh308c2a52010-05-14 11:30:18 +00003259 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3260 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003261#ifndef SQLITE_DISABLE_DIRSYNC
3262 /* The directory sync is only attempted if full_fsync is
3263 ** turned off or unavailable. If a full_fsync occurred above,
3264 ** then the directory sync is superfluous.
3265 */
3266 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3267 /*
3268 ** We have received multiple reports of fsync() returning
3269 ** errors when applied to directories on certain file systems.
3270 ** A failed directory sync is not a big deal. So it seems
3271 ** better to ignore the error. Ticket #1657
3272 */
3273 /* pFile->lastErrno = errno; */
3274 /* return SQLITE_IOERR; */
3275 }
3276#endif
3277 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3278 if( err==0 ){ /* directory when we are done */
3279 pFile->dirfd = -1;
3280 }else{
3281 pFile->lastErrno = errno;
3282 rc = SQLITE_IOERR_DIR_CLOSE;
3283 }
3284 }
3285 return rc;
3286}
3287
3288/*
3289** Truncate an open file to a specified size
3290*/
3291static int unixTruncate(sqlite3_file *id, i64 nByte){
3292 int rc;
3293 assert( id );
3294 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3295 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3296 if( rc ){
3297 ((unixFile*)id)->lastErrno = errno;
3298 return SQLITE_IOERR_TRUNCATE;
3299 }else{
drh3313b142009-11-06 04:13:18 +00003300#ifndef NDEBUG
3301 /* If we are doing a normal write to a database file (as opposed to
3302 ** doing a hot-journal rollback or a write to some file other than a
3303 ** normal database file) and we truncate the file to zero length,
3304 ** that effectively updates the change counter. This might happen
3305 ** when restoring a database using the backup API from a zero-length
3306 ** source.
3307 */
3308 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3309 ((unixFile*)id)->transCntrChng = 1;
3310 }
3311#endif
3312
drh734c9862008-11-28 15:37:20 +00003313 return SQLITE_OK;
3314 }
3315}
3316
3317/*
3318** Determine the current size of a file in bytes
3319*/
3320static int unixFileSize(sqlite3_file *id, i64 *pSize){
3321 int rc;
3322 struct stat buf;
3323 assert( id );
3324 rc = fstat(((unixFile*)id)->h, &buf);
3325 SimulateIOError( rc=1 );
3326 if( rc!=0 ){
3327 ((unixFile*)id)->lastErrno = errno;
3328 return SQLITE_IOERR_FSTAT;
3329 }
3330 *pSize = buf.st_size;
3331
3332 /* When opening a zero-size database, the findLockInfo() procedure
3333 ** writes a single byte into that file in order to work around a bug
3334 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3335 ** layers, we need to report this file size as zero even though it is
3336 ** really 1. Ticket #3260.
3337 */
3338 if( *pSize==1 ) *pSize = 0;
3339
3340
3341 return SQLITE_OK;
3342}
3343
drhd2cb50b2009-01-09 21:41:17 +00003344#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003345/*
3346** Handler for proxy-locking file-control verbs. Defined below in the
3347** proxying locking division.
3348*/
3349static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003350#endif
drh715ff302008-12-03 22:32:44 +00003351
danielk1977ad94b582007-08-20 06:44:22 +00003352
danielk1977e3026632004-06-22 11:29:02 +00003353/*
drh9e33c2c2007-08-31 18:34:59 +00003354** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003355*/
drhcc6bb3e2007-08-31 16:11:35 +00003356static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003357 switch( op ){
3358 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003359 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003360 return SQLITE_OK;
3361 }
drh7708e972008-11-29 00:56:52 +00003362 case SQLITE_LAST_ERRNO: {
3363 *(int*)pArg = ((unixFile*)id)->lastErrno;
3364 return SQLITE_OK;
3365 }
drh8f941bc2009-01-14 23:03:40 +00003366#ifndef NDEBUG
3367 /* The pager calls this method to signal that it has done
3368 ** a rollback and that the database is therefore unchanged and
3369 ** it hence it is OK for the transaction change counter to be
3370 ** unchanged.
3371 */
3372 case SQLITE_FCNTL_DB_UNCHANGED: {
3373 ((unixFile*)id)->dbUpdate = 0;
3374 return SQLITE_OK;
3375 }
3376#endif
drhd2cb50b2009-01-09 21:41:17 +00003377#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003378 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003379 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003380 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003381 }
drhd2cb50b2009-01-09 21:41:17 +00003382#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003383 }
drhcc6bb3e2007-08-31 16:11:35 +00003384 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003385}
3386
3387/*
danielk1977a3d4c882007-03-23 10:08:38 +00003388** Return the sector size in bytes of the underlying block device for
3389** the specified file. This is almost always 512 bytes, but may be
3390** larger for some devices.
3391**
3392** SQLite code assumes this function cannot fail. It also assumes that
3393** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003394** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003395** same for both.
3396*/
danielk1977397d65f2008-11-19 11:35:39 +00003397static int unixSectorSize(sqlite3_file *NotUsed){
3398 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003399 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003400}
3401
danielk197790949c22007-08-17 16:50:38 +00003402/*
danielk1977397d65f2008-11-19 11:35:39 +00003403** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003404*/
danielk1977397d65f2008-11-19 11:35:39 +00003405static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3406 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003407 return 0;
3408}
3409
drhd9e5c4f2010-05-12 18:01:39 +00003410#ifndef SQLITE_OMIT_WAL
3411
3412
3413/*
3414** Object used to represent a single file opened and mmapped to provide
3415** shared memory. When multiple threads all reference the same
3416** log-summary, each thread has its own unixFile object, but they all
3417** point to a single instance of this object. In other words, each
3418** log-summary is opened only once per process.
3419**
3420** unixMutexHeld() must be true when creating or destroying
3421** this object or while reading or writing the following fields:
3422**
3423** nRef
3424** pNext
3425**
3426** The following fields are read-only after the object is created:
3427**
3428** fid
3429** zFilename
3430**
3431** Either unixShmFile.mutex must be held or unixShmFile.nRef==0 and
3432** unixMutexHeld() is true when reading or writing any other field
3433** in this structure.
3434**
3435** To avoid deadlocks, mutex and mutexBuf are always released in the
3436** reverse order that they are acquired. mutexBuf is always acquired
3437** first and released last. This invariant is check by asserting
3438** sqlite3_mutex_notheld() on mutex whenever mutexBuf is acquired or
3439** released.
3440*/
3441struct unixShmFile {
3442 struct unixFileId fid; /* Unique file identifier */
3443 sqlite3_mutex *mutex; /* Mutex to access this object */
3444 sqlite3_mutex *mutexBuf; /* Mutex to access zBuf[] */
3445 char *zFilename; /* Name of the mmapped file */
3446 int h; /* Open file descriptor */
3447 int szMap; /* Size of the mapping of file into memory */
3448 char *pMMapBuf; /* Where currently mmapped(). NULL if unmapped */
3449 int nRef; /* Number of unixShm objects pointing to this */
3450 unixShm *pFirst; /* All unixShm objects pointing to this */
3451 unixShmFile *pNext; /* Next in list of all unixShmFile objects */
3452#ifdef SQLITE_DEBUG
3453 u8 exclMask; /* Mask of exclusive locks held */
3454 u8 sharedMask; /* Mask of shared locks held */
3455 u8 nextShmId; /* Next available unixShm.id value */
3456#endif
3457};
3458
3459/*
3460** A global array of all unixShmFile objects.
3461**
3462** The unixMutexHeld() must be true while reading or writing this list.
3463*/
3464static unixShmFile *unixShmFileList = 0;
3465
3466/*
3467** Structure used internally by this VFS to record the state of an
3468** open shared memory connection.
3469**
3470** unixShm.pFile->mutex must be held while reading or writing the
3471** unixShm.pNext and unixShm.locks[] elements.
3472**
3473** The unixShm.pFile element is initialized when the object is created
3474** and is read-only thereafter.
3475*/
3476struct unixShm {
3477 unixShmFile *pFile; /* The underlying unixShmFile object */
3478 unixShm *pNext; /* Next unixShm with the same unixShmFile */
3479 u8 lockState; /* Current lock state */
3480 u8 hasMutex; /* True if holding the unixShmFile mutex */
3481 u8 hasMutexBuf; /* True if holding pFile->mutexBuf */
3482 u8 sharedMask; /* Mask of shared locks held */
3483 u8 exclMask; /* Mask of exclusive locks held */
3484#ifdef SQLITE_DEBUG
3485 u8 id; /* Id of this connection with its unixShmFile */
3486#endif
3487};
3488
3489/*
3490** Size increment by which shared memory grows
3491*/
3492#define SQLITE_UNIX_SHM_INCR 4096
3493
3494/*
3495** Constants used for locking
3496*/
3497#define UNIX_SHM_BASE 32 /* Byte offset of the first lock byte */
3498#define UNIX_SHM_DMS 0x01 /* Mask for Dead-Man-Switch lock */
3499#define UNIX_SHM_A 0x10 /* Mask for region locks... */
3500#define UNIX_SHM_B 0x20
3501#define UNIX_SHM_C 0x40
3502#define UNIX_SHM_D 0x80
3503
3504#ifdef SQLITE_DEBUG
3505/*
3506** Return a pointer to a nul-terminated string in static memory that
3507** describes a locking mask. The string is of the form "MSABCD" with
3508** each character representing a lock. "M" for MUTEX, "S" for DMS,
3509** and "A" through "D" for the region locks. If a lock is held, the
3510** letter is shown. If the lock is not held, the letter is converted
3511** to ".".
3512**
3513** This routine is for debugging purposes only and does not appear
3514** in a production build.
3515*/
3516static const char *unixShmLockString(u8 mask){
3517 static char zBuf[48];
3518 static int iBuf = 0;
3519 char *z;
3520
3521 z = &zBuf[iBuf];
3522 iBuf += 8;
3523 if( iBuf>=sizeof(zBuf) ) iBuf = 0;
3524
3525 z[0] = (mask & UNIX_SHM_DMS) ? 'S' : '.';
3526 z[1] = (mask & UNIX_SHM_A) ? 'A' : '.';
3527 z[2] = (mask & UNIX_SHM_B) ? 'B' : '.';
3528 z[3] = (mask & UNIX_SHM_C) ? 'C' : '.';
3529 z[4] = (mask & UNIX_SHM_D) ? 'D' : '.';
3530 z[5] = 0;
3531 return z;
3532}
3533#endif /* SQLITE_DEBUG */
3534
3535/*
3536** Apply posix advisory locks for all bytes identified in lockMask.
3537**
3538** lockMask might contain multiple bits but all bits are guaranteed
3539** to be contiguous.
3540**
3541** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3542** otherwise.
3543*/
3544static int unixShmSystemLock(
3545 unixShmFile *pFile, /* Apply locks to this open shared-memory segment */
3546 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
3547 u8 lockMask /* Which bytes to lock or unlock */
3548){
3549 struct flock f; /* The posix advisory locking structure */
3550 int lockOp; /* The opcode for fcntl() */
3551 int i; /* Offset into the locking byte range */
3552 int rc; /* Result code form fcntl() */
3553 u8 mask; /* Mask of bits in lockMask */
3554
3555 /* Access to the unixShmFile object is serialized by the caller */
3556 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
3557
3558 /* Initialize the locking parameters */
3559 memset(&f, 0, sizeof(f));
3560 f.l_type = lockType;
3561 f.l_whence = SEEK_SET;
3562 if( lockMask==UNIX_SHM_C && lockType!=F_UNLCK ){
3563 lockOp = F_SETLKW;
3564 OSTRACE(("SHM-LOCK requesting blocking lock\n"));
3565 }else{
3566 lockOp = F_SETLK;
3567 }
3568
3569 /* Find the first bit in lockMask that is set */
3570 for(i=0, mask=0x01; mask!=0 && (lockMask&mask)==0; mask <<= 1, i++){}
3571 assert( mask!=0 );
3572 f.l_start = i+UNIX_SHM_BASE;
3573 f.l_len = 1;
3574
3575 /* Extend the locking range for each additional bit that is set */
3576 mask <<= 1;
3577 while( mask!=0 && (lockMask & mask)!=0 ){
3578 f.l_len++;
3579 mask <<= 1;
3580 }
3581
3582 /* Verify that all bits set in lockMask are contiguous */
3583 assert( mask==0 || (lockMask & ~(mask | (mask-1)))==0 );
3584
3585 /* Acquire the system-level lock */
3586 rc = fcntl(pFile->h, lockOp, &f);
3587 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3588
3589 /* Update the global lock state and do debug tracing */
3590#ifdef SQLITE_DEBUG
3591 OSTRACE(("SHM-LOCK "));
3592 if( rc==SQLITE_OK ){
3593 if( lockType==F_UNLCK ){
3594 OSTRACE(("unlock ok"));
3595 pFile->exclMask &= ~lockMask;
3596 pFile->sharedMask &= ~lockMask;
3597 }else if( lockType==F_RDLCK ){
3598 OSTRACE(("read-lock ok"));
3599 pFile->exclMask &= ~lockMask;
3600 pFile->sharedMask |= lockMask;
3601 }else{
3602 assert( lockType==F_WRLCK );
3603 OSTRACE(("write-lock ok"));
3604 pFile->exclMask |= lockMask;
3605 pFile->sharedMask &= ~lockMask;
3606 }
3607 }else{
3608 if( lockType==F_UNLCK ){
3609 OSTRACE(("unlock failed"));
3610 }else if( lockType==F_RDLCK ){
3611 OSTRACE(("read-lock failed"));
3612 }else{
3613 assert( lockType==F_WRLCK );
3614 OSTRACE(("write-lock failed"));
3615 }
3616 }
3617 OSTRACE((" - change requested %s - afterwards %s:%s\n",
3618 unixShmLockString(lockMask),
3619 unixShmLockString(pFile->sharedMask),
3620 unixShmLockString(pFile->exclMask)));
3621#endif
3622
3623 return rc;
3624}
3625
3626/*
3627** For connection p, unlock all of the locks identified by the unlockMask
3628** parameter.
3629*/
3630static int unixShmUnlock(
3631 unixShmFile *pFile, /* The underlying shared-memory file */
3632 unixShm *p, /* The connection to be unlocked */
3633 u8 unlockMask /* Mask of locks to be unlocked */
3634){
3635 int rc; /* Result code */
3636 unixShm *pX; /* For looping over all sibling connections */
3637 u8 allMask; /* Union of locks held by connections other than "p" */
3638
3639 /* Access to the unixShmFile object is serialized by the caller */
3640 assert( sqlite3_mutex_held(pFile->mutex) );
3641
3642 /* Compute locks held by sibling connections */
3643 allMask = 0;
3644 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3645 if( pX==p ) continue;
3646 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3647 allMask |= pX->sharedMask;
3648 }
3649
3650 /* Unlock the system-level locks */
3651 if( (unlockMask & allMask)!=unlockMask ){
3652 rc = unixShmSystemLock(pFile, F_UNLCK, unlockMask & ~allMask);
3653 }else{
3654 rc = SQLITE_OK;
3655 }
3656
3657 /* Undo the local locks */
3658 if( rc==SQLITE_OK ){
3659 p->exclMask &= ~unlockMask;
3660 p->sharedMask &= ~unlockMask;
3661 }
3662 return rc;
3663}
3664
3665/*
3666** Get reader locks for connection p on all locks in the readMask parameter.
3667*/
3668static int unixShmSharedLock(
3669 unixShmFile *pFile, /* The underlying shared-memory file */
3670 unixShm *p, /* The connection to get the shared locks */
3671 u8 readMask /* Mask of shared locks to be acquired */
3672){
3673 int rc; /* Result code */
3674 unixShm *pX; /* For looping over all sibling connections */
3675 u8 allShared; /* Union of locks held by connections other than "p" */
3676
3677 /* Access to the unixShmFile object is serialized by the caller */
3678 assert( sqlite3_mutex_held(pFile->mutex) );
3679
3680 /* Find out which shared locks are already held by sibling connections.
3681 ** If any sibling already holds an exclusive lock, go ahead and return
3682 ** SQLITE_BUSY.
3683 */
3684 allShared = 0;
3685 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3686 if( pX==p ) continue;
3687 if( (pX->exclMask & readMask)!=0 ) return SQLITE_BUSY;
3688 allShared |= pX->sharedMask;
3689 }
3690
3691 /* Get shared locks at the system level, if necessary */
3692 if( (~allShared) & readMask ){
3693 rc = unixShmSystemLock(pFile, F_RDLCK, readMask);
3694 }else{
3695 rc = SQLITE_OK;
3696 }
3697
3698 /* Get the local shared locks */
3699 if( rc==SQLITE_OK ){
3700 p->sharedMask |= readMask;
3701 }
3702 return rc;
3703}
3704
3705/*
3706** For connection p, get an exclusive lock on all locks identified in
3707** the writeMask parameter.
3708*/
3709static int unixShmExclusiveLock(
3710 unixShmFile *pFile, /* The underlying shared-memory file */
3711 unixShm *p, /* The connection to get the exclusive locks */
3712 u8 writeMask /* Mask of exclusive locks to be acquired */
3713){
3714 int rc; /* Result code */
3715 unixShm *pX; /* For looping over all sibling connections */
3716
3717 /* Access to the unixShmFile object is serialized by the caller */
3718 assert( sqlite3_mutex_held(pFile->mutex) );
3719
3720 /* Make sure no sibling connections hold locks that will block this
3721 ** lock. If any do, return SQLITE_BUSY right away.
3722 */
3723 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3724 if( pX==p ) continue;
3725 if( (pX->exclMask & writeMask)!=0 ) return SQLITE_BUSY;
3726 if( (pX->sharedMask & writeMask)!=0 ) return SQLITE_BUSY;
3727 }
3728
3729 /* Get the exclusive locks at the system level. Then if successful
3730 ** also mark the local connection as being locked.
3731 */
3732 rc = unixShmSystemLock(pFile, F_WRLCK, writeMask);
3733 if( rc==SQLITE_OK ){
3734 p->sharedMask &= ~writeMask;
3735 p->exclMask |= writeMask;
3736 }
3737 return rc;
3738}
3739
3740/*
3741** Purge the unixShmFileList list of all entries with unixShmFile.nRef==0.
3742**
3743** This is not a VFS shared-memory method; it is a utility function called
3744** by VFS shared-memory methods.
3745*/
3746static void unixShmPurge(void){
3747 unixShmFile **pp;
3748 unixShmFile *p;
3749 assert( unixMutexHeld() );
3750 pp = &unixShmFileList;
3751 while( (p = *pp)!=0 ){
3752 if( p->nRef==0 ){
3753 if( p->mutex ) sqlite3_mutex_free(p->mutex);
3754 if( p->mutexBuf ) sqlite3_mutex_free(p->mutexBuf);
3755 if( p->h>=0 ) close(p->h);
3756 *pp = p->pNext;
3757 sqlite3_free(p);
3758 }else{
3759 pp = &p->pNext;
3760 }
3761 }
3762}
3763
3764/*
3765** Open a shared-memory area. This particular implementation uses
3766** mmapped files.
3767**
3768** zName is a filename used to identify the shared-memory area. The
3769** implementation does not (and perhaps should not) use this name
3770** directly, but rather use it as a template for finding an appropriate
3771** name for the shared-memory storage. In this implementation, the
3772** string "-index" is appended to zName and used as the name of the
3773** mmapped file.
3774**
3775** When opening a new shared-memory file, if no other instances of that
3776** file are currently open, in this process or in other processes, then
3777** the file must be truncated to zero length or have its header cleared.
3778*/
3779static int unixShmOpen(
3780 sqlite3_file *fd /* The file descriptor of the associated database */
3781){
3782 struct unixShm *p = 0; /* The connection to be opened */
3783 struct unixShmFile *pFile = 0; /* The underlying mmapped file */
3784 int rc; /* Result code */
3785 struct unixFileId fid; /* Unix file identifier */
3786 struct unixShmFile *pNew; /* Newly allocated pFile */
3787 struct stat sStat; /* Result from stat() an fstat() */
3788 struct unixFile *pDbFd; /* Underlying database file */
3789 int nPath; /* Size of pDbFd->zPath in bytes */
3790
3791 /* Allocate space for the new sqlite3_shm object. Also speculatively
3792 ** allocate space for a new unixShmFile and filename.
3793 */
3794 p = sqlite3_malloc( sizeof(*p) );
3795 if( p==0 ) return SQLITE_NOMEM;
3796 memset(p, 0, sizeof(*p));
3797 pDbFd = (struct unixFile*)fd;
3798 assert( pDbFd->pShm==0 );
3799 nPath = strlen(pDbFd->zPath);
3800 pNew = sqlite3_malloc( sizeof(*pFile) + nPath + 15 );
3801 if( pNew==0 ){
3802 sqlite3_free(p);
3803 return SQLITE_NOMEM;
3804 }
3805 memset(pNew, 0, sizeof(*pNew));
3806 pNew->zFilename = (char*)&pNew[1];
3807 sqlite3_snprintf(nPath+15, pNew->zFilename, "%s-wal-index", pDbFd->zPath);
3808
3809 /* Look to see if there is an existing unixShmFile that can be used.
3810 ** If no matching unixShmFile currently exists, create a new one.
3811 */
3812 unixEnterMutex();
3813 rc = stat(pNew->zFilename, &sStat);
3814 if( rc==0 ){
3815 memset(&fid, 0, sizeof(fid));
3816 fid.dev = sStat.st_dev;
3817 fid.ino = sStat.st_ino;
3818 for(pFile = unixShmFileList; pFile; pFile=pFile->pNext){
3819 if( memcmp(&pFile->fid, &fid, sizeof(fid))==0 ) break;
3820 }
3821 }
3822 if( pFile ){
3823 sqlite3_free(pNew);
3824 }else{
3825 pFile = pNew;
3826 pNew = 0;
3827 pFile->h = -1;
3828 pFile->pNext = unixShmFileList;
3829 unixShmFileList = pFile;
3830
3831 pFile->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3832 if( pFile->mutex==0 ){
3833 rc = SQLITE_NOMEM;
3834 goto shm_open_err;
3835 }
3836 pFile->mutexBuf = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3837 if( pFile->mutexBuf==0 ){
3838 rc = SQLITE_NOMEM;
3839 goto shm_open_err;
3840 }
3841
3842 pFile->h = open(pFile->zFilename, O_RDWR|O_CREAT, 0664);
3843 if( pFile->h<0 ){
3844 rc = SQLITE_CANTOPEN_BKPT;
3845 goto shm_open_err;
3846 }
3847
3848 rc = fstat(pFile->h, &sStat);
3849 if( rc ){
3850 rc = SQLITE_CANTOPEN_BKPT;
3851 goto shm_open_err;
3852 }
3853 pFile->fid.dev = sStat.st_dev;
3854 pFile->fid.ino = sStat.st_ino;
3855
3856 /* Check to see if another process is holding the dead-man switch.
3857 ** If not, truncate the file to zero length.
3858 */
3859 if( unixShmSystemLock(pFile, F_WRLCK, UNIX_SHM_DMS)==SQLITE_OK ){
3860 if( ftruncate(pFile->h, 0) ){
3861 rc = SQLITE_IOERR;
3862 }
3863 }
3864 if( rc==SQLITE_OK ){
3865 rc = unixShmSystemLock(pFile, F_RDLCK, UNIX_SHM_DMS);
3866 }
3867 if( rc ) goto shm_open_err;
3868 }
3869
3870 /* Make the new connection a child of the unixShmFile */
3871 p->pFile = pFile;
3872 p->pNext = pFile->pFirst;
3873#ifdef SQLITE_DEBUG
3874 p->id = pFile->nextShmId++;
3875#endif
3876 pFile->pFirst = p;
3877 pFile->nRef++;
3878 pDbFd->pShm = p;
3879 unixLeaveMutex();
3880 return SQLITE_OK;
3881
3882 /* Jump here on any error */
3883shm_open_err:
3884 unixShmPurge(); /* This call frees pFile if required */
3885 sqlite3_free(p);
3886 sqlite3_free(pNew);
3887 unixLeaveMutex();
3888 return rc;
3889}
3890
3891/*
3892** Close a connection to shared-memory. Delete the underlying
3893** storage if deleteFlag is true.
3894*/
3895static int unixShmClose(
3896 sqlite3_file *fd, /* The underlying database file */
3897 int deleteFlag /* Delete shared-memory if true */
3898){
3899 unixShm *p; /* The connection to be closed */
3900 unixShmFile *pFile; /* The underlying shared-memory file */
3901 unixShm **pp; /* For looping over sibling connections */
3902 unixFile *pDbFd; /* The underlying database file */
3903
3904 pDbFd = (unixFile*)fd;
3905 p = pDbFd->pShm;
3906 if( p==0 ) return SQLITE_OK;
3907 pFile = p->pFile;
3908
3909 /* Verify that the connection being closed holds no locks */
3910 assert( p->exclMask==0 );
3911 assert( p->sharedMask==0 );
3912
3913 /* Remove connection p from the set of connections associated with pFile */
3914 sqlite3_mutex_enter(pFile->mutex);
3915 for(pp=&pFile->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3916 *pp = p->pNext;
3917
3918 /* Free the connection p */
3919 sqlite3_free(p);
3920 pDbFd->pShm = 0;
3921 sqlite3_mutex_leave(pFile->mutex);
3922
3923 /* If pFile->nRef has reached 0, then close the underlying
3924 ** shared-memory file, too */
3925 unixEnterMutex();
3926 assert( pFile->nRef>0 );
3927 pFile->nRef--;
3928 if( pFile->nRef==0 ){
3929 if( deleteFlag ) unlink(pFile->zFilename);
3930 unixShmPurge();
3931 }
3932 unixLeaveMutex();
3933
3934 return SQLITE_OK;
3935}
3936
3937/*
3938** Query and/or changes the size of the underlying storage for
3939** a shared-memory segment. The reqSize parameter is the new size
3940** of the underlying storage, or -1 to do just a query. The size
3941** of the underlying storage (after resizing if resizing occurs) is
3942** written into pNewSize.
3943**
3944** This routine does not (necessarily) change the size of the mapping
3945** of the underlying storage into memory. Use xShmGet() to change
3946** the mapping size.
3947**
3948** The reqSize parameter is the minimum size requested. The implementation
3949** is free to expand the storage to some larger amount if it chooses.
3950*/
3951static int unixShmSize(
3952 sqlite3_file *fd, /* The open database file holding SHM */
3953 int reqSize, /* Requested size. -1 for query only */
3954 int *pNewSize /* Write new size here */
3955){
3956 unixFile *pDbFd = (unixFile*)fd;
3957 unixShm *p = pDbFd->pShm;
3958 unixShmFile *pFile = p->pFile;
3959 int rc = SQLITE_OK;
3960 struct stat sStat;
3961
drha925fd22010-05-13 08:33:35 +00003962 /* On a query, this loop runs once. When reqSize>=0, the loop potentially
3963 ** runs twice, except if the actual size is already greater than or equal
3964 ** to the requested size, reqSize is set to -1 on the first iteration and
3965 ** the loop only runs once.
3966 */
3967 while( 1 ){
3968 if( fstat(pFile->h, &sStat)==0 ){
3969 *pNewSize = (int)sStat.st_size;
3970 if( reqSize>=0 && reqSize<=(int)sStat.st_size ) break;
3971 }else{
3972 *pNewSize = 0;
3973 rc = SQLITE_IOERR;
3974 break;
3975 }
3976 if( reqSize<0 ) break;
drhd9e5c4f2010-05-12 18:01:39 +00003977 reqSize = (reqSize + SQLITE_UNIX_SHM_INCR - 1)/SQLITE_UNIX_SHM_INCR;
3978 reqSize *= SQLITE_UNIX_SHM_INCR;
3979 rc = ftruncate(pFile->h, reqSize);
drha925fd22010-05-13 08:33:35 +00003980 reqSize = -1;
drhd9e5c4f2010-05-12 18:01:39 +00003981 }
3982 return rc;
3983}
3984
3985
3986/*
3987** Map the shared storage into memory. The minimum size of the
3988** mapping should be reqMapSize if reqMapSize is positive. If
3989** reqMapSize is zero or negative, the implementation can choose
3990** whatever mapping size is convenient.
3991**
3992** *ppBuf is made to point to the memory which is a mapping of the
3993** underlying storage. A mutex is acquired to prevent other threads
3994** from running while *ppBuf is in use in order to prevent other threads
3995** remapping *ppBuf out from under this thread. The unixShmRelease()
3996** call will release the mutex. However, if the lock state is CHECKPOINT,
3997** the mutex is not acquired because CHECKPOINT will never remap the
3998** buffer. RECOVER might remap, though, so CHECKPOINT will acquire
3999** the mutex if and when it promotes to RECOVER.
4000**
4001** RECOVER needs to be atomic. The same mutex that prevents *ppBuf from
4002** being remapped also prevents more than one thread from being in
4003** RECOVER at a time. But, RECOVER sometimes wants to remap itself.
4004** To prevent RECOVER from losing its lock while remapping, the
4005** mutex is not released by unixShmRelease() when in RECOVER.
4006**
4007** *pNewMapSize is set to the size of the mapping.
4008**
4009** *ppBuf and *pNewMapSize might be NULL and zero if no space has
4010** yet been allocated to the underlying storage.
4011*/
4012static int unixShmGet(
4013 sqlite3_file *fd, /* Database file holding shared memory */
4014 int reqMapSize, /* Requested size of mapping. -1 means don't care */
4015 int *pNewMapSize, /* Write new size of mapping here */
4016 void **ppBuf /* Write mapping buffer origin here */
4017){
4018 unixFile *pDbFd = (unixFile*)fd;
4019 unixShm *p = pDbFd->pShm;
4020 unixShmFile *pFile = p->pFile;
4021 int rc = SQLITE_OK;
4022
4023 if( p->lockState!=SQLITE_SHM_CHECKPOINT && p->hasMutexBuf==0 ){
4024 assert( sqlite3_mutex_notheld(pFile->mutex) );
4025 sqlite3_mutex_enter(pFile->mutexBuf);
4026 p->hasMutexBuf = 1;
4027 }
4028 sqlite3_mutex_enter(pFile->mutex);
4029 if( pFile->szMap==0 || reqMapSize>pFile->szMap ){
4030 int actualSize;
4031 if( unixShmSize(fd, -1, &actualSize)==SQLITE_OK
4032 && reqMapSize<actualSize
4033 ){
4034 reqMapSize = actualSize;
4035 }
4036 if( pFile->pMMapBuf ){
4037 munmap(pFile->pMMapBuf, pFile->szMap);
4038 }
4039 pFile->pMMapBuf = mmap(0, reqMapSize, PROT_READ|PROT_WRITE, MAP_SHARED,
4040 pFile->h, 0);
4041 pFile->szMap = pFile->pMMapBuf ? reqMapSize : 0;
4042 }
4043 *pNewMapSize = pFile->szMap;
4044 *ppBuf = pFile->pMMapBuf;
4045 sqlite3_mutex_leave(pFile->mutex);
4046 return rc;
4047}
4048
4049/*
4050** Release the lock held on the shared memory segment to that other
4051** threads are free to resize it if necessary.
4052**
4053** If the lock is not currently held, this routine is a harmless no-op.
4054**
4055** If the shared-memory object is in lock state RECOVER, then we do not
4056** really want to release the lock, so in that case too, this routine
4057** is a no-op.
4058*/
4059static int unixShmRelease(sqlite3_file *fd){
4060 unixFile *pDbFd = (unixFile*)fd;
4061 unixShm *p = pDbFd->pShm;
4062
4063 if( p->hasMutexBuf && p->lockState!=SQLITE_SHM_RECOVER ){
4064 assert( sqlite3_mutex_notheld(p->pFile->mutex) );
4065 sqlite3_mutex_leave(p->pFile->mutexBuf);
4066 p->hasMutexBuf = 0;
4067 }
4068 return SQLITE_OK;
4069}
4070
4071/*
4072** Symbolic names for LOCK states used for debugging.
4073*/
4074#ifdef SQLITE_DEBUG
4075static const char *azLkName[] = {
4076 "UNLOCK",
4077 "READ",
4078 "READ_FULL",
4079 "WRITE",
4080 "PENDING",
4081 "CHECKPOINT",
4082 "RECOVER"
4083};
4084#endif
4085
4086
4087/*
4088** Change the lock state for a shared-memory segment.
4089*/
4090static int unixShmLock(
4091 sqlite3_file *fd, /* Database file holding the shared memory */
4092 int desiredLock, /* One of SQLITE_SHM_xxxxx locking states */
4093 int *pGotLock /* The lock you actually got */
4094){
4095 unixFile *pDbFd = (unixFile*)fd;
4096 unixShm *p = pDbFd->pShm;
4097 unixShmFile *pFile = p->pFile;
4098 int rc = SQLITE_PROTOCOL;
4099
4100 /* Note that SQLITE_SHM_READ_FULL and SQLITE_SHM_PENDING are never
4101 ** directly requested; they are side effects from requesting
4102 ** SQLITE_SHM_READ and SQLITE_SHM_CHECKPOINT, respectively.
4103 */
4104 assert( desiredLock==SQLITE_SHM_UNLOCK
4105 || desiredLock==SQLITE_SHM_READ
4106 || desiredLock==SQLITE_SHM_WRITE
4107 || desiredLock==SQLITE_SHM_CHECKPOINT
4108 || desiredLock==SQLITE_SHM_RECOVER );
4109
4110 /* Return directly if this is just a lock state query, or if
4111 ** the connection is already in the desired locking state.
4112 */
4113 if( desiredLock==p->lockState
4114 || (desiredLock==SQLITE_SHM_READ && p->lockState==SQLITE_SHM_READ_FULL)
4115 ){
4116 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s and got %s\n",
4117 p->id, getpid(), azLkName[desiredLock], azLkName[p->lockState]));
4118 if( pGotLock ) *pGotLock = p->lockState;
4119 return SQLITE_OK;
4120 }
4121
4122 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s->%s\n",
4123 p->id, getpid(), azLkName[p->lockState], azLkName[desiredLock]));
4124
4125 if( desiredLock==SQLITE_SHM_RECOVER && !p->hasMutexBuf ){
4126 assert( sqlite3_mutex_notheld(pFile->mutex) );
4127 sqlite3_mutex_enter(pFile->mutexBuf);
4128 p->hasMutexBuf = 1;
4129 }
4130 sqlite3_mutex_enter(pFile->mutex);
4131 switch( desiredLock ){
4132 case SQLITE_SHM_UNLOCK: {
4133 assert( p->lockState!=SQLITE_SHM_RECOVER );
4134 unixShmUnlock(pFile, p, UNIX_SHM_A|UNIX_SHM_B|UNIX_SHM_C|UNIX_SHM_D);
4135 rc = SQLITE_OK;
4136 p->lockState = SQLITE_SHM_UNLOCK;
4137 break;
4138 }
4139 case SQLITE_SHM_READ: {
4140 if( p->lockState==SQLITE_SHM_UNLOCK ){
4141 int nAttempt;
4142 rc = SQLITE_BUSY;
4143 assert( p->lockState==SQLITE_SHM_UNLOCK );
4144 for(nAttempt=0; nAttempt<5 && rc==SQLITE_BUSY; nAttempt++){
4145 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A|UNIX_SHM_B);
4146 if( rc==SQLITE_BUSY ){
4147 rc = unixShmSharedLock(pFile, p, UNIX_SHM_D);
4148 if( rc==SQLITE_OK ){
4149 p->lockState = SQLITE_SHM_READ_FULL;
4150 }
4151 }else{
4152 unixShmUnlock(pFile, p, UNIX_SHM_B);
4153 p->lockState = SQLITE_SHM_READ;
4154 }
4155 }
4156 }else{
4157 assert( p->lockState==SQLITE_SHM_WRITE
4158 || p->lockState==SQLITE_SHM_RECOVER );
4159 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A);
4160 unixShmUnlock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
4161 p->lockState = SQLITE_SHM_READ;
4162 }
4163 break;
4164 }
4165 case SQLITE_SHM_WRITE: {
4166 assert( p->lockState==SQLITE_SHM_READ
4167 || p->lockState==SQLITE_SHM_READ_FULL );
4168 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
4169 if( rc==SQLITE_OK ){
4170 p->lockState = SQLITE_SHM_WRITE;
4171 }
4172 break;
4173 }
4174 case SQLITE_SHM_CHECKPOINT: {
4175 assert( p->lockState==SQLITE_SHM_UNLOCK
4176 || p->lockState==SQLITE_SHM_PENDING
4177 );
4178 if( p->lockState==SQLITE_SHM_UNLOCK ){
4179 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_B|UNIX_SHM_C);
4180 if( rc==SQLITE_OK ){
4181 p->lockState = SQLITE_SHM_PENDING;
4182 }
4183 }
4184 if( p->lockState==SQLITE_SHM_PENDING ){
4185 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_A);
4186 if( rc==SQLITE_OK ){
4187 p->lockState = SQLITE_SHM_CHECKPOINT;
4188 }
4189 }
4190 break;
4191 }
4192 default: {
4193 assert( desiredLock==SQLITE_SHM_RECOVER );
4194 assert( p->lockState==SQLITE_SHM_READ
4195 || p->lockState==SQLITE_SHM_READ_FULL
4196 );
4197 assert( sqlite3_mutex_held(pFile->mutexBuf) );
4198 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C);
4199 if( rc==SQLITE_OK ){
4200 p->lockState = SQLITE_SHM_RECOVER;
4201 }
4202 break;
4203 }
4204 }
4205 sqlite3_mutex_leave(pFile->mutex);
4206 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %s\n",
4207 p->id, getpid(), azLkName[p->lockState]));
4208 if( pGotLock ) *pGotLock = p->lockState;
4209 return rc;
4210}
4211
4212#else
4213# define unixShmOpen 0
4214# define unixShmSize 0
4215# define unixShmGet 0
4216# define unixShmRelease 0
4217# define unixShmLock 0
4218# define unixShmClose 0
4219#endif /* #ifndef SQLITE_OMIT_WAL */
4220
drh734c9862008-11-28 15:37:20 +00004221/*
4222** Here ends the implementation of all sqlite3_file methods.
4223**
4224********************** End sqlite3_file Methods *******************************
4225******************************************************************************/
4226
4227/*
drh6b9d6dd2008-12-03 19:34:47 +00004228** This division contains definitions of sqlite3_io_methods objects that
4229** implement various file locking strategies. It also contains definitions
4230** of "finder" functions. A finder-function is used to locate the appropriate
4231** sqlite3_io_methods object for a particular database file. The pAppData
4232** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4233** the correct finder-function for that VFS.
4234**
4235** Most finder functions return a pointer to a fixed sqlite3_io_methods
4236** object. The only interesting finder-function is autolockIoFinder, which
4237** looks at the filesystem type and tries to guess the best locking
4238** strategy from that.
4239**
drh1875f7a2008-12-08 18:19:17 +00004240** For finder-funtion F, two objects are created:
4241**
4242** (1) The real finder-function named "FImpt()".
4243**
dane946c392009-08-22 11:39:46 +00004244** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004245**
4246**
4247** A pointer to the F pointer is used as the pAppData value for VFS
4248** objects. We have to do this instead of letting pAppData point
4249** directly at the finder-function since C90 rules prevent a void*
4250** from be cast into a function pointer.
4251**
drh6b9d6dd2008-12-03 19:34:47 +00004252**
drh7708e972008-11-29 00:56:52 +00004253** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004254**
drh7708e972008-11-29 00:56:52 +00004255** * A constant sqlite3_io_methods object call METHOD that has locking
4256** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4257**
4258** * An I/O method finder function called FINDER that returns a pointer
4259** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004260*/
drhd9e5c4f2010-05-12 18:01:39 +00004261#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004262static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004263 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004264 CLOSE, /* xClose */ \
4265 unixRead, /* xRead */ \
4266 unixWrite, /* xWrite */ \
4267 unixTruncate, /* xTruncate */ \
4268 unixSync, /* xSync */ \
4269 unixFileSize, /* xFileSize */ \
4270 LOCK, /* xLock */ \
4271 UNLOCK, /* xUnlock */ \
4272 CKLOCK, /* xCheckReservedLock */ \
4273 unixFileControl, /* xFileControl */ \
4274 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004275 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
4276 unixShmOpen, /* xShmOpen */ \
4277 unixShmSize, /* xShmSize */ \
4278 unixShmGet, /* xShmGet */ \
4279 unixShmRelease, /* xShmRelease */ \
4280 unixShmLock, /* xShmLock */ \
4281 unixShmClose /* xShmClose */ \
drh7708e972008-11-29 00:56:52 +00004282}; \
drh0c2694b2009-09-03 16:23:44 +00004283static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4284 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004285 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004286} \
drh0c2694b2009-09-03 16:23:44 +00004287static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004288 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004289
4290/*
4291** Here are all of the sqlite3_io_methods objects for each of the
4292** locking strategies. Functions that return pointers to these methods
4293** are also created.
4294*/
4295IOMETHODS(
4296 posixIoFinder, /* Finder function name */
4297 posixIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004298 2, /* ShmOpen is enabled */
drh7708e972008-11-29 00:56:52 +00004299 unixClose, /* xClose method */
4300 unixLock, /* xLock method */
4301 unixUnlock, /* xUnlock method */
4302 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004303)
drh7708e972008-11-29 00:56:52 +00004304IOMETHODS(
4305 nolockIoFinder, /* Finder function name */
4306 nolockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004307 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004308 nolockClose, /* xClose method */
4309 nolockLock, /* xLock method */
4310 nolockUnlock, /* xUnlock method */
4311 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004312)
drh7708e972008-11-29 00:56:52 +00004313IOMETHODS(
4314 dotlockIoFinder, /* Finder function name */
4315 dotlockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004316 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004317 dotlockClose, /* xClose method */
4318 dotlockLock, /* xLock method */
4319 dotlockUnlock, /* xUnlock method */
4320 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004321)
drh7708e972008-11-29 00:56:52 +00004322
chw78a13182009-04-07 05:35:03 +00004323#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004324IOMETHODS(
4325 flockIoFinder, /* Finder function name */
4326 flockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004327 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004328 flockClose, /* xClose method */
4329 flockLock, /* xLock method */
4330 flockUnlock, /* xUnlock method */
4331 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004332)
drh7708e972008-11-29 00:56:52 +00004333#endif
4334
drh6c7d5c52008-11-21 20:32:33 +00004335#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004336IOMETHODS(
4337 semIoFinder, /* Finder function name */
4338 semIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004339 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004340 semClose, /* xClose method */
4341 semLock, /* xLock method */
4342 semUnlock, /* xUnlock method */
4343 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004344)
aswiftaebf4132008-11-21 00:10:35 +00004345#endif
drh7708e972008-11-29 00:56:52 +00004346
drhd2cb50b2009-01-09 21:41:17 +00004347#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004348IOMETHODS(
4349 afpIoFinder, /* Finder function name */
4350 afpIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004351 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004352 afpClose, /* xClose method */
4353 afpLock, /* xLock method */
4354 afpUnlock, /* xUnlock method */
4355 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004356)
drh715ff302008-12-03 22:32:44 +00004357#endif
4358
4359/*
4360** The proxy locking method is a "super-method" in the sense that it
4361** opens secondary file descriptors for the conch and lock files and
4362** it uses proxy, dot-file, AFP, and flock() locking methods on those
4363** secondary files. For this reason, the division that implements
4364** proxy locking is located much further down in the file. But we need
4365** to go ahead and define the sqlite3_io_methods and finder function
4366** for proxy locking here. So we forward declare the I/O methods.
4367*/
drhd2cb50b2009-01-09 21:41:17 +00004368#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004369static int proxyClose(sqlite3_file*);
4370static int proxyLock(sqlite3_file*, int);
4371static int proxyUnlock(sqlite3_file*, int);
4372static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004373IOMETHODS(
4374 proxyIoFinder, /* Finder function name */
4375 proxyIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004376 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004377 proxyClose, /* xClose method */
4378 proxyLock, /* xLock method */
4379 proxyUnlock, /* xUnlock method */
4380 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004381)
aswiftaebf4132008-11-21 00:10:35 +00004382#endif
drh7708e972008-11-29 00:56:52 +00004383
drh7ed97b92010-01-20 13:07:21 +00004384/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4385#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4386IOMETHODS(
4387 nfsIoFinder, /* Finder function name */
4388 nfsIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004389 1, /* ShmOpen is disabled */
drh7ed97b92010-01-20 13:07:21 +00004390 unixClose, /* xClose method */
4391 unixLock, /* xLock method */
4392 nfsUnlock, /* xUnlock method */
4393 unixCheckReservedLock /* xCheckReservedLock method */
4394)
4395#endif
drh7708e972008-11-29 00:56:52 +00004396
drhd2cb50b2009-01-09 21:41:17 +00004397#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004398/*
drh6b9d6dd2008-12-03 19:34:47 +00004399** This "finder" function attempts to determine the best locking strategy
4400** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004401** object that implements that strategy.
4402**
4403** This is for MacOSX only.
4404*/
drh1875f7a2008-12-08 18:19:17 +00004405static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004406 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004407 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004408){
4409 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004410 const char *zFilesystem; /* Filesystem type name */
4411 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004412 } aMap[] = {
4413 { "hfs", &posixIoMethods },
4414 { "ufs", &posixIoMethods },
4415 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004416 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004417 { "webdav", &nolockIoMethods },
4418 { 0, 0 }
4419 };
4420 int i;
4421 struct statfs fsInfo;
4422 struct flock lockInfo;
4423
4424 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004425 /* If filePath==NULL that means we are dealing with a transient file
4426 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004427 return &nolockIoMethods;
4428 }
4429 if( statfs(filePath, &fsInfo) != -1 ){
4430 if( fsInfo.f_flags & MNT_RDONLY ){
4431 return &nolockIoMethods;
4432 }
4433 for(i=0; aMap[i].zFilesystem; i++){
4434 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4435 return aMap[i].pMethods;
4436 }
4437 }
4438 }
4439
4440 /* Default case. Handles, amongst others, "nfs".
4441 ** Test byte-range lock using fcntl(). If the call succeeds,
4442 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004443 */
drh7708e972008-11-29 00:56:52 +00004444 lockInfo.l_len = 1;
4445 lockInfo.l_start = 0;
4446 lockInfo.l_whence = SEEK_SET;
4447 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004448 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004449 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4450 return &nfsIoMethods;
4451 } else {
4452 return &posixIoMethods;
4453 }
drh7708e972008-11-29 00:56:52 +00004454 }else{
4455 return &dotlockIoMethods;
4456 }
4457}
drh0c2694b2009-09-03 16:23:44 +00004458static const sqlite3_io_methods
4459 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004460
drhd2cb50b2009-01-09 21:41:17 +00004461#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004462
chw78a13182009-04-07 05:35:03 +00004463#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4464/*
4465** This "finder" function attempts to determine the best locking strategy
4466** for the database file "filePath". It then returns the sqlite3_io_methods
4467** object that implements that strategy.
4468**
4469** This is for VXWorks only.
4470*/
4471static const sqlite3_io_methods *autolockIoFinderImpl(
4472 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004473 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004474){
4475 struct flock lockInfo;
4476
4477 if( !filePath ){
4478 /* If filePath==NULL that means we are dealing with a transient file
4479 ** that does not need to be locked. */
4480 return &nolockIoMethods;
4481 }
4482
4483 /* Test if fcntl() is supported and use POSIX style locks.
4484 ** Otherwise fall back to the named semaphore method.
4485 */
4486 lockInfo.l_len = 1;
4487 lockInfo.l_start = 0;
4488 lockInfo.l_whence = SEEK_SET;
4489 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004490 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004491 return &posixIoMethods;
4492 }else{
4493 return &semIoMethods;
4494 }
4495}
drh0c2694b2009-09-03 16:23:44 +00004496static const sqlite3_io_methods
4497 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004498
4499#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4500
drh7708e972008-11-29 00:56:52 +00004501/*
4502** An abstract type for a pointer to a IO method finder function:
4503*/
drh0c2694b2009-09-03 16:23:44 +00004504typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004505
aswiftaebf4132008-11-21 00:10:35 +00004506
drh734c9862008-11-28 15:37:20 +00004507/****************************************************************************
4508**************************** sqlite3_vfs methods ****************************
4509**
4510** This division contains the implementation of methods on the
4511** sqlite3_vfs object.
4512*/
4513
danielk1977a3d4c882007-03-23 10:08:38 +00004514/*
danielk1977e339d652008-06-28 11:23:00 +00004515** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004516*/
4517static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004518 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004519 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004520 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004521 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004522 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004523 int noLock, /* Omit locking if true */
4524 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004525){
drh7708e972008-11-29 00:56:52 +00004526 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004527 unixFile *pNew = (unixFile *)pId;
4528 int rc = SQLITE_OK;
4529
danielk197717b90b52008-06-06 11:11:25 +00004530 assert( pNew->pLock==NULL );
4531 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00004532
dane946c392009-08-22 11:39:46 +00004533 /* Parameter isDelete is only used on vxworks. Express this explicitly
4534 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004535 */
drh7708e972008-11-29 00:56:52 +00004536 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004537
drh308c2a52010-05-14 11:30:18 +00004538 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004539 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004540 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00004541 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00004542 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004543 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
4544 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004545
drh6c7d5c52008-11-21 20:32:33 +00004546#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004547 pNew->pId = vxworksFindFileId(zFilename);
4548 if( pNew->pId==0 ){
4549 noLock = 1;
4550 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004551 }
4552#endif
4553
drhda0e7682008-07-30 15:27:54 +00004554 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004555 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004556 }else{
drh0c2694b2009-09-03 16:23:44 +00004557 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004558#if SQLITE_ENABLE_LOCKING_STYLE
4559 /* Cache zFilename in the locking context (AFP and dotlock override) for
4560 ** proxyLock activation is possible (remote proxy is based on db name)
4561 ** zFilename remains valid until file is closed, to support */
4562 pNew->lockingContext = (void*)zFilename;
4563#endif
drhda0e7682008-07-30 15:27:54 +00004564 }
danielk1977e339d652008-06-28 11:23:00 +00004565
drh7ed97b92010-01-20 13:07:21 +00004566 if( pLockingStyle == &posixIoMethods
4567#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4568 || pLockingStyle == &nfsIoMethods
4569#endif
4570 ){
drh7708e972008-11-29 00:56:52 +00004571 unixEnterMutex();
4572 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00004573 if( rc!=SQLITE_OK ){
4574 /* If an error occured in findLockInfo(), close the file descriptor
4575 ** immediately, before releasing the mutex. findLockInfo() may fail
4576 ** in two scenarios:
4577 **
4578 ** (a) A call to fstat() failed.
4579 ** (b) A malloc failed.
4580 **
4581 ** Scenario (b) may only occur if the process is holding no other
4582 ** file descriptors open on the same file. If there were other file
4583 ** descriptors on this file, then no malloc would be required by
4584 ** findLockInfo(). If this is the case, it is quite safe to close
4585 ** handle h - as it is guaranteed that no posix locks will be released
4586 ** by doing so.
4587 **
4588 ** If scenario (a) caused the error then things are not so safe. The
4589 ** implicit assumption here is that if fstat() fails, things are in
4590 ** such bad shape that dropping a lock or two doesn't matter much.
4591 */
4592 close(h);
4593 h = -1;
4594 }
drh7708e972008-11-29 00:56:52 +00004595 unixLeaveMutex();
4596 }
danielk1977e339d652008-06-28 11:23:00 +00004597
drhd2cb50b2009-01-09 21:41:17 +00004598#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004599 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004600 /* AFP locking uses the file path so it needs to be included in
4601 ** the afpLockingContext.
4602 */
4603 afpLockingContext *pCtx;
4604 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4605 if( pCtx==0 ){
4606 rc = SQLITE_NOMEM;
4607 }else{
4608 /* NB: zFilename exists and remains valid until the file is closed
4609 ** according to requirement F11141. So we do not need to make a
4610 ** copy of the filename. */
4611 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004612 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004613 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004614 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00004615 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
4616 if( rc!=SQLITE_OK ){
4617 sqlite3_free(pNew->lockingContext);
4618 close(h);
4619 h = -1;
4620 }
drh7708e972008-11-29 00:56:52 +00004621 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004622 }
drh7708e972008-11-29 00:56:52 +00004623 }
4624#endif
danielk1977e339d652008-06-28 11:23:00 +00004625
drh7708e972008-11-29 00:56:52 +00004626 else if( pLockingStyle == &dotlockIoMethods ){
4627 /* Dotfile locking uses the file path so it needs to be included in
4628 ** the dotlockLockingContext
4629 */
4630 char *zLockFile;
4631 int nFilename;
drhea678832008-12-10 19:26:22 +00004632 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004633 zLockFile = (char *)sqlite3_malloc(nFilename);
4634 if( zLockFile==0 ){
4635 rc = SQLITE_NOMEM;
4636 }else{
4637 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004638 }
drh7708e972008-11-29 00:56:52 +00004639 pNew->lockingContext = zLockFile;
4640 }
danielk1977e339d652008-06-28 11:23:00 +00004641
drh6c7d5c52008-11-21 20:32:33 +00004642#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004643 else if( pLockingStyle == &semIoMethods ){
4644 /* Named semaphore locking uses the file path so it needs to be
4645 ** included in the semLockingContext
4646 */
4647 unixEnterMutex();
4648 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
4649 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
4650 char *zSemName = pNew->pOpen->aSemName;
4651 int n;
drh2238dcc2009-08-27 17:56:20 +00004652 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004653 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004654 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004655 if( zSemName[n]=='/' ) zSemName[n] = '_';
4656 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4657 if( pNew->pOpen->pSem == SEM_FAILED ){
4658 rc = SQLITE_NOMEM;
4659 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004660 }
chw97185482008-11-17 08:05:31 +00004661 }
drh7708e972008-11-29 00:56:52 +00004662 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004663 }
drh7708e972008-11-29 00:56:52 +00004664#endif
aswift5b1a2562008-08-22 00:22:35 +00004665
4666 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004667#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004668 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004669 if( h>=0 ) close(h);
4670 h = -1;
chw97185482008-11-17 08:05:31 +00004671 unlink(zFilename);
4672 isDelete = 0;
4673 }
4674 pNew->isDelete = isDelete;
4675#endif
danielk1977e339d652008-06-28 11:23:00 +00004676 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004677 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004678 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004679 }else{
drh7708e972008-11-29 00:56:52 +00004680 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004681 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004682 }
danielk1977e339d652008-06-28 11:23:00 +00004683 return rc;
drh054889e2005-11-30 03:20:31 +00004684}
drh9c06c952005-11-26 00:25:00 +00004685
danielk1977ad94b582007-08-20 06:44:22 +00004686/*
4687** Open a file descriptor to the directory containing file zFilename.
4688** If successful, *pFd is set to the opened file descriptor and
4689** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4690** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4691** value.
4692**
4693** If SQLITE_OK is returned, the caller is responsible for closing
4694** the file descriptor *pFd using close().
4695*/
danielk1977fee2d252007-08-18 10:59:19 +00004696static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004697 int ii;
drh777b17a2007-09-20 10:02:54 +00004698 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004699 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004700
drh153c62c2007-08-24 03:51:33 +00004701 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004702 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004703 if( ii>0 ){
4704 zDirname[ii] = '\0';
4705 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004706 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004707#ifdef FD_CLOEXEC
4708 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4709#endif
drh308c2a52010-05-14 11:30:18 +00004710 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004711 }
4712 }
danielk1977fee2d252007-08-18 10:59:19 +00004713 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004714 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004715}
4716
danielk1977b4b47412007-08-17 15:53:36 +00004717/*
danielk197717b90b52008-06-06 11:11:25 +00004718** Create a temporary file name in zBuf. zBuf must be allocated
4719** by the calling process and must be big enough to hold at least
4720** pVfs->mxPathname bytes.
4721*/
4722static int getTempname(int nBuf, char *zBuf){
4723 static const char *azDirs[] = {
4724 0,
aswiftaebf4132008-11-21 00:10:35 +00004725 0,
danielk197717b90b52008-06-06 11:11:25 +00004726 "/var/tmp",
4727 "/usr/tmp",
4728 "/tmp",
4729 ".",
4730 };
4731 static const unsigned char zChars[] =
4732 "abcdefghijklmnopqrstuvwxyz"
4733 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4734 "0123456789";
drh41022642008-11-21 00:24:42 +00004735 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00004736 struct stat buf;
4737 const char *zDir = ".";
4738
4739 /* It's odd to simulate an io-error here, but really this is just
4740 ** using the io-error infrastructure to test that SQLite handles this
4741 ** function failing.
4742 */
4743 SimulateIOError( return SQLITE_IOERR );
4744
4745 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00004746 if (NULL == azDirs[1]) {
4747 azDirs[1] = getenv("TMPDIR");
4748 }
4749
4750 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00004751 if( azDirs[i]==0 ) continue;
4752 if( stat(azDirs[i], &buf) ) continue;
4753 if( !S_ISDIR(buf.st_mode) ) continue;
4754 if( access(azDirs[i], 07) ) continue;
4755 zDir = azDirs[i];
4756 break;
4757 }
4758
4759 /* Check that the output buffer is large enough for the temporary file
4760 ** name. If it is not, return SQLITE_ERROR.
4761 */
danielk197700e13612008-11-17 19:18:54 +00004762 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004763 return SQLITE_ERROR;
4764 }
4765
4766 do{
4767 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004768 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004769 sqlite3_randomness(15, &zBuf[j]);
4770 for(i=0; i<15; i++, j++){
4771 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4772 }
4773 zBuf[j] = 0;
4774 }while( access(zBuf,0)==0 );
4775 return SQLITE_OK;
4776}
4777
drhd2cb50b2009-01-09 21:41:17 +00004778#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004779/*
4780** Routine to transform a unixFile into a proxy-locking unixFile.
4781** Implementation in the proxy-lock division, but used by unixOpen()
4782** if SQLITE_PREFER_PROXY_LOCKING is defined.
4783*/
4784static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004785#endif
drhc66d5b62008-12-03 22:48:32 +00004786
dan08da86a2009-08-21 17:18:03 +00004787/*
4788** Search for an unused file descriptor that was opened on the database
4789** file (not a journal or master-journal file) identified by pathname
4790** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4791** argument to this function.
4792**
4793** Such a file descriptor may exist if a database connection was closed
4794** but the associated file descriptor could not be closed because some
4795** other file descriptor open on the same file is holding a file-lock.
4796** Refer to comments in the unixClose() function and the lengthy comment
4797** describing "Posix Advisory Locking" at the start of this file for
4798** further details. Also, ticket #4018.
4799**
4800** If a suitable file descriptor is found, then it is returned. If no
4801** such file descriptor is located, -1 is returned.
4802*/
dane946c392009-08-22 11:39:46 +00004803static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4804 UnixUnusedFd *pUnused = 0;
4805
4806 /* Do not search for an unused file descriptor on vxworks. Not because
4807 ** vxworks would not benefit from the change (it might, we're not sure),
4808 ** but because no way to test it is currently available. It is better
4809 ** not to risk breaking vxworks support for the sake of such an obscure
4810 ** feature. */
4811#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004812 struct stat sStat; /* Results of stat() call */
4813
4814 /* A stat() call may fail for various reasons. If this happens, it is
4815 ** almost certain that an open() call on the same path will also fail.
4816 ** For this reason, if an error occurs in the stat() call here, it is
4817 ** ignored and -1 is returned. The caller will try to open a new file
4818 ** descriptor on the same path, fail, and return an error to SQLite.
4819 **
4820 ** Even if a subsequent open() call does succeed, the consequences of
4821 ** not searching for a resusable file descriptor are not dire. */
4822 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00004823 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00004824
4825 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00004826 pOpen = openList;
4827 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
4828 || pOpen->fileId.ino!=sStat.st_ino) ){
4829 pOpen = pOpen->pNext;
4830 }
4831 if( pOpen ){
dane946c392009-08-22 11:39:46 +00004832 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00004833 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004834 pUnused = *pp;
4835 if( pUnused ){
4836 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004837 }
4838 }
4839 unixLeaveMutex();
4840 }
dane946c392009-08-22 11:39:46 +00004841#endif /* if !OS_VXWORKS */
4842 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004843}
danielk197717b90b52008-06-06 11:11:25 +00004844
4845/*
danielk1977ad94b582007-08-20 06:44:22 +00004846** Open the file zPath.
4847**
danielk1977b4b47412007-08-17 15:53:36 +00004848** Previously, the SQLite OS layer used three functions in place of this
4849** one:
4850**
4851** sqlite3OsOpenReadWrite();
4852** sqlite3OsOpenReadOnly();
4853** sqlite3OsOpenExclusive();
4854**
4855** These calls correspond to the following combinations of flags:
4856**
4857** ReadWrite() -> (READWRITE | CREATE)
4858** ReadOnly() -> (READONLY)
4859** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4860**
4861** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4862** true, the file was configured to be automatically deleted when the
4863** file handle closed. To achieve the same effect using this new
4864** interface, add the DELETEONCLOSE flag to those specified above for
4865** OpenExclusive().
4866*/
4867static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004868 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4869 const char *zPath, /* Pathname of file to be opened */
4870 sqlite3_file *pFile, /* The file descriptor to be filled in */
4871 int flags, /* Input flags to control the opening */
4872 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004873){
dan08da86a2009-08-21 17:18:03 +00004874 unixFile *p = (unixFile *)pFile;
4875 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004876 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004877 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004878 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004879 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004880 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004881
4882 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4883 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4884 int isCreate = (flags & SQLITE_OPEN_CREATE);
4885 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4886 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004887#if SQLITE_ENABLE_LOCKING_STYLE
4888 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4889#endif
danielk1977b4b47412007-08-17 15:53:36 +00004890
danielk1977fee2d252007-08-18 10:59:19 +00004891 /* If creating a master or main-file journal, this function will open
4892 ** a file-descriptor on the directory too. The first time unixSync()
4893 ** is called the directory file descriptor will be fsync()ed and close()d.
4894 */
4895 int isOpenDirectory = (isCreate &&
4896 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4897 );
4898
danielk197717b90b52008-06-06 11:11:25 +00004899 /* If argument zPath is a NULL pointer, this function is required to open
4900 ** a temporary file. Use this buffer to store the file name in.
4901 */
4902 char zTmpname[MAX_PATHNAME+1];
4903 const char *zName = zPath;
4904
danielk1977fee2d252007-08-18 10:59:19 +00004905 /* Check the following statements are true:
4906 **
4907 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4908 ** (b) if CREATE is set, then READWRITE must also be set, and
4909 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004910 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004911 */
danielk1977b4b47412007-08-17 15:53:36 +00004912 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004913 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004914 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004915 assert(isDelete==0 || isCreate);
4916
drh33f4e022007-09-03 15:19:34 +00004917 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004918 ** deleted. Nor are they ever temporary files. */
4919 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4920 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4921 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004922
danielk1977fee2d252007-08-18 10:59:19 +00004923 /* Assert that the upper layer has set one of the "file-type" flags. */
4924 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4925 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4926 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004927 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004928 );
4929
dan08da86a2009-08-21 17:18:03 +00004930 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004931
dan08da86a2009-08-21 17:18:03 +00004932 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004933 UnixUnusedFd *pUnused;
4934 pUnused = findReusableFd(zName, flags);
4935 if( pUnused ){
4936 fd = pUnused->fd;
4937 }else{
dan6aa657f2009-08-24 18:57:58 +00004938 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004939 if( !pUnused ){
4940 return SQLITE_NOMEM;
4941 }
4942 }
4943 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004944 }else if( !zName ){
4945 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004946 assert(isDelete && !isOpenDirectory);
4947 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4948 if( rc!=SQLITE_OK ){
4949 return rc;
4950 }
4951 zName = zTmpname;
4952 }
4953
dan08da86a2009-08-21 17:18:03 +00004954 /* Determine the value of the flags parameter passed to POSIX function
4955 ** open(). These must be calculated even if open() is not called, as
4956 ** they may be stored as part of the file handle and used by the
4957 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004958 if( isReadonly ) openFlags |= O_RDONLY;
4959 if( isReadWrite ) openFlags |= O_RDWR;
4960 if( isCreate ) openFlags |= O_CREAT;
4961 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4962 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004963
danielk1977b4b47412007-08-17 15:53:36 +00004964 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004965 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4966 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004967 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004968 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4969 /* Failed to open the file for read/write access. Try read-only. */
4970 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004971 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004972 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004973 openFlags |= O_RDONLY;
4974 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004975 }
4976 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004977 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004978 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004979 }
danielk1977b4b47412007-08-17 15:53:36 +00004980 }
dan08da86a2009-08-21 17:18:03 +00004981 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004982 if( pOutFlags ){
4983 *pOutFlags = flags;
4984 }
4985
dane946c392009-08-22 11:39:46 +00004986 if( p->pUnused ){
4987 p->pUnused->fd = fd;
4988 p->pUnused->flags = flags;
4989 }
4990
danielk1977b4b47412007-08-17 15:53:36 +00004991 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004992#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004993 zPath = zName;
4994#else
danielk197717b90b52008-06-06 11:11:25 +00004995 unlink(zName);
chw97185482008-11-17 08:05:31 +00004996#endif
danielk1977b4b47412007-08-17 15:53:36 +00004997 }
drh41022642008-11-21 00:24:42 +00004998#if SQLITE_ENABLE_LOCKING_STYLE
4999 else{
dan08da86a2009-08-21 17:18:03 +00005000 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005001 }
5002#endif
5003
danielk1977fee2d252007-08-18 10:59:19 +00005004 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005005 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005006 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005007 /* It is safe to close fd at this point, because it is guaranteed not
5008 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005009 ** it would not be safe to close as this would release any locks held
5010 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005011 assert( eType!=SQLITE_OPEN_MAIN_DB );
5012 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00005013 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005014 }
5015 }
danielk1977e339d652008-06-28 11:23:00 +00005016
5017#ifdef FD_CLOEXEC
5018 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
5019#endif
5020
drhda0e7682008-07-30 15:27:54 +00005021 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005022
drh7ed97b92010-01-20 13:07:21 +00005023
5024#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5025 struct statfs fsInfo;
5026 if( fstatfs(fd, &fsInfo) == -1 ){
5027 ((unixFile*)pFile)->lastErrno = errno;
5028 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
5029 close(fd); /* silently leak if fail, in error */
5030 return SQLITE_IOERR_ACCESS;
5031 }
5032 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5033 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5034 }
5035#endif
5036
5037#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005038#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005039 isAutoProxy = 1;
5040#endif
5041 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005042 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5043 int useProxy = 0;
5044
dan08da86a2009-08-21 17:18:03 +00005045 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5046 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005047 if( envforce!=NULL ){
5048 useProxy = atoi(envforce)>0;
5049 }else{
5050 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005051 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005052 /* In theory, the close(fd) call is sub-optimal. If the file opened
5053 ** with fd is a database file, and there are other connections open
5054 ** on that file that are currently holding advisory locks on it,
5055 ** then the call to close() will cancel those locks. In practice,
5056 ** we're assuming that statfs() doesn't fail very often. At least
5057 ** not while other file descriptors opened by the same process on
5058 ** the same file are working. */
5059 p->lastErrno = errno;
5060 if( dirfd>=0 ){
5061 close(dirfd); /* silently leak if fail, in error */
5062 }
aswiftaebf4132008-11-21 00:10:35 +00005063 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00005064 rc = SQLITE_IOERR_ACCESS;
5065 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005066 }
5067 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5068 }
5069 if( useProxy ){
5070 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
5071 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005072 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005073 if( rc!=SQLITE_OK ){
5074 /* Use unixClose to clean up the resources added in fillInUnixFile
5075 ** and clear all the structure's references. Specifically,
5076 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5077 */
5078 unixClose(pFile);
5079 return rc;
5080 }
aswiftaebf4132008-11-21 00:10:35 +00005081 }
dane946c392009-08-22 11:39:46 +00005082 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005083 }
5084 }
5085#endif
5086
dane946c392009-08-22 11:39:46 +00005087 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
5088open_finished:
5089 if( rc!=SQLITE_OK ){
5090 sqlite3_free(p->pUnused);
5091 }
5092 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005093}
5094
dane946c392009-08-22 11:39:46 +00005095
danielk1977b4b47412007-08-17 15:53:36 +00005096/*
danielk1977fee2d252007-08-18 10:59:19 +00005097** Delete the file at zPath. If the dirSync argument is true, fsync()
5098** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005099*/
drh6b9d6dd2008-12-03 19:34:47 +00005100static int unixDelete(
5101 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5102 const char *zPath, /* Name of file to be deleted */
5103 int dirSync /* If true, fsync() directory after deleting file */
5104){
danielk1977fee2d252007-08-18 10:59:19 +00005105 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005106 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005107 SimulateIOError(return SQLITE_IOERR_DELETE);
5108 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00005109#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005110 if( dirSync ){
5111 int fd;
5112 rc = openDirectory(zPath, &fd);
5113 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005114#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005115 if( fsync(fd)==-1 )
5116#else
5117 if( fsync(fd) )
5118#endif
5119 {
danielk1977fee2d252007-08-18 10:59:19 +00005120 rc = SQLITE_IOERR_DIR_FSYNC;
5121 }
aswiftaebf4132008-11-21 00:10:35 +00005122 if( close(fd)&&!rc ){
5123 rc = SQLITE_IOERR_DIR_CLOSE;
5124 }
danielk1977fee2d252007-08-18 10:59:19 +00005125 }
5126 }
danielk1977d138dd82008-10-15 16:02:48 +00005127#endif
danielk1977fee2d252007-08-18 10:59:19 +00005128 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005129}
5130
danielk197790949c22007-08-17 16:50:38 +00005131/*
5132** Test the existance of or access permissions of file zPath. The
5133** test performed depends on the value of flags:
5134**
5135** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5136** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5137** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5138**
5139** Otherwise return 0.
5140*/
danielk1977861f7452008-06-05 11:39:11 +00005141static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005142 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5143 const char *zPath, /* Path of the file to examine */
5144 int flags, /* What do we want to learn about the zPath file? */
5145 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005146){
rse25c0d1a2007-09-20 08:38:14 +00005147 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005148 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005149 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005150 switch( flags ){
5151 case SQLITE_ACCESS_EXISTS:
5152 amode = F_OK;
5153 break;
5154 case SQLITE_ACCESS_READWRITE:
5155 amode = W_OK|R_OK;
5156 break;
drh50d3f902007-08-27 21:10:36 +00005157 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005158 amode = R_OK;
5159 break;
5160
5161 default:
5162 assert(!"Invalid flags argument");
5163 }
danielk1977861f7452008-06-05 11:39:11 +00005164 *pResOut = (access(zPath, amode)==0);
5165 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005166}
5167
danielk1977b4b47412007-08-17 15:53:36 +00005168
5169/*
5170** Turn a relative pathname into a full pathname. The relative path
5171** is stored as a nul-terminated string in the buffer pointed to by
5172** zPath.
5173**
5174** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5175** (in this case, MAX_PATHNAME bytes). The full-path is written to
5176** this buffer before returning.
5177*/
danielk1977adfb9b02007-09-17 07:02:56 +00005178static int unixFullPathname(
5179 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5180 const char *zPath, /* Possibly relative input path */
5181 int nOut, /* Size of output buffer in bytes */
5182 char *zOut /* Output buffer */
5183){
danielk1977843e65f2007-09-01 16:16:15 +00005184
5185 /* It's odd to simulate an io-error here, but really this is just
5186 ** using the io-error infrastructure to test that SQLite handles this
5187 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005188 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005189 */
5190 SimulateIOError( return SQLITE_ERROR );
5191
drh153c62c2007-08-24 03:51:33 +00005192 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005193 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005194
drh3c7f2dc2007-12-06 13:26:20 +00005195 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005196 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005197 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005198 }else{
5199 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00005200 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00005201 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00005202 }
drhea678832008-12-10 19:26:22 +00005203 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005204 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005205 }
5206 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005207}
5208
drh0ccebe72005-06-07 22:22:50 +00005209
drh761df872006-12-21 01:29:22 +00005210#ifndef SQLITE_OMIT_LOAD_EXTENSION
5211/*
5212** Interfaces for opening a shared library, finding entry points
5213** within the shared library, and closing the shared library.
5214*/
5215#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005216static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5217 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005218 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5219}
danielk197795c8a542007-09-01 06:51:27 +00005220
5221/*
5222** SQLite calls this function immediately after a call to unixDlSym() or
5223** unixDlOpen() fails (returns a null pointer). If a more detailed error
5224** message is available, it is written to zBufOut. If no error message
5225** is available, zBufOut is left unmodified and SQLite uses a default
5226** error message.
5227*/
danielk1977397d65f2008-11-19 11:35:39 +00005228static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00005229 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005230 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005231 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005232 zErr = dlerror();
5233 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005234 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005235 }
drh6c7d5c52008-11-21 20:32:33 +00005236 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005237}
drh1875f7a2008-12-08 18:19:17 +00005238static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5239 /*
5240 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5241 ** cast into a pointer to a function. And yet the library dlsym() routine
5242 ** returns a void* which is really a pointer to a function. So how do we
5243 ** use dlsym() with -pedantic-errors?
5244 **
5245 ** Variable x below is defined to be a pointer to a function taking
5246 ** parameters void* and const char* and returning a pointer to a function.
5247 ** We initialize x by assigning it a pointer to the dlsym() function.
5248 ** (That assignment requires a cast.) Then we call the function that
5249 ** x points to.
5250 **
5251 ** This work-around is unlikely to work correctly on any system where
5252 ** you really cannot cast a function pointer into void*. But then, on the
5253 ** other hand, dlsym() will not work on such a system either, so we have
5254 ** not really lost anything.
5255 */
5256 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005257 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005258 x = (void(*(*)(void*,const char*))(void))dlsym;
5259 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005260}
danielk1977397d65f2008-11-19 11:35:39 +00005261static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5262 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005263 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005264}
danielk1977b4b47412007-08-17 15:53:36 +00005265#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5266 #define unixDlOpen 0
5267 #define unixDlError 0
5268 #define unixDlSym 0
5269 #define unixDlClose 0
5270#endif
5271
5272/*
danielk197790949c22007-08-17 16:50:38 +00005273** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005274*/
danielk1977397d65f2008-11-19 11:35:39 +00005275static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5276 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005277 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005278
drhbbd42a62004-05-22 17:41:58 +00005279 /* We have to initialize zBuf to prevent valgrind from reporting
5280 ** errors. The reports issued by valgrind are incorrect - we would
5281 ** prefer that the randomness be increased by making use of the
5282 ** uninitialized space in zBuf - but valgrind errors tend to worry
5283 ** some users. Rather than argue, it seems easier just to initialize
5284 ** the whole array and silence valgrind, even if that means less randomness
5285 ** in the random seed.
5286 **
5287 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005288 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005289 ** tests repeatable.
5290 */
danielk1977b4b47412007-08-17 15:53:36 +00005291 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005292#if !defined(SQLITE_TEST)
5293 {
drh842b8642005-01-21 17:53:17 +00005294 int pid, fd;
5295 fd = open("/dev/urandom", O_RDONLY);
5296 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005297 time_t t;
5298 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005299 memcpy(zBuf, &t, sizeof(t));
5300 pid = getpid();
5301 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005302 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005303 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005304 }else{
drh72cbd072008-10-14 17:58:38 +00005305 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00005306 close(fd);
5307 }
drhbbd42a62004-05-22 17:41:58 +00005308 }
5309#endif
drh72cbd072008-10-14 17:58:38 +00005310 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005311}
5312
danielk1977b4b47412007-08-17 15:53:36 +00005313
drhbbd42a62004-05-22 17:41:58 +00005314/*
5315** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005316** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005317** The return value is the number of microseconds of sleep actually
5318** requested from the underlying operating system, a number which
5319** might be greater than or equal to the argument, but not less
5320** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005321*/
danielk1977397d65f2008-11-19 11:35:39 +00005322static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005323#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005324 struct timespec sp;
5325
5326 sp.tv_sec = microseconds / 1000000;
5327 sp.tv_nsec = (microseconds % 1000000) * 1000;
5328 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005329 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005330 return microseconds;
5331#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005332 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005333 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005334 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005335#else
danielk1977b4b47412007-08-17 15:53:36 +00005336 int seconds = (microseconds+999999)/1000000;
5337 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005338 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005339 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005340#endif
drh88f474a2006-01-02 20:00:12 +00005341}
5342
5343/*
drh6b9d6dd2008-12-03 19:34:47 +00005344** The following variable, if set to a non-zero value, is interpreted as
5345** the number of seconds since 1970 and is used to set the result of
5346** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005347*/
5348#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005349int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005350#endif
5351
5352/*
drhb7e8ea22010-05-03 14:32:30 +00005353** Find the current time (in Universal Coordinated Time). Write into *piNow
5354** the current time and date as a Julian Day number times 86_400_000. In
5355** other words, write into *piNow the number of milliseconds since the Julian
5356** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5357** proleptic Gregorian calendar.
5358**
5359** On success, return 0. Return 1 if the time and date cannot be found.
5360*/
5361static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5362 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5363#if defined(NO_GETTOD)
5364 time_t t;
5365 time(&t);
5366 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
5367#elif OS_VXWORKS
5368 struct timespec sNow;
5369 clock_gettime(CLOCK_REALTIME, &sNow);
5370 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5371#else
5372 struct timeval sNow;
5373 gettimeofday(&sNow, 0);
5374 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5375#endif
5376
5377#ifdef SQLITE_TEST
5378 if( sqlite3_current_time ){
5379 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5380 }
5381#endif
5382 UNUSED_PARAMETER(NotUsed);
5383 return 0;
5384}
5385
5386/*
drhbbd42a62004-05-22 17:41:58 +00005387** Find the current time (in Universal Coordinated Time). Write the
5388** current time and date as a Julian Day number into *prNow and
5389** return 0. Return 1 if the time and date cannot be found.
5390*/
danielk1977397d65f2008-11-19 11:35:39 +00005391static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005392 sqlite3_int64 i;
5393 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005394 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005395 return 0;
5396}
danielk1977b4b47412007-08-17 15:53:36 +00005397
drh6b9d6dd2008-12-03 19:34:47 +00005398/*
5399** We added the xGetLastError() method with the intention of providing
5400** better low-level error messages when operating-system problems come up
5401** during SQLite operation. But so far, none of that has been implemented
5402** in the core. So this routine is never called. For now, it is merely
5403** a place-holder.
5404*/
danielk1977397d65f2008-11-19 11:35:39 +00005405static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5406 UNUSED_PARAMETER(NotUsed);
5407 UNUSED_PARAMETER(NotUsed2);
5408 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005409 return 0;
5410}
5411
drhf2424c52010-04-26 00:04:55 +00005412
5413/*
drh734c9862008-11-28 15:37:20 +00005414************************ End of sqlite3_vfs methods ***************************
5415******************************************************************************/
5416
drh715ff302008-12-03 22:32:44 +00005417/******************************************************************************
5418************************** Begin Proxy Locking ********************************
5419**
5420** Proxy locking is a "uber-locking-method" in this sense: It uses the
5421** other locking methods on secondary lock files. Proxy locking is a
5422** meta-layer over top of the primitive locking implemented above. For
5423** this reason, the division that implements of proxy locking is deferred
5424** until late in the file (here) after all of the other I/O methods have
5425** been defined - so that the primitive locking methods are available
5426** as services to help with the implementation of proxy locking.
5427**
5428****
5429**
5430** The default locking schemes in SQLite use byte-range locks on the
5431** database file to coordinate safe, concurrent access by multiple readers
5432** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5433** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5434** as POSIX read & write locks over fixed set of locations (via fsctl),
5435** on AFP and SMB only exclusive byte-range locks are available via fsctl
5436** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5437** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5438** address in the shared range is taken for a SHARED lock, the entire
5439** shared range is taken for an EXCLUSIVE lock):
5440**
5441** PENDING_BYTE 0x40000000
5442** RESERVED_BYTE 0x40000001
5443** SHARED_RANGE 0x40000002 -> 0x40000200
5444**
5445** This works well on the local file system, but shows a nearly 100x
5446** slowdown in read performance on AFP because the AFP client disables
5447** the read cache when byte-range locks are present. Enabling the read
5448** cache exposes a cache coherency problem that is present on all OS X
5449** supported network file systems. NFS and AFP both observe the
5450** close-to-open semantics for ensuring cache coherency
5451** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5452** address the requirements for concurrent database access by multiple
5453** readers and writers
5454** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5455**
5456** To address the performance and cache coherency issues, proxy file locking
5457** changes the way database access is controlled by limiting access to a
5458** single host at a time and moving file locks off of the database file
5459** and onto a proxy file on the local file system.
5460**
5461**
5462** Using proxy locks
5463** -----------------
5464**
5465** C APIs
5466**
5467** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5468** <proxy_path> | ":auto:");
5469** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5470**
5471**
5472** SQL pragmas
5473**
5474** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5475** PRAGMA [database.]lock_proxy_file
5476**
5477** Specifying ":auto:" means that if there is a conch file with a matching
5478** host ID in it, the proxy path in the conch file will be used, otherwise
5479** a proxy path based on the user's temp dir
5480** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5481** actual proxy file name is generated from the name and path of the
5482** database file. For example:
5483**
5484** For database path "/Users/me/foo.db"
5485** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5486**
5487** Once a lock proxy is configured for a database connection, it can not
5488** be removed, however it may be switched to a different proxy path via
5489** the above APIs (assuming the conch file is not being held by another
5490** connection or process).
5491**
5492**
5493** How proxy locking works
5494** -----------------------
5495**
5496** Proxy file locking relies primarily on two new supporting files:
5497**
5498** * conch file to limit access to the database file to a single host
5499** at a time
5500**
5501** * proxy file to act as a proxy for the advisory locks normally
5502** taken on the database
5503**
5504** The conch file - to use a proxy file, sqlite must first "hold the conch"
5505** by taking an sqlite-style shared lock on the conch file, reading the
5506** contents and comparing the host's unique host ID (see below) and lock
5507** proxy path against the values stored in the conch. The conch file is
5508** stored in the same directory as the database file and the file name
5509** is patterned after the database file name as ".<databasename>-conch".
5510** If the conch file does not exist, or it's contents do not match the
5511** host ID and/or proxy path, then the lock is escalated to an exclusive
5512** lock and the conch file contents is updated with the host ID and proxy
5513** path and the lock is downgraded to a shared lock again. If the conch
5514** is held by another process (with a shared lock), the exclusive lock
5515** will fail and SQLITE_BUSY is returned.
5516**
5517** The proxy file - a single-byte file used for all advisory file locks
5518** normally taken on the database file. This allows for safe sharing
5519** of the database file for multiple readers and writers on the same
5520** host (the conch ensures that they all use the same local lock file).
5521**
drh715ff302008-12-03 22:32:44 +00005522** Requesting the lock proxy does not immediately take the conch, it is
5523** only taken when the first request to lock database file is made.
5524** This matches the semantics of the traditional locking behavior, where
5525** opening a connection to a database file does not take a lock on it.
5526** The shared lock and an open file descriptor are maintained until
5527** the connection to the database is closed.
5528**
5529** The proxy file and the lock file are never deleted so they only need
5530** to be created the first time they are used.
5531**
5532** Configuration options
5533** ---------------------
5534**
5535** SQLITE_PREFER_PROXY_LOCKING
5536**
5537** Database files accessed on non-local file systems are
5538** automatically configured for proxy locking, lock files are
5539** named automatically using the same logic as
5540** PRAGMA lock_proxy_file=":auto:"
5541**
5542** SQLITE_PROXY_DEBUG
5543**
5544** Enables the logging of error messages during host id file
5545** retrieval and creation
5546**
drh715ff302008-12-03 22:32:44 +00005547** LOCKPROXYDIR
5548**
5549** Overrides the default directory used for lock proxy files that
5550** are named automatically via the ":auto:" setting
5551**
5552** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5553**
5554** Permissions to use when creating a directory for storing the
5555** lock proxy files, only used when LOCKPROXYDIR is not set.
5556**
5557**
5558** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5559** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5560** force proxy locking to be used for every database file opened, and 0
5561** will force automatic proxy locking to be disabled for all database
5562** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5563** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5564*/
5565
5566/*
5567** Proxy locking is only available on MacOSX
5568*/
drhd2cb50b2009-01-09 21:41:17 +00005569#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005570
drh715ff302008-12-03 22:32:44 +00005571/*
5572** The proxyLockingContext has the path and file structures for the remote
5573** and local proxy files in it
5574*/
5575typedef struct proxyLockingContext proxyLockingContext;
5576struct proxyLockingContext {
5577 unixFile *conchFile; /* Open conch file */
5578 char *conchFilePath; /* Name of the conch file */
5579 unixFile *lockProxy; /* Open proxy lock file */
5580 char *lockProxyPath; /* Name of the proxy lock file */
5581 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005582 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005583 void *oldLockingContext; /* Original lockingcontext to restore on close */
5584 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5585};
5586
drh7ed97b92010-01-20 13:07:21 +00005587/*
5588** The proxy lock file path for the database at dbPath is written into lPath,
5589** which must point to valid, writable memory large enough for a maxLen length
5590** file path.
drh715ff302008-12-03 22:32:44 +00005591*/
drh715ff302008-12-03 22:32:44 +00005592static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5593 int len;
5594 int dbLen;
5595 int i;
5596
5597#ifdef LOCKPROXYDIR
5598 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5599#else
5600# ifdef _CS_DARWIN_USER_TEMP_DIR
5601 {
drh7ed97b92010-01-20 13:07:21 +00005602 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005603 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5604 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005605 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005606 }
drh7ed97b92010-01-20 13:07:21 +00005607 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005608 }
5609# else
5610 len = strlcpy(lPath, "/tmp/", maxLen);
5611# endif
5612#endif
5613
5614 if( lPath[len-1]!='/' ){
5615 len = strlcat(lPath, "/", maxLen);
5616 }
5617
5618 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005619 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00005620 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
5621 char c = dbPath[i];
5622 lPath[i+len] = (c=='/')?'_':c;
5623 }
5624 lPath[i+len]='\0';
5625 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005626 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005627 return SQLITE_OK;
5628}
5629
drh7ed97b92010-01-20 13:07:21 +00005630/*
5631 ** Creates the lock file and any missing directories in lockPath
5632 */
5633static int proxyCreateLockPath(const char *lockPath){
5634 int i, len;
5635 char buf[MAXPATHLEN];
5636 int start = 0;
5637
5638 assert(lockPath!=NULL);
5639 /* try to create all the intermediate directories */
5640 len = (int)strlen(lockPath);
5641 buf[0] = lockPath[0];
5642 for( i=1; i<len; i++ ){
5643 if( lockPath[i] == '/' && (i - start > 0) ){
5644 /* only mkdir if leaf dir != "." or "/" or ".." */
5645 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5646 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5647 buf[i]='\0';
5648 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5649 int err=errno;
5650 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005651 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005652 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005653 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005654 return err;
5655 }
5656 }
5657 }
5658 start=i+1;
5659 }
5660 buf[i] = lockPath[i];
5661 }
drh308c2a52010-05-14 11:30:18 +00005662 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005663 return 0;
5664}
5665
drh715ff302008-12-03 22:32:44 +00005666/*
5667** Create a new VFS file descriptor (stored in memory obtained from
5668** sqlite3_malloc) and open the file named "path" in the file descriptor.
5669**
5670** The caller is responsible not only for closing the file descriptor
5671** but also for freeing the memory associated with the file descriptor.
5672*/
drh7ed97b92010-01-20 13:07:21 +00005673static int proxyCreateUnixFile(
5674 const char *path, /* path for the new unixFile */
5675 unixFile **ppFile, /* unixFile created and returned by ref */
5676 int islockfile /* if non zero missing dirs will be created */
5677) {
5678 int fd = -1;
5679 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005680 unixFile *pNew;
5681 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005682 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005683 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005684 int terrno = 0;
5685 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005686
drh7ed97b92010-01-20 13:07:21 +00005687 /* 1. first try to open/create the file
5688 ** 2. if that fails, and this is a lock file (not-conch), try creating
5689 ** the parent directories and then try again.
5690 ** 3. if that fails, try to open the file read-only
5691 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5692 */
5693 pUnused = findReusableFd(path, openFlags);
5694 if( pUnused ){
5695 fd = pUnused->fd;
5696 }else{
5697 pUnused = sqlite3_malloc(sizeof(*pUnused));
5698 if( !pUnused ){
5699 return SQLITE_NOMEM;
5700 }
5701 }
5702 if( fd<0 ){
5703 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5704 terrno = errno;
5705 if( fd<0 && errno==ENOENT && islockfile ){
5706 if( proxyCreateLockPath(path) == SQLITE_OK ){
5707 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5708 }
5709 }
5710 }
5711 if( fd<0 ){
5712 openFlags = O_RDONLY;
5713 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5714 terrno = errno;
5715 }
5716 if( fd<0 ){
5717 if( islockfile ){
5718 return SQLITE_BUSY;
5719 }
5720 switch (terrno) {
5721 case EACCES:
5722 return SQLITE_PERM;
5723 case EIO:
5724 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5725 default:
drh9978c972010-02-23 17:36:32 +00005726 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005727 }
5728 }
5729
5730 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5731 if( pNew==NULL ){
5732 rc = SQLITE_NOMEM;
5733 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005734 }
5735 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005736 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005737 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005738 pUnused->fd = fd;
5739 pUnused->flags = openFlags;
5740 pNew->pUnused = pUnused;
5741
5742 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5743 if( rc==SQLITE_OK ){
5744 *ppFile = pNew;
5745 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005746 }
drh7ed97b92010-01-20 13:07:21 +00005747end_create_proxy:
5748 close(fd); /* silently leak fd if error, we're already in error */
5749 sqlite3_free(pNew);
5750 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005751 return rc;
5752}
5753
drh7ed97b92010-01-20 13:07:21 +00005754#ifdef SQLITE_TEST
5755/* simulate multiple hosts by creating unique hostid file paths */
5756int sqlite3_hostid_num = 0;
5757#endif
5758
5759#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5760
5761/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5762** bytes of writable memory.
5763*/
5764static int proxyGetHostID(unsigned char *pHostID, int *pError){
5765 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5766
5767 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5768 memset(pHostID, 0, PROXY_HOSTIDLEN);
5769 if( gethostuuid(pHostID, &timeout) ){
5770 int err = errno;
5771 if( pError ){
5772 *pError = err;
5773 }
5774 return SQLITE_IOERR;
5775 }
5776#ifdef SQLITE_TEST
5777 /* simulate multiple hosts by creating unique hostid file paths */
5778 if( sqlite3_hostid_num != 0){
5779 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5780 }
5781#endif
5782
5783 return SQLITE_OK;
5784}
5785
5786/* The conch file contains the header, host id and lock file path
5787 */
5788#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5789#define PROXY_HEADERLEN 1 /* conch file header length */
5790#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5791#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5792
5793/*
5794** Takes an open conch file, copies the contents to a new path and then moves
5795** it back. The newly created file's file descriptor is assigned to the
5796** conch file structure and finally the original conch file descriptor is
5797** closed. Returns zero if successful.
5798*/
5799static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5800 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5801 unixFile *conchFile = pCtx->conchFile;
5802 char tPath[MAXPATHLEN];
5803 char buf[PROXY_MAXCONCHLEN];
5804 char *cPath = pCtx->conchFilePath;
5805 size_t readLen = 0;
5806 size_t pathLen = 0;
5807 char errmsg[64] = "";
5808 int fd = -1;
5809 int rc = -1;
5810
5811 /* create a new path by replace the trailing '-conch' with '-break' */
5812 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5813 if( pathLen>MAXPATHLEN || pathLen<6 ||
5814 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5815 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5816 goto end_breaklock;
5817 }
5818 /* read the conch content */
5819 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5820 if( readLen<PROXY_PATHINDEX ){
5821 sprintf(errmsg, "read error (len %d)", (int)readLen);
5822 goto end_breaklock;
5823 }
5824 /* write it out to the temporary break file */
5825 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5826 if( fd<0 ){
5827 sprintf(errmsg, "create failed (%d)", errno);
5828 goto end_breaklock;
5829 }
5830 if( pwrite(fd, buf, readLen, 0) != readLen ){
5831 sprintf(errmsg, "write failed (%d)", errno);
5832 goto end_breaklock;
5833 }
5834 if( rename(tPath, cPath) ){
5835 sprintf(errmsg, "rename failed (%d)", errno);
5836 goto end_breaklock;
5837 }
5838 rc = 0;
5839 fprintf(stderr, "broke stale lock on %s\n", cPath);
5840 close(conchFile->h);
5841 conchFile->h = fd;
5842 conchFile->openFlags = O_RDWR | O_CREAT;
5843
5844end_breaklock:
5845 if( rc ){
5846 if( fd>=0 ){
5847 unlink(tPath);
5848 close(fd);
5849 }
5850 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5851 }
5852 return rc;
5853}
5854
5855/* Take the requested lock on the conch file and break a stale lock if the
5856** host id matches.
5857*/
5858static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5859 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5860 unixFile *conchFile = pCtx->conchFile;
5861 int rc = SQLITE_OK;
5862 int nTries = 0;
5863 struct timespec conchModTime;
5864
5865 do {
5866 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5867 nTries ++;
5868 if( rc==SQLITE_BUSY ){
5869 /* If the lock failed (busy):
5870 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5871 * 2nd try: fail if the mod time changed or host id is different, wait
5872 * 10 sec and try again
5873 * 3rd try: break the lock unless the mod time has changed.
5874 */
5875 struct stat buf;
5876 if( fstat(conchFile->h, &buf) ){
5877 pFile->lastErrno = errno;
5878 return SQLITE_IOERR_LOCK;
5879 }
5880
5881 if( nTries==1 ){
5882 conchModTime = buf.st_mtimespec;
5883 usleep(500000); /* wait 0.5 sec and try the lock again*/
5884 continue;
5885 }
5886
5887 assert( nTries>1 );
5888 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5889 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5890 return SQLITE_BUSY;
5891 }
5892
5893 if( nTries==2 ){
5894 char tBuf[PROXY_MAXCONCHLEN];
5895 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5896 if( len<0 ){
5897 pFile->lastErrno = errno;
5898 return SQLITE_IOERR_LOCK;
5899 }
5900 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5901 /* don't break the lock if the host id doesn't match */
5902 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5903 return SQLITE_BUSY;
5904 }
5905 }else{
5906 /* don't break the lock on short read or a version mismatch */
5907 return SQLITE_BUSY;
5908 }
5909 usleep(10000000); /* wait 10 sec and try the lock again */
5910 continue;
5911 }
5912
5913 assert( nTries==3 );
5914 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5915 rc = SQLITE_OK;
5916 if( lockType==EXCLUSIVE_LOCK ){
5917 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5918 }
5919 if( !rc ){
5920 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5921 }
5922 }
5923 }
5924 } while( rc==SQLITE_BUSY && nTries<3 );
5925
5926 return rc;
5927}
5928
5929/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005930** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5931** lockPath means that the lockPath in the conch file will be used if the
5932** host IDs match, or a new lock path will be generated automatically
5933** and written to the conch file.
5934*/
5935static int proxyTakeConch(unixFile *pFile){
5936 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5937
drh7ed97b92010-01-20 13:07:21 +00005938 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005939 return SQLITE_OK;
5940 }else{
5941 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005942 uuid_t myHostID;
5943 int pError = 0;
5944 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005945 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005946 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005947 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005948 int createConch = 0;
5949 int hostIdMatch = 0;
5950 int readLen = 0;
5951 int tryOldLockPath = 0;
5952 int forceNewLockPath = 0;
5953
drh308c2a52010-05-14 11:30:18 +00005954 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5955 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005956
drh7ed97b92010-01-20 13:07:21 +00005957 rc = proxyGetHostID(myHostID, &pError);
5958 if( (rc&0xff)==SQLITE_IOERR ){
5959 pFile->lastErrno = pError;
5960 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005961 }
drh7ed97b92010-01-20 13:07:21 +00005962 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005963 if( rc!=SQLITE_OK ){
5964 goto end_takeconch;
5965 }
drh7ed97b92010-01-20 13:07:21 +00005966 /* read the existing conch file */
5967 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5968 if( readLen<0 ){
5969 /* I/O error: lastErrno set by seekAndRead */
5970 pFile->lastErrno = conchFile->lastErrno;
5971 rc = SQLITE_IOERR_READ;
5972 goto end_takeconch;
5973 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5974 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5975 /* a short read or version format mismatch means we need to create a new
5976 ** conch file.
5977 */
5978 createConch = 1;
5979 }
5980 /* if the host id matches and the lock path already exists in the conch
5981 ** we'll try to use the path there, if we can't open that path, we'll
5982 ** retry with a new auto-generated path
5983 */
5984 do { /* in case we need to try again for an :auto: named lock file */
5985
5986 if( !createConch && !forceNewLockPath ){
5987 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5988 PROXY_HOSTIDLEN);
5989 /* if the conch has data compare the contents */
5990 if( !pCtx->lockProxyPath ){
5991 /* for auto-named local lock file, just check the host ID and we'll
5992 ** use the local lock file path that's already in there
5993 */
5994 if( hostIdMatch ){
5995 size_t pathLen = (readLen - PROXY_PATHINDEX);
5996
5997 if( pathLen>=MAXPATHLEN ){
5998 pathLen=MAXPATHLEN-1;
5999 }
6000 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6001 lockPath[pathLen] = 0;
6002 tempLockPath = lockPath;
6003 tryOldLockPath = 1;
6004 /* create a copy of the lock path if the conch is taken */
6005 goto end_takeconch;
6006 }
6007 }else if( hostIdMatch
6008 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6009 readLen-PROXY_PATHINDEX)
6010 ){
6011 /* conch host and lock path match */
6012 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006013 }
drh7ed97b92010-01-20 13:07:21 +00006014 }
6015
6016 /* if the conch isn't writable and doesn't match, we can't take it */
6017 if( (conchFile->openFlags&O_RDWR) == 0 ){
6018 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006019 goto end_takeconch;
6020 }
drh7ed97b92010-01-20 13:07:21 +00006021
6022 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006023 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006024 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6025 tempLockPath = lockPath;
6026 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006027 }
drh7ed97b92010-01-20 13:07:21 +00006028
6029 /* update conch with host and path (this will fail if other process
6030 ** has a shared lock already), if the host id matches, use the big
6031 ** stick.
drh715ff302008-12-03 22:32:44 +00006032 */
drh7ed97b92010-01-20 13:07:21 +00006033 futimes(conchFile->h, NULL);
6034 if( hostIdMatch && !createConch ){
drh308c2a52010-05-14 11:30:18 +00006035 if( conchFile->pLock && conchFile->pLock->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006036 /* We are trying for an exclusive lock but another thread in this
6037 ** same process is still holding a shared lock. */
6038 rc = SQLITE_BUSY;
6039 } else {
6040 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006041 }
drh715ff302008-12-03 22:32:44 +00006042 }else{
drh7ed97b92010-01-20 13:07:21 +00006043 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006044 }
drh7ed97b92010-01-20 13:07:21 +00006045 if( rc==SQLITE_OK ){
6046 char writeBuffer[PROXY_MAXCONCHLEN];
6047 int writeSize = 0;
6048
6049 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6050 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6051 if( pCtx->lockProxyPath!=NULL ){
6052 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6053 }else{
6054 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6055 }
6056 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
6057 ftruncate(conchFile->h, writeSize);
6058 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6059 fsync(conchFile->h);
6060 /* If we created a new conch file (not just updated the contents of a
6061 ** valid conch file), try to match the permissions of the database
6062 */
6063 if( rc==SQLITE_OK && createConch ){
6064 struct stat buf;
6065 int err = fstat(pFile->h, &buf);
6066 if( err==0 ){
6067 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6068 S_IROTH|S_IWOTH);
6069 /* try to match the database file R/W permissions, ignore failure */
6070#ifndef SQLITE_PROXY_DEBUG
6071 fchmod(conchFile->h, cmode);
6072#else
6073 if( fchmod(conchFile->h, cmode)!=0 ){
6074 int code = errno;
6075 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6076 cmode, code, strerror(code));
6077 } else {
6078 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6079 }
6080 }else{
6081 int code = errno;
6082 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6083 err, code, strerror(code));
6084#endif
6085 }
drh715ff302008-12-03 22:32:44 +00006086 }
6087 }
drh7ed97b92010-01-20 13:07:21 +00006088 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6089
6090 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006091 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006092 if( rc==SQLITE_OK && pFile->openFlags ){
6093 if( pFile->h>=0 ){
6094#ifdef STRICT_CLOSE_ERROR
6095 if( close(pFile->h) ){
6096 pFile->lastErrno = errno;
6097 return SQLITE_IOERR_CLOSE;
6098 }
6099#else
6100 close(pFile->h); /* silently leak fd if fail */
6101#endif
6102 }
6103 pFile->h = -1;
6104 int fd = open(pCtx->dbPath, pFile->openFlags,
6105 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006106 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006107 if( fd>=0 ){
6108 pFile->h = fd;
6109 }else{
drh9978c972010-02-23 17:36:32 +00006110 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006111 during locking */
6112 }
6113 }
6114 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6115 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6116 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6117 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6118 /* we couldn't create the proxy lock file with the old lock file path
6119 ** so try again via auto-naming
6120 */
6121 forceNewLockPath = 1;
6122 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006123 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006124 }
6125 }
6126 if( rc==SQLITE_OK ){
6127 /* Need to make a copy of path if we extracted the value
6128 ** from the conch file or the path was allocated on the stack
6129 */
6130 if( tempLockPath ){
6131 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6132 if( !pCtx->lockProxyPath ){
6133 rc = SQLITE_NOMEM;
6134 }
6135 }
6136 }
6137 if( rc==SQLITE_OK ){
6138 pCtx->conchHeld = 1;
6139
6140 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6141 afpLockingContext *afpCtx;
6142 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6143 afpCtx->dbPath = pCtx->lockProxyPath;
6144 }
6145 } else {
6146 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6147 }
drh308c2a52010-05-14 11:30:18 +00006148 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6149 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006150 return rc;
drh308c2a52010-05-14 11:30:18 +00006151 } while (1); /* in case we need to retry the :auto: lock file -
6152 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006153 }
6154}
6155
6156/*
6157** If pFile holds a lock on a conch file, then release that lock.
6158*/
6159static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006160 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006161 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6162 unixFile *conchFile; /* Name of the conch file */
6163
6164 pCtx = (proxyLockingContext *)pFile->lockingContext;
6165 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006166 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006167 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006168 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006169 if( pCtx->conchHeld>0 ){
6170 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6171 }
drh715ff302008-12-03 22:32:44 +00006172 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006173 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6174 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006175 return rc;
6176}
6177
6178/*
6179** Given the name of a database file, compute the name of its conch file.
6180** Store the conch filename in memory obtained from sqlite3_malloc().
6181** Make *pConchPath point to the new name. Return SQLITE_OK on success
6182** or SQLITE_NOMEM if unable to obtain memory.
6183**
6184** The caller is responsible for ensuring that the allocated memory
6185** space is eventually freed.
6186**
6187** *pConchPath is set to NULL if a memory allocation error occurs.
6188*/
6189static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6190 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006191 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006192 char *conchPath; /* buffer in which to construct conch name */
6193
6194 /* Allocate space for the conch filename and initialize the name to
6195 ** the name of the original database file. */
6196 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6197 if( conchPath==0 ){
6198 return SQLITE_NOMEM;
6199 }
6200 memcpy(conchPath, dbPath, len+1);
6201
6202 /* now insert a "." before the last / character */
6203 for( i=(len-1); i>=0; i-- ){
6204 if( conchPath[i]=='/' ){
6205 i++;
6206 break;
6207 }
6208 }
6209 conchPath[i]='.';
6210 while ( i<len ){
6211 conchPath[i+1]=dbPath[i];
6212 i++;
6213 }
6214
6215 /* append the "-conch" suffix to the file */
6216 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006217 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006218
6219 return SQLITE_OK;
6220}
6221
6222
6223/* Takes a fully configured proxy locking-style unix file and switches
6224** the local lock file path
6225*/
6226static int switchLockProxyPath(unixFile *pFile, const char *path) {
6227 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6228 char *oldPath = pCtx->lockProxyPath;
6229 int rc = SQLITE_OK;
6230
drh308c2a52010-05-14 11:30:18 +00006231 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006232 return SQLITE_BUSY;
6233 }
6234
6235 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6236 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6237 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6238 return SQLITE_OK;
6239 }else{
6240 unixFile *lockProxy = pCtx->lockProxy;
6241 pCtx->lockProxy=NULL;
6242 pCtx->conchHeld = 0;
6243 if( lockProxy!=NULL ){
6244 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6245 if( rc ) return rc;
6246 sqlite3_free(lockProxy);
6247 }
6248 sqlite3_free(oldPath);
6249 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6250 }
6251
6252 return rc;
6253}
6254
6255/*
6256** pFile is a file that has been opened by a prior xOpen call. dbPath
6257** is a string buffer at least MAXPATHLEN+1 characters in size.
6258**
6259** This routine find the filename associated with pFile and writes it
6260** int dbPath.
6261*/
6262static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006263#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006264 if( pFile->pMethod == &afpIoMethods ){
6265 /* afp style keeps a reference to the db path in the filePath field
6266 ** of the struct */
drhea678832008-12-10 19:26:22 +00006267 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006268 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6269 } else
drh715ff302008-12-03 22:32:44 +00006270#endif
6271 if( pFile->pMethod == &dotlockIoMethods ){
6272 /* dot lock style uses the locking context to store the dot lock
6273 ** file path */
6274 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6275 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6276 }else{
6277 /* all other styles use the locking context to store the db file path */
6278 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006279 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006280 }
6281 return SQLITE_OK;
6282}
6283
6284/*
6285** Takes an already filled in unix file and alters it so all file locking
6286** will be performed on the local proxy lock file. The following fields
6287** are preserved in the locking context so that they can be restored and
6288** the unix structure properly cleaned up at close time:
6289** ->lockingContext
6290** ->pMethod
6291*/
6292static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6293 proxyLockingContext *pCtx;
6294 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6295 char *lockPath=NULL;
6296 int rc = SQLITE_OK;
6297
drh308c2a52010-05-14 11:30:18 +00006298 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006299 return SQLITE_BUSY;
6300 }
6301 proxyGetDbPathForUnixFile(pFile, dbPath);
6302 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6303 lockPath=NULL;
6304 }else{
6305 lockPath=(char *)path;
6306 }
6307
drh308c2a52010-05-14 11:30:18 +00006308 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6309 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006310
6311 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6312 if( pCtx==0 ){
6313 return SQLITE_NOMEM;
6314 }
6315 memset(pCtx, 0, sizeof(*pCtx));
6316
6317 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6318 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006319 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6320 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6321 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6322 ** (c) the file system is read-only, then enable no-locking access.
6323 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6324 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6325 */
6326 struct statfs fsInfo;
6327 struct stat conchInfo;
6328 int goLockless = 0;
6329
6330 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6331 int err = errno;
6332 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6333 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6334 }
6335 }
6336 if( goLockless ){
6337 pCtx->conchHeld = -1; /* read only FS/ lockless */
6338 rc = SQLITE_OK;
6339 }
6340 }
drh715ff302008-12-03 22:32:44 +00006341 }
6342 if( rc==SQLITE_OK && lockPath ){
6343 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6344 }
6345
6346 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006347 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6348 if( pCtx->dbPath==NULL ){
6349 rc = SQLITE_NOMEM;
6350 }
6351 }
6352 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006353 /* all memory is allocated, proxys are created and assigned,
6354 ** switch the locking context and pMethod then return.
6355 */
drh715ff302008-12-03 22:32:44 +00006356 pCtx->oldLockingContext = pFile->lockingContext;
6357 pFile->lockingContext = pCtx;
6358 pCtx->pOldMethod = pFile->pMethod;
6359 pFile->pMethod = &proxyIoMethods;
6360 }else{
6361 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006362 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006363 sqlite3_free(pCtx->conchFile);
6364 }
drh7ed97b92010-01-20 13:07:21 +00006365 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006366 sqlite3_free(pCtx->conchFilePath);
6367 sqlite3_free(pCtx);
6368 }
drh308c2a52010-05-14 11:30:18 +00006369 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6370 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006371 return rc;
6372}
6373
6374
6375/*
6376** This routine handles sqlite3_file_control() calls that are specific
6377** to proxy locking.
6378*/
6379static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6380 switch( op ){
6381 case SQLITE_GET_LOCKPROXYFILE: {
6382 unixFile *pFile = (unixFile*)id;
6383 if( pFile->pMethod == &proxyIoMethods ){
6384 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6385 proxyTakeConch(pFile);
6386 if( pCtx->lockProxyPath ){
6387 *(const char **)pArg = pCtx->lockProxyPath;
6388 }else{
6389 *(const char **)pArg = ":auto: (not held)";
6390 }
6391 } else {
6392 *(const char **)pArg = NULL;
6393 }
6394 return SQLITE_OK;
6395 }
6396 case SQLITE_SET_LOCKPROXYFILE: {
6397 unixFile *pFile = (unixFile*)id;
6398 int rc = SQLITE_OK;
6399 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6400 if( pArg==NULL || (const char *)pArg==0 ){
6401 if( isProxyStyle ){
6402 /* turn off proxy locking - not supported */
6403 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6404 }else{
6405 /* turn off proxy locking - already off - NOOP */
6406 rc = SQLITE_OK;
6407 }
6408 }else{
6409 const char *proxyPath = (const char *)pArg;
6410 if( isProxyStyle ){
6411 proxyLockingContext *pCtx =
6412 (proxyLockingContext*)pFile->lockingContext;
6413 if( !strcmp(pArg, ":auto:")
6414 || (pCtx->lockProxyPath &&
6415 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6416 ){
6417 rc = SQLITE_OK;
6418 }else{
6419 rc = switchLockProxyPath(pFile, proxyPath);
6420 }
6421 }else{
6422 /* turn on proxy file locking */
6423 rc = proxyTransformUnixFile(pFile, proxyPath);
6424 }
6425 }
6426 return rc;
6427 }
6428 default: {
6429 assert( 0 ); /* The call assures that only valid opcodes are sent */
6430 }
6431 }
6432 /*NOTREACHED*/
6433 return SQLITE_ERROR;
6434}
6435
6436/*
6437** Within this division (the proxying locking implementation) the procedures
6438** above this point are all utilities. The lock-related methods of the
6439** proxy-locking sqlite3_io_method object follow.
6440*/
6441
6442
6443/*
6444** This routine checks if there is a RESERVED lock held on the specified
6445** file by this or any other process. If such a lock is held, set *pResOut
6446** to a non-zero value otherwise *pResOut is set to zero. The return value
6447** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6448*/
6449static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6450 unixFile *pFile = (unixFile*)id;
6451 int rc = proxyTakeConch(pFile);
6452 if( rc==SQLITE_OK ){
6453 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006454 if( pCtx->conchHeld>0 ){
6455 unixFile *proxy = pCtx->lockProxy;
6456 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6457 }else{ /* conchHeld < 0 is lockless */
6458 pResOut=0;
6459 }
drh715ff302008-12-03 22:32:44 +00006460 }
6461 return rc;
6462}
6463
6464/*
drh308c2a52010-05-14 11:30:18 +00006465** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006466** of the following:
6467**
6468** (1) SHARED_LOCK
6469** (2) RESERVED_LOCK
6470** (3) PENDING_LOCK
6471** (4) EXCLUSIVE_LOCK
6472**
6473** Sometimes when requesting one lock state, additional lock states
6474** are inserted in between. The locking might fail on one of the later
6475** transitions leaving the lock state different from what it started but
6476** still short of its goal. The following chart shows the allowed
6477** transitions and the inserted intermediate states:
6478**
6479** UNLOCKED -> SHARED
6480** SHARED -> RESERVED
6481** SHARED -> (PENDING) -> EXCLUSIVE
6482** RESERVED -> (PENDING) -> EXCLUSIVE
6483** PENDING -> EXCLUSIVE
6484**
6485** This routine will only increase a lock. Use the sqlite3OsUnlock()
6486** routine to lower a locking level.
6487*/
drh308c2a52010-05-14 11:30:18 +00006488static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006489 unixFile *pFile = (unixFile*)id;
6490 int rc = proxyTakeConch(pFile);
6491 if( rc==SQLITE_OK ){
6492 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006493 if( pCtx->conchHeld>0 ){
6494 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006495 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6496 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006497 }else{
6498 /* conchHeld < 0 is lockless */
6499 }
drh715ff302008-12-03 22:32:44 +00006500 }
6501 return rc;
6502}
6503
6504
6505/*
drh308c2a52010-05-14 11:30:18 +00006506** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006507** must be either NO_LOCK or SHARED_LOCK.
6508**
6509** If the locking level of the file descriptor is already at or below
6510** the requested locking level, this routine is a no-op.
6511*/
drh308c2a52010-05-14 11:30:18 +00006512static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006513 unixFile *pFile = (unixFile*)id;
6514 int rc = proxyTakeConch(pFile);
6515 if( rc==SQLITE_OK ){
6516 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006517 if( pCtx->conchHeld>0 ){
6518 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006519 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6520 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006521 }else{
6522 /* conchHeld < 0 is lockless */
6523 }
drh715ff302008-12-03 22:32:44 +00006524 }
6525 return rc;
6526}
6527
6528/*
6529** Close a file that uses proxy locks.
6530*/
6531static int proxyClose(sqlite3_file *id) {
6532 if( id ){
6533 unixFile *pFile = (unixFile*)id;
6534 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6535 unixFile *lockProxy = pCtx->lockProxy;
6536 unixFile *conchFile = pCtx->conchFile;
6537 int rc = SQLITE_OK;
6538
6539 if( lockProxy ){
6540 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6541 if( rc ) return rc;
6542 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6543 if( rc ) return rc;
6544 sqlite3_free(lockProxy);
6545 pCtx->lockProxy = 0;
6546 }
6547 if( conchFile ){
6548 if( pCtx->conchHeld ){
6549 rc = proxyReleaseConch(pFile);
6550 if( rc ) return rc;
6551 }
6552 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6553 if( rc ) return rc;
6554 sqlite3_free(conchFile);
6555 }
6556 sqlite3_free(pCtx->lockProxyPath);
6557 sqlite3_free(pCtx->conchFilePath);
6558 sqlite3_free(pCtx->dbPath);
6559 /* restore the original locking context and pMethod then close it */
6560 pFile->lockingContext = pCtx->oldLockingContext;
6561 pFile->pMethod = pCtx->pOldMethod;
6562 sqlite3_free(pCtx);
6563 return pFile->pMethod->xClose(id);
6564 }
6565 return SQLITE_OK;
6566}
6567
6568
6569
drhd2cb50b2009-01-09 21:41:17 +00006570#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006571/*
6572** The proxy locking style is intended for use with AFP filesystems.
6573** And since AFP is only supported on MacOSX, the proxy locking is also
6574** restricted to MacOSX.
6575**
6576**
6577******************* End of the proxy lock implementation **********************
6578******************************************************************************/
6579
drh734c9862008-11-28 15:37:20 +00006580/*
danielk1977e339d652008-06-28 11:23:00 +00006581** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006582**
6583** This routine registers all VFS implementations for unix-like operating
6584** systems. This routine, and the sqlite3_os_end() routine that follows,
6585** should be the only routines in this file that are visible from other
6586** files.
drh6b9d6dd2008-12-03 19:34:47 +00006587**
6588** This routine is called once during SQLite initialization and by a
6589** single thread. The memory allocation and mutex subsystems have not
6590** necessarily been initialized when this routine is called, and so they
6591** should not be used.
drh153c62c2007-08-24 03:51:33 +00006592*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006593int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006594 /*
6595 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006596 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6597 ** to the "finder" function. (pAppData is a pointer to a pointer because
6598 ** silly C90 rules prohibit a void* from being cast to a function pointer
6599 ** and so we have to go through the intermediate pointer to avoid problems
6600 ** when compiling with -pedantic-errors on GCC.)
6601 **
6602 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006603 ** finder-function. The finder-function returns a pointer to the
6604 ** sqlite_io_methods object that implements the desired locking
6605 ** behaviors. See the division above that contains the IOMETHODS
6606 ** macro for addition information on finder-functions.
6607 **
6608 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6609 ** object. But the "autolockIoFinder" available on MacOSX does a little
6610 ** more than that; it looks at the filesystem type that hosts the
6611 ** database file and tries to choose an locking method appropriate for
6612 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006613 */
drh7708e972008-11-29 00:56:52 +00006614 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006615 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006616 sizeof(unixFile), /* szOsFile */ \
6617 MAX_PATHNAME, /* mxPathname */ \
6618 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006619 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006620 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006621 unixOpen, /* xOpen */ \
6622 unixDelete, /* xDelete */ \
6623 unixAccess, /* xAccess */ \
6624 unixFullPathname, /* xFullPathname */ \
6625 unixDlOpen, /* xDlOpen */ \
6626 unixDlError, /* xDlError */ \
6627 unixDlSym, /* xDlSym */ \
6628 unixDlClose, /* xDlClose */ \
6629 unixRandomness, /* xRandomness */ \
6630 unixSleep, /* xSleep */ \
6631 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006632 unixGetLastError, /* xGetLastError */ \
drhf2424c52010-04-26 00:04:55 +00006633 0, /* xRename */ \
drhb7e8ea22010-05-03 14:32:30 +00006634 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006635 }
6636
drh6b9d6dd2008-12-03 19:34:47 +00006637 /*
6638 ** All default VFSes for unix are contained in the following array.
6639 **
6640 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6641 ** by the SQLite core when the VFS is registered. So the following
6642 ** array cannot be const.
6643 */
danielk1977e339d652008-06-28 11:23:00 +00006644 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006645#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006646 UNIXVFS("unix", autolockIoFinder ),
6647#else
6648 UNIXVFS("unix", posixIoFinder ),
6649#endif
6650 UNIXVFS("unix-none", nolockIoFinder ),
6651 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006652#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006653 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006654#endif
6655#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006656 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006657#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006658 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006659#endif
chw78a13182009-04-07 05:35:03 +00006660#endif
drhd2cb50b2009-01-09 21:41:17 +00006661#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006662 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006663 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006664 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006665#endif
drh153c62c2007-08-24 03:51:33 +00006666 };
drh6b9d6dd2008-12-03 19:34:47 +00006667 unsigned int i; /* Loop counter */
6668
6669 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006670 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006671 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006672 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006673 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006674}
danielk1977e339d652008-06-28 11:23:00 +00006675
6676/*
drh6b9d6dd2008-12-03 19:34:47 +00006677** Shutdown the operating system interface.
6678**
6679** Some operating systems might need to do some cleanup in this routine,
6680** to release dynamically allocated objects. But not on unix.
6681** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006682*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006683int sqlite3_os_end(void){
6684 return SQLITE_OK;
6685}
drhdce8bdb2007-08-16 13:01:44 +00006686
danielk197729bafea2008-06-26 10:41:19 +00006687#endif /* SQLITE_OS_UNIX */