blob: ff967ca8b96aa0b14fc1a971e9a1e89020200ff1 [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 */
206 unsigned char locktype; /* The type of lock held on this fd */
207 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*/
327static const char *locktypeName(int locktype){
328 switch( locktype ){
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 */
764 int cnt; /* Number of SHARED locks held */
765 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
766 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;
1054 pLock->cnt = 0;
1055 pLock->locktype = 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 */
1118 OSTRACE1("No-transfer, same thread\n");
1119 return SQLITE_OK;
1120 }
1121 if( pFile->locktype!=NO_LOCK ){
1122 /* 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 }
1125 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1126 pFile->h, pFile->tid, hSelf);
1127 pFile->tid = hSelf;
1128 if (pFile->pLock != NULL) {
1129 releaseLockInfo(pFile->pLock);
1130 rc = findLockInfo(pFile, &pFile->pLock, 0);
1131 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1132 locktypeName(pFile->locktype),
1133 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1134 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 */
drh054889e2005-11-30 03:20:31 +00001162 if( pFile->pLock->locktype>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();
drh476bda72009-12-04 14:25:18 +00001186 OSTRACE4("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/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001193** Lock the file with the lock specified by parameter locktype - one
1194** 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*/
danielk197762079062007-08-15 17:08:46 +00001216static int unixLock(sqlite3_file *id, int locktype){
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 );
drh476bda72009-12-04 14:25:18 +00001263 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001264 locktypeName(locktype), locktypeName(pFile->locktype),
1265 locktypeName(pLock->locktype), pLock->cnt , 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 */
drh054889e2005-11-30 03:20:31 +00001271 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00001272 OSTRACE3("LOCK %d %s ok (already held) (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001273 locktypeName(locktype));
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 */
drh054889e2005-11-30 03:20:31 +00001282 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001283 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001284 assert( locktype!=RESERVED_LOCK || pFile->locktype==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 */
drh054889e2005-11-30 03:20:31 +00001302 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001303 (pLock->locktype>=PENDING_LOCK || locktype>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 */
1313 if( locktype==SHARED_LOCK &&
1314 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1315 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001316 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001317 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001318 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001319 pLock->cnt++;
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;
drh3cde3bb2004-06-12 02:17:14 +00001331 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001332 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001333 ){
danielk1977489468c2004-06-28 08:25:47 +00001334 lock.l_type = (locktype==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 */
1351 if( locktype==SHARED_LOCK ){
1352 assert( pLock->cnt==0 );
1353 assert( pLock->locktype==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{
drh054889e2005-11-30 03:20:31 +00001382 pFile->locktype = SHARED_LOCK;
1383 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001384 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001385 }
drh3cde3bb2004-06-12 02:17:14 +00001386 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1387 /* 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 */
drh054889e2005-11-30 03:20:31 +00001395 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 lock.l_type = F_WRLCK;
1397 switch( locktype ){
1398 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
1426 && pFile->locktype<=SHARED_LOCK
1427 && locktype==RESERVED_LOCK
1428 ){
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 ){
drh054889e2005-11-30 03:20:31 +00001437 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001438 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001439 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001440 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001441 pLock->locktype = 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();
drh476bda72009-12-04 14:25:18 +00001446 OSTRACE4("LOCK %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001447 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/*
drh054889e2005-11-30 03:20:31 +00001495** Lower the locking level on file descriptor pFile to locktype. locktype
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*/
drh7ed97b92010-01-20 13:07:21 +00001507static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
1508 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 );
drh476bda72009-12-04 14:25:18 +00001516 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001517 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001518
1519 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001520 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001521 return SQLITE_OK;
1522 }
drhf1a221e2006-01-15 17:27:17 +00001523 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00001524 return SQLITE_MISUSE_BKPT;
drhf1a221e2006-01-15 17:27:17 +00001525 }
drh6c7d5c52008-11-21 20:32:33 +00001526 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001527 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001528 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001529 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001530 if( pFile->locktype>SHARED_LOCK ){
1531 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001532 SimulateIOErrorBenign(1);
1533 SimulateIOError( h=(-1) )
1534 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001535
1536#ifndef NDEBUG
1537 /* When reducing a lock such that other processes can start
1538 ** reading the database file again, make sure that the
1539 ** transaction counter was updated if any part of the database
1540 ** file changed. If the transaction counter is not updated,
1541 ** other connections to the same file might not realize that
1542 ** the file has changed and hence might not know to flush their
1543 ** cache. The use of a stale cache can lead to database corruption.
1544 */
dan7c246102010-04-12 19:00:29 +00001545#if 0
drh8f941bc2009-01-14 23:03:40 +00001546 assert( pFile->inNormalWrite==0
1547 || pFile->dbUpdate==0
1548 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001549#endif
drh8f941bc2009-01-14 23:03:40 +00001550 pFile->inNormalWrite = 0;
1551#endif
1552
drh7ed97b92010-01-20 13:07:21 +00001553 /* downgrading to a shared lock on NFS involves clearing the write lock
1554 ** before establishing the readlock - to avoid a race condition we downgrade
1555 ** the lock in 2 blocks, so that part of the range will be covered by a
1556 ** write lock until the rest is covered by a read lock:
1557 ** 1: [WWWWW]
1558 ** 2: [....W]
1559 ** 3: [RRRRW]
1560 ** 4: [RRRR.]
1561 */
drh9c105bb2004-10-02 20:38:28 +00001562 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001563 if( handleNFSUnlock ){
1564 off_t divSize = SHARED_SIZE - 1;
1565
1566 lock.l_type = F_UNLCK;
1567 lock.l_whence = SEEK_SET;
1568 lock.l_start = SHARED_FIRST;
1569 lock.l_len = divSize;
1570 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001571 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001572 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1573 if( IS_LOCK_ERROR(rc) ){
1574 pFile->lastErrno = tErrno;
1575 }
1576 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001577 }
drh7ed97b92010-01-20 13:07:21 +00001578 lock.l_type = F_RDLCK;
1579 lock.l_whence = SEEK_SET;
1580 lock.l_start = SHARED_FIRST;
1581 lock.l_len = divSize;
1582 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001583 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001584 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1585 if( IS_LOCK_ERROR(rc) ){
1586 pFile->lastErrno = tErrno;
1587 }
1588 goto end_unlock;
1589 }
1590 lock.l_type = F_UNLCK;
1591 lock.l_whence = SEEK_SET;
1592 lock.l_start = SHARED_FIRST+divSize;
1593 lock.l_len = SHARED_SIZE-divSize;
1594 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001595 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001596 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1597 if( IS_LOCK_ERROR(rc) ){
1598 pFile->lastErrno = tErrno;
1599 }
1600 goto end_unlock;
1601 }
1602 }else{
1603 lock.l_type = F_RDLCK;
1604 lock.l_whence = SEEK_SET;
1605 lock.l_start = SHARED_FIRST;
1606 lock.l_len = SHARED_SIZE;
1607 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001608 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001609 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1610 if( IS_LOCK_ERROR(rc) ){
1611 pFile->lastErrno = tErrno;
1612 }
1613 goto end_unlock;
1614 }
drh9c105bb2004-10-02 20:38:28 +00001615 }
1616 }
drhbbd42a62004-05-22 17:41:58 +00001617 lock.l_type = F_UNLCK;
1618 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001619 lock.l_start = PENDING_BYTE;
1620 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001621 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001622 pLock->locktype = SHARED_LOCK;
1623 }else{
drh0c2694b2009-09-03 16:23:44 +00001624 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001625 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1626 if( IS_LOCK_ERROR(rc) ){
1627 pFile->lastErrno = tErrno;
1628 }
drhcd731cf2009-03-28 23:23:02 +00001629 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001630 }
drhbbd42a62004-05-22 17:41:58 +00001631 }
drha6abd042004-06-09 17:37:22 +00001632 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001633 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001634
drha6abd042004-06-09 17:37:22 +00001635 /* Decrement the shared lock counter. Release the lock using an
1636 ** OS call only when all threads in this same process have released
1637 ** the lock.
1638 */
1639 pLock->cnt--;
1640 if( pLock->cnt==0 ){
1641 lock.l_type = F_UNLCK;
1642 lock.l_whence = SEEK_SET;
1643 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001644 SimulateIOErrorBenign(1);
1645 SimulateIOError( h=(-1) )
1646 SimulateIOErrorBenign(0);
1647 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001648 pLock->locktype = NO_LOCK;
1649 }else{
drh0c2694b2009-09-03 16:23:44 +00001650 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001651 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001652 if( IS_LOCK_ERROR(rc) ){
1653 pFile->lastErrno = tErrno;
1654 }
drhf48f9ca2009-03-28 23:47:10 +00001655 pLock->locktype = NO_LOCK;
1656 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001657 }
drha6abd042004-06-09 17:37:22 +00001658 }
1659
drhbbd42a62004-05-22 17:41:58 +00001660 /* Decrement the count of locks against this same file. When the
1661 ** count reaches zero, close any other file descriptors whose close
1662 ** was deferred because of outstanding locks.
1663 */
danielk197764a54c52009-03-30 07:39:35 +00001664 pOpen = pFile->pOpen;
1665 pOpen->nLock--;
1666 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001667 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001668 int rc2 = closePendingFds(pFile);
1669 if( rc==SQLITE_OK ){
1670 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001671 }
drhbbd42a62004-05-22 17:41:58 +00001672 }
1673 }
aswift5b1a2562008-08-22 00:22:35 +00001674
1675end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001676 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001677 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001678 return rc;
drhbbd42a62004-05-22 17:41:58 +00001679}
1680
1681/*
drh7ed97b92010-01-20 13:07:21 +00001682** Lower the locking level on file descriptor pFile to locktype. locktype
1683** must be either NO_LOCK or SHARED_LOCK.
1684**
1685** If the locking level of the file descriptor is already at or below
1686** the requested locking level, this routine is a no-op.
1687*/
1688static int unixUnlock(sqlite3_file *id, int locktype){
1689 return _posixUnlock(id, locktype, 0);
1690}
1691
1692/*
danielk1977e339d652008-06-28 11:23:00 +00001693** This function performs the parts of the "close file" operation
1694** common to all locking schemes. It closes the directory and file
1695** handles, if they are valid, and sets all fields of the unixFile
1696** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001697**
1698** It is *not* necessary to hold the mutex when this routine is called,
1699** even on VxWorks. A mutex will be acquired on VxWorks by the
1700** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001701*/
1702static int closeUnixFile(sqlite3_file *id){
1703 unixFile *pFile = (unixFile*)id;
1704 if( pFile ){
1705 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001706 int err = close(pFile->dirfd);
1707 if( err ){
1708 pFile->lastErrno = errno;
1709 return SQLITE_IOERR_DIR_CLOSE;
1710 }else{
1711 pFile->dirfd=-1;
1712 }
danielk1977e339d652008-06-28 11:23:00 +00001713 }
1714 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001715 int err = close(pFile->h);
1716 if( err ){
1717 pFile->lastErrno = errno;
1718 return SQLITE_IOERR_CLOSE;
1719 }
danielk1977e339d652008-06-28 11:23:00 +00001720 }
drh6c7d5c52008-11-21 20:32:33 +00001721#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001722 if( pFile->pId ){
1723 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001724 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001725 }
drh107886a2008-11-21 22:21:50 +00001726 vxworksReleaseFileId(pFile->pId);
1727 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001728 }
1729#endif
danielk1977e339d652008-06-28 11:23:00 +00001730 OSTRACE2("CLOSE %-3d\n", pFile->h);
1731 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001732 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001733 memset(pFile, 0, sizeof(unixFile));
1734 }
1735 return SQLITE_OK;
1736}
1737
1738/*
danielk1977e3026632004-06-22 11:29:02 +00001739** Close a file.
1740*/
danielk197762079062007-08-15 17:08:46 +00001741static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001742 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001743 if( id ){
1744 unixFile *pFile = (unixFile *)id;
1745 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001746 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001747 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001748 /* If there are outstanding locks, do not actually close the file just
1749 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001750 ** descriptor to pOpen->pUnused list. It will be automatically closed
1751 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001752 */
dan08da86a2009-08-21 17:18:03 +00001753 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001754 }
danielk1977e339d652008-06-28 11:23:00 +00001755 releaseLockInfo(pFile->pLock);
1756 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001757 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001758 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001759 }
aswiftaebf4132008-11-21 00:10:35 +00001760 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001761}
1762
drh734c9862008-11-28 15:37:20 +00001763/************** End of the posix advisory lock implementation *****************
1764******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001765
drh734c9862008-11-28 15:37:20 +00001766/******************************************************************************
1767****************************** No-op Locking **********************************
1768**
1769** Of the various locking implementations available, this is by far the
1770** simplest: locking is ignored. No attempt is made to lock the database
1771** file for reading or writing.
1772**
1773** This locking mode is appropriate for use on read-only databases
1774** (ex: databases that are burned into CD-ROM, for example.) It can
1775** also be used if the application employs some external mechanism to
1776** prevent simultaneous access of the same database by two or more
1777** database connections. But there is a serious risk of database
1778** corruption if this locking mode is used in situations where multiple
1779** database connections are accessing the same database file at the same
1780** time and one or more of those connections are writing.
1781*/
drhbfe66312006-10-03 17:40:40 +00001782
drh734c9862008-11-28 15:37:20 +00001783static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1784 UNUSED_PARAMETER(NotUsed);
1785 *pResOut = 0;
1786 return SQLITE_OK;
1787}
drh734c9862008-11-28 15:37:20 +00001788static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1789 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1790 return SQLITE_OK;
1791}
drh734c9862008-11-28 15:37:20 +00001792static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1793 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1794 return SQLITE_OK;
1795}
1796
1797/*
drh9b35ea62008-11-29 02:20:26 +00001798** Close the file.
drh734c9862008-11-28 15:37:20 +00001799*/
1800static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001801 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001802}
1803
1804/******************* End of the no-op lock implementation *********************
1805******************************************************************************/
1806
1807/******************************************************************************
1808************************* Begin dot-file Locking ******************************
1809**
drh0c2694b2009-09-03 16:23:44 +00001810** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001811** files in order to control access to the database. This works on just
1812** about every filesystem imaginable. But there are serious downsides:
1813**
1814** (1) There is zero concurrency. A single reader blocks all other
1815** connections from reading or writing the database.
1816**
1817** (2) An application crash or power loss can leave stale lock files
1818** sitting around that need to be cleared manually.
1819**
1820** Nevertheless, a dotlock is an appropriate locking mode for use if no
1821** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001822**
1823** Dotfile locking works by creating a file in the same directory as the
1824** database and with the same name but with a ".lock" extension added.
1825** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1826** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001827*/
1828
1829/*
1830** The file suffix added to the data base filename in order to create the
1831** lock file.
1832*/
1833#define DOTLOCK_SUFFIX ".lock"
1834
drh7708e972008-11-29 00:56:52 +00001835/*
1836** This routine checks if there is a RESERVED lock held on the specified
1837** file by this or any other process. If such a lock is held, set *pResOut
1838** to a non-zero value otherwise *pResOut is set to zero. The return value
1839** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1840**
1841** In dotfile locking, either a lock exists or it does not. So in this
1842** variation of CheckReservedLock(), *pResOut is set to true if any lock
1843** is held on the file and false if the file is unlocked.
1844*/
drh734c9862008-11-28 15:37:20 +00001845static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1846 int rc = SQLITE_OK;
1847 int reserved = 0;
1848 unixFile *pFile = (unixFile*)id;
1849
1850 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1851
1852 assert( pFile );
1853
1854 /* Check if a thread in this process holds such a lock */
1855 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001856 /* Either this connection or some other connection in the same process
1857 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001858 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001859 }else{
1860 /* The lock is held if and only if the lockfile exists */
1861 const char *zLockFile = (const char*)pFile->lockingContext;
1862 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001863 }
drh476bda72009-12-04 14:25:18 +00001864 OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001865 *pResOut = reserved;
1866 return rc;
1867}
1868
drh7708e972008-11-29 00:56:52 +00001869/*
1870** Lock the file with the lock specified by parameter locktype - one
1871** of the following:
1872**
1873** (1) SHARED_LOCK
1874** (2) RESERVED_LOCK
1875** (3) PENDING_LOCK
1876** (4) EXCLUSIVE_LOCK
1877**
1878** Sometimes when requesting one lock state, additional lock states
1879** are inserted in between. The locking might fail on one of the later
1880** transitions leaving the lock state different from what it started but
1881** still short of its goal. The following chart shows the allowed
1882** transitions and the inserted intermediate states:
1883**
1884** UNLOCKED -> SHARED
1885** SHARED -> RESERVED
1886** SHARED -> (PENDING) -> EXCLUSIVE
1887** RESERVED -> (PENDING) -> EXCLUSIVE
1888** PENDING -> EXCLUSIVE
1889**
1890** This routine will only increase a lock. Use the sqlite3OsUnlock()
1891** routine to lower a locking level.
1892**
1893** With dotfile locking, we really only support state (4): EXCLUSIVE.
1894** But we track the other locking levels internally.
1895*/
drh734c9862008-11-28 15:37:20 +00001896static int dotlockLock(sqlite3_file *id, int locktype) {
1897 unixFile *pFile = (unixFile*)id;
1898 int fd;
1899 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001900 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001901
drh7708e972008-11-29 00:56:52 +00001902
1903 /* If we have any lock, then the lock file already exists. All we have
1904 ** to do is adjust our internal record of the lock level.
1905 */
1906 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001907 pFile->locktype = locktype;
1908#if !OS_VXWORKS
1909 /* Always update the timestamp on the old file */
1910 utimes(zLockFile, NULL);
1911#endif
drh7708e972008-11-29 00:56:52 +00001912 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001913 }
1914
1915 /* grab an exclusive lock */
1916 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1917 if( fd<0 ){
1918 /* failed to open/create the file, someone else may have stolen the lock */
1919 int tErrno = errno;
1920 if( EEXIST == tErrno ){
1921 rc = SQLITE_BUSY;
1922 } else {
1923 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1924 if( IS_LOCK_ERROR(rc) ){
1925 pFile->lastErrno = tErrno;
1926 }
1927 }
drh7708e972008-11-29 00:56:52 +00001928 return rc;
drh734c9862008-11-28 15:37:20 +00001929 }
1930 if( close(fd) ){
1931 pFile->lastErrno = errno;
1932 rc = SQLITE_IOERR_CLOSE;
1933 }
1934
1935 /* got it, set the type and return ok */
1936 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001937 return rc;
1938}
1939
drh7708e972008-11-29 00:56:52 +00001940/*
1941** Lower the locking level on file descriptor pFile to locktype. locktype
1942** must be either NO_LOCK or SHARED_LOCK.
1943**
1944** If the locking level of the file descriptor is already at or below
1945** the requested locking level, this routine is a no-op.
1946**
1947** When the locking level reaches NO_LOCK, delete the lock file.
1948*/
drh734c9862008-11-28 15:37:20 +00001949static int dotlockUnlock(sqlite3_file *id, int locktype) {
1950 unixFile *pFile = (unixFile*)id;
1951 char *zLockFile = (char *)pFile->lockingContext;
1952
1953 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001954 OSTRACE5("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00001955 pFile->locktype, getpid());
1956 assert( locktype<=SHARED_LOCK );
1957
1958 /* no-op if possible */
1959 if( pFile->locktype==locktype ){
1960 return SQLITE_OK;
1961 }
drh7708e972008-11-29 00:56:52 +00001962
1963 /* To downgrade to shared, simply update our internal notion of the
1964 ** lock state. No need to mess with the file on disk.
1965 */
1966 if( locktype==SHARED_LOCK ){
1967 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001968 return SQLITE_OK;
1969 }
1970
drh7708e972008-11-29 00:56:52 +00001971 /* To fully unlock the database, delete the lock file */
1972 assert( locktype==NO_LOCK );
1973 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001974 int rc = 0;
1975 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001976 if( ENOENT != tErrno ){
1977 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1978 }
1979 if( IS_LOCK_ERROR(rc) ){
1980 pFile->lastErrno = tErrno;
1981 }
1982 return rc;
1983 }
1984 pFile->locktype = NO_LOCK;
1985 return SQLITE_OK;
1986}
1987
1988/*
drh9b35ea62008-11-29 02:20:26 +00001989** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001990*/
1991static int dotlockClose(sqlite3_file *id) {
1992 int rc;
1993 if( id ){
1994 unixFile *pFile = (unixFile*)id;
1995 dotlockUnlock(id, NO_LOCK);
1996 sqlite3_free(pFile->lockingContext);
1997 }
drh734c9862008-11-28 15:37:20 +00001998 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001999 return rc;
2000}
2001/****************** End of the dot-file lock implementation *******************
2002******************************************************************************/
2003
2004/******************************************************************************
2005************************** Begin flock Locking ********************************
2006**
2007** Use the flock() system call to do file locking.
2008**
drh6b9d6dd2008-12-03 19:34:47 +00002009** flock() locking is like dot-file locking in that the various
2010** fine-grain locking levels supported by SQLite are collapsed into
2011** a single exclusive lock. In other words, SHARED, RESERVED, and
2012** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2013** still works when you do this, but concurrency is reduced since
2014** only a single process can be reading the database at a time.
2015**
drh734c9862008-11-28 15:37:20 +00002016** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2017** compiling for VXWORKS.
2018*/
2019#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002020
drh6b9d6dd2008-12-03 19:34:47 +00002021/*
2022** This routine checks if there is a RESERVED lock held on the specified
2023** file by this or any other process. If such a lock is held, set *pResOut
2024** to a non-zero value otherwise *pResOut is set to zero. The return value
2025** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2026*/
drh734c9862008-11-28 15:37:20 +00002027static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2028 int rc = SQLITE_OK;
2029 int reserved = 0;
2030 unixFile *pFile = (unixFile*)id;
2031
2032 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2033
2034 assert( pFile );
2035
2036 /* Check if a thread in this process holds such a lock */
2037 if( pFile->locktype>SHARED_LOCK ){
2038 reserved = 1;
2039 }
2040
2041 /* Otherwise see if some other process holds it. */
2042 if( !reserved ){
2043 /* attempt to get the lock */
2044 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2045 if( !lrc ){
2046 /* got the lock, unlock it */
2047 lrc = flock(pFile->h, LOCK_UN);
2048 if ( lrc ) {
2049 int tErrno = errno;
2050 /* unlock failed with an error */
2051 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2052 if( IS_LOCK_ERROR(lrc) ){
2053 pFile->lastErrno = tErrno;
2054 rc = lrc;
2055 }
2056 }
2057 } else {
2058 int tErrno = errno;
2059 reserved = 1;
2060 /* someone else might have it reserved */
2061 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2062 if( IS_LOCK_ERROR(lrc) ){
2063 pFile->lastErrno = tErrno;
2064 rc = lrc;
2065 }
2066 }
2067 }
drh476bda72009-12-04 14:25:18 +00002068 OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002069
2070#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2071 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2072 rc = SQLITE_OK;
2073 reserved=1;
2074 }
2075#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2076 *pResOut = reserved;
2077 return rc;
2078}
2079
drh6b9d6dd2008-12-03 19:34:47 +00002080/*
2081** Lock the file with the lock specified by parameter locktype - one
2082** of the following:
2083**
2084** (1) SHARED_LOCK
2085** (2) RESERVED_LOCK
2086** (3) PENDING_LOCK
2087** (4) EXCLUSIVE_LOCK
2088**
2089** Sometimes when requesting one lock state, additional lock states
2090** are inserted in between. The locking might fail on one of the later
2091** transitions leaving the lock state different from what it started but
2092** still short of its goal. The following chart shows the allowed
2093** transitions and the inserted intermediate states:
2094**
2095** UNLOCKED -> SHARED
2096** SHARED -> RESERVED
2097** SHARED -> (PENDING) -> EXCLUSIVE
2098** RESERVED -> (PENDING) -> EXCLUSIVE
2099** PENDING -> EXCLUSIVE
2100**
2101** flock() only really support EXCLUSIVE locks. We track intermediate
2102** lock states in the sqlite3_file structure, but all locks SHARED or
2103** above are really EXCLUSIVE locks and exclude all other processes from
2104** access the file.
2105**
2106** This routine will only increase a lock. Use the sqlite3OsUnlock()
2107** routine to lower a locking level.
2108*/
drh734c9862008-11-28 15:37:20 +00002109static int flockLock(sqlite3_file *id, int locktype) {
2110 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002111 unixFile *pFile = (unixFile*)id;
2112
2113 assert( pFile );
2114
2115 /* if we already have a lock, it is exclusive.
2116 ** Just adjust level and punt on outta here. */
2117 if (pFile->locktype > NO_LOCK) {
2118 pFile->locktype = locktype;
2119 return SQLITE_OK;
2120 }
2121
2122 /* grab an exclusive lock */
2123
2124 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2125 int tErrno = errno;
2126 /* didn't get, must be busy */
2127 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2128 if( IS_LOCK_ERROR(rc) ){
2129 pFile->lastErrno = tErrno;
2130 }
2131 } else {
2132 /* got it, set the type and return ok */
2133 pFile->locktype = locktype;
2134 }
drh476bda72009-12-04 14:25:18 +00002135 OSTRACE4("LOCK %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
drh734c9862008-11-28 15:37:20 +00002136 rc==SQLITE_OK ? "ok" : "failed");
2137#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2138 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2139 rc = SQLITE_BUSY;
2140 }
2141#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2142 return rc;
2143}
2144
drh6b9d6dd2008-12-03 19:34:47 +00002145
2146/*
2147** Lower the locking level on file descriptor pFile to locktype. locktype
2148** must be either NO_LOCK or SHARED_LOCK.
2149**
2150** If the locking level of the file descriptor is already at or below
2151** the requested locking level, this routine is a no-op.
2152*/
drh734c9862008-11-28 15:37:20 +00002153static int flockUnlock(sqlite3_file *id, int locktype) {
2154 unixFile *pFile = (unixFile*)id;
2155
2156 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002157 OSTRACE5("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002158 pFile->locktype, getpid());
2159 assert( locktype<=SHARED_LOCK );
2160
2161 /* no-op if possible */
2162 if( pFile->locktype==locktype ){
2163 return SQLITE_OK;
2164 }
2165
2166 /* shared can just be set because we always have an exclusive */
2167 if (locktype==SHARED_LOCK) {
2168 pFile->locktype = locktype;
2169 return SQLITE_OK;
2170 }
2171
2172 /* no, really, unlock. */
2173 int rc = flock(pFile->h, LOCK_UN);
2174 if (rc) {
2175 int r, tErrno = errno;
2176 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2177 if( IS_LOCK_ERROR(r) ){
2178 pFile->lastErrno = tErrno;
2179 }
2180#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2181 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2182 r = SQLITE_BUSY;
2183 }
2184#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2185
2186 return r;
2187 } else {
2188 pFile->locktype = NO_LOCK;
2189 return SQLITE_OK;
2190 }
2191}
2192
2193/*
2194** Close a file.
2195*/
2196static int flockClose(sqlite3_file *id) {
2197 if( id ){
2198 flockUnlock(id, NO_LOCK);
2199 }
2200 return closeUnixFile(id);
2201}
2202
2203#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2204
2205/******************* End of the flock lock implementation *********************
2206******************************************************************************/
2207
2208/******************************************************************************
2209************************ Begin Named Semaphore Locking ************************
2210**
2211** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002212**
2213** Semaphore locking is like dot-lock and flock in that it really only
2214** supports EXCLUSIVE locking. Only a single process can read or write
2215** the database file at a time. This reduces potential concurrency, but
2216** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002217*/
2218#if OS_VXWORKS
2219
drh6b9d6dd2008-12-03 19:34:47 +00002220/*
2221** This routine checks if there is a RESERVED lock held on the specified
2222** file by this or any other process. If such a lock is held, set *pResOut
2223** to a non-zero value otherwise *pResOut is set to zero. The return value
2224** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2225*/
drh734c9862008-11-28 15:37:20 +00002226static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2227 int rc = SQLITE_OK;
2228 int reserved = 0;
2229 unixFile *pFile = (unixFile*)id;
2230
2231 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2232
2233 assert( pFile );
2234
2235 /* Check if a thread in this process holds such a lock */
2236 if( pFile->locktype>SHARED_LOCK ){
2237 reserved = 1;
2238 }
2239
2240 /* Otherwise see if some other process holds it. */
2241 if( !reserved ){
2242 sem_t *pSem = pFile->pOpen->pSem;
2243 struct stat statBuf;
2244
2245 if( sem_trywait(pSem)==-1 ){
2246 int tErrno = errno;
2247 if( EAGAIN != tErrno ){
2248 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2249 pFile->lastErrno = tErrno;
2250 } else {
2251 /* someone else has the lock when we are in NO_LOCK */
2252 reserved = (pFile->locktype < SHARED_LOCK);
2253 }
2254 }else{
2255 /* we could have it if we want it */
2256 sem_post(pSem);
2257 }
2258 }
drh476bda72009-12-04 14:25:18 +00002259 OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002260
2261 *pResOut = reserved;
2262 return rc;
2263}
2264
drh6b9d6dd2008-12-03 19:34:47 +00002265/*
2266** Lock the file with the lock specified by parameter locktype - one
2267** of the following:
2268**
2269** (1) SHARED_LOCK
2270** (2) RESERVED_LOCK
2271** (3) PENDING_LOCK
2272** (4) EXCLUSIVE_LOCK
2273**
2274** Sometimes when requesting one lock state, additional lock states
2275** are inserted in between. The locking might fail on one of the later
2276** transitions leaving the lock state different from what it started but
2277** still short of its goal. The following chart shows the allowed
2278** transitions and the inserted intermediate states:
2279**
2280** UNLOCKED -> SHARED
2281** SHARED -> RESERVED
2282** SHARED -> (PENDING) -> EXCLUSIVE
2283** RESERVED -> (PENDING) -> EXCLUSIVE
2284** PENDING -> EXCLUSIVE
2285**
2286** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2287** lock states in the sqlite3_file structure, but all locks SHARED or
2288** above are really EXCLUSIVE locks and exclude all other processes from
2289** access the file.
2290**
2291** This routine will only increase a lock. Use the sqlite3OsUnlock()
2292** routine to lower a locking level.
2293*/
drh734c9862008-11-28 15:37:20 +00002294static int semLock(sqlite3_file *id, int locktype) {
2295 unixFile *pFile = (unixFile*)id;
2296 int fd;
2297 sem_t *pSem = pFile->pOpen->pSem;
2298 int rc = SQLITE_OK;
2299
2300 /* if we already have a lock, it is exclusive.
2301 ** Just adjust level and punt on outta here. */
2302 if (pFile->locktype > NO_LOCK) {
2303 pFile->locktype = locktype;
2304 rc = SQLITE_OK;
2305 goto sem_end_lock;
2306 }
2307
2308 /* lock semaphore now but bail out when already locked. */
2309 if( sem_trywait(pSem)==-1 ){
2310 rc = SQLITE_BUSY;
2311 goto sem_end_lock;
2312 }
2313
2314 /* got it, set the type and return ok */
2315 pFile->locktype = locktype;
2316
2317 sem_end_lock:
2318 return rc;
2319}
2320
drh6b9d6dd2008-12-03 19:34:47 +00002321/*
2322** Lower the locking level on file descriptor pFile to locktype. locktype
2323** must be either NO_LOCK or SHARED_LOCK.
2324**
2325** If the locking level of the file descriptor is already at or below
2326** the requested locking level, this routine is a no-op.
2327*/
drh734c9862008-11-28 15:37:20 +00002328static int semUnlock(sqlite3_file *id, int locktype) {
2329 unixFile *pFile = (unixFile*)id;
2330 sem_t *pSem = pFile->pOpen->pSem;
2331
2332 assert( pFile );
2333 assert( pSem );
drh476bda72009-12-04 14:25:18 +00002334 OSTRACE5("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002335 pFile->locktype, getpid());
2336 assert( locktype<=SHARED_LOCK );
2337
2338 /* no-op if possible */
2339 if( pFile->locktype==locktype ){
2340 return SQLITE_OK;
2341 }
2342
2343 /* shared can just be set because we always have an exclusive */
2344 if (locktype==SHARED_LOCK) {
2345 pFile->locktype = locktype;
2346 return SQLITE_OK;
2347 }
2348
2349 /* no, really unlock. */
2350 if ( sem_post(pSem)==-1 ) {
2351 int rc, tErrno = errno;
2352 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2353 if( IS_LOCK_ERROR(rc) ){
2354 pFile->lastErrno = tErrno;
2355 }
2356 return rc;
2357 }
2358 pFile->locktype = NO_LOCK;
2359 return SQLITE_OK;
2360}
2361
2362/*
2363 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002364 */
drh734c9862008-11-28 15:37:20 +00002365static int semClose(sqlite3_file *id) {
2366 if( id ){
2367 unixFile *pFile = (unixFile*)id;
2368 semUnlock(id, NO_LOCK);
2369 assert( pFile );
2370 unixEnterMutex();
2371 releaseLockInfo(pFile->pLock);
2372 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002373 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002374 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002375 }
2376 return SQLITE_OK;
2377}
2378
2379#endif /* OS_VXWORKS */
2380/*
2381** Named semaphore locking is only available on VxWorks.
2382**
2383*************** End of the named semaphore lock implementation ****************
2384******************************************************************************/
2385
2386
2387/******************************************************************************
2388*************************** Begin AFP Locking *********************************
2389**
2390** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2391** on Apple Macintosh computers - both OS9 and OSX.
2392**
2393** Third-party implementations of AFP are available. But this code here
2394** only works on OSX.
2395*/
2396
drhd2cb50b2009-01-09 21:41:17 +00002397#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002398/*
2399** The afpLockingContext structure contains all afp lock specific state
2400*/
drhbfe66312006-10-03 17:40:40 +00002401typedef struct afpLockingContext afpLockingContext;
2402struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002403 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002404 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002405};
2406
2407struct ByteRangeLockPB2
2408{
2409 unsigned long long offset; /* offset to first byte to lock */
2410 unsigned long long length; /* nbr of bytes to lock */
2411 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2412 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2413 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2414 int fd; /* file desc to assoc this lock with */
2415};
2416
drhfd131da2007-08-07 17:13:03 +00002417#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002418
drh6b9d6dd2008-12-03 19:34:47 +00002419/*
2420** This is a utility for setting or clearing a bit-range lock on an
2421** AFP filesystem.
2422**
2423** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2424*/
2425static int afpSetLock(
2426 const char *path, /* Name of the file to be locked or unlocked */
2427 unixFile *pFile, /* Open file descriptor on path */
2428 unsigned long long offset, /* First byte to be locked */
2429 unsigned long long length, /* Number of bytes to lock */
2430 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002431){
drh6b9d6dd2008-12-03 19:34:47 +00002432 struct ByteRangeLockPB2 pb;
2433 int err;
drhbfe66312006-10-03 17:40:40 +00002434
2435 pb.unLockFlag = setLockFlag ? 0 : 1;
2436 pb.startEndFlag = 0;
2437 pb.offset = offset;
2438 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002439 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002440
2441 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002442 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2443 offset, length);
drhbfe66312006-10-03 17:40:40 +00002444 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2445 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002446 int rc;
2447 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002448 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2449 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002450#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2451 rc = SQLITE_BUSY;
2452#else
drh734c9862008-11-28 15:37:20 +00002453 rc = sqliteErrorFromPosixError(tErrno,
2454 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002455#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002456 if( IS_LOCK_ERROR(rc) ){
2457 pFile->lastErrno = tErrno;
2458 }
2459 return rc;
drhbfe66312006-10-03 17:40:40 +00002460 } else {
aswift5b1a2562008-08-22 00:22:35 +00002461 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002462 }
2463}
2464
drh6b9d6dd2008-12-03 19:34:47 +00002465/*
2466** This routine checks if there is a RESERVED lock held on the specified
2467** file by this or any other process. If such a lock is held, set *pResOut
2468** to a non-zero value otherwise *pResOut is set to zero. The return value
2469** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2470*/
danielk1977e339d652008-06-28 11:23:00 +00002471static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002472 int rc = SQLITE_OK;
2473 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002474 unixFile *pFile = (unixFile*)id;
2475
aswift5b1a2562008-08-22 00:22:35 +00002476 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2477
2478 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002479 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002480 if( context->reserved ){
2481 *pResOut = 1;
2482 return SQLITE_OK;
2483 }
2484 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002485
2486 /* Check if a thread in this process holds such a lock */
drh7ed97b92010-01-20 13:07:21 +00002487 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002488 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002489 }
2490
2491 /* Otherwise see if some other process holds it.
2492 */
aswift5b1a2562008-08-22 00:22:35 +00002493 if( !reserved ){
2494 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002495 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002496 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002497 /* if we succeeded in taking the reserved lock, unlock it to restore
2498 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002499 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002500 } else {
2501 /* if we failed to get the lock then someone else must have it */
2502 reserved = 1;
2503 }
2504 if( IS_LOCK_ERROR(lrc) ){
2505 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002506 }
2507 }
drhbfe66312006-10-03 17:40:40 +00002508
drh7ed97b92010-01-20 13:07:21 +00002509 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002510 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
aswift5b1a2562008-08-22 00:22:35 +00002511
2512 *pResOut = reserved;
2513 return rc;
drhbfe66312006-10-03 17:40:40 +00002514}
2515
drh6b9d6dd2008-12-03 19:34:47 +00002516/*
2517** Lock the file with the lock specified by parameter locktype - one
2518** of the following:
2519**
2520** (1) SHARED_LOCK
2521** (2) RESERVED_LOCK
2522** (3) PENDING_LOCK
2523** (4) EXCLUSIVE_LOCK
2524**
2525** Sometimes when requesting one lock state, additional lock states
2526** are inserted in between. The locking might fail on one of the later
2527** transitions leaving the lock state different from what it started but
2528** still short of its goal. The following chart shows the allowed
2529** transitions and the inserted intermediate states:
2530**
2531** UNLOCKED -> SHARED
2532** SHARED -> RESERVED
2533** SHARED -> (PENDING) -> EXCLUSIVE
2534** RESERVED -> (PENDING) -> EXCLUSIVE
2535** PENDING -> EXCLUSIVE
2536**
2537** This routine will only increase a lock. Use the sqlite3OsUnlock()
2538** routine to lower a locking level.
2539*/
danielk1977e339d652008-06-28 11:23:00 +00002540static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002541 int rc = SQLITE_OK;
2542 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002543 struct unixLockInfo *pLock = pFile->pLock;
drhbfe66312006-10-03 17:40:40 +00002544 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002545
2546 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002547 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2548 locktypeName(locktype), locktypeName(pFile->locktype),
2549 locktypeName(pLock->locktype), pLock->cnt , getpid());
drh339eb0b2008-03-07 15:34:11 +00002550
drhbfe66312006-10-03 17:40:40 +00002551 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002552 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002553 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002554 */
drhbfe66312006-10-03 17:40:40 +00002555 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00002556 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002557 locktypeName(locktype));
2558 return SQLITE_OK;
2559 }
2560
2561 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002562 ** (1) We never move from unlocked to anything higher than shared lock.
2563 ** (2) SQLite never explicitly requests a pendig lock.
2564 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002565 */
drhbfe66312006-10-03 17:40:40 +00002566 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2567 assert( locktype!=PENDING_LOCK );
2568 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2569
2570 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002571 */
drh6c7d5c52008-11-21 20:32:33 +00002572 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002573
2574 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002575 */
drhbfe66312006-10-03 17:40:40 +00002576 rc = transferOwnership(pFile);
2577 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002578 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002579 return rc;
2580 }
drh7ed97b92010-01-20 13:07:21 +00002581 pLock = pFile->pLock;
2582
2583 /* If some thread using this PID has a lock via a different unixFile*
2584 ** handle that precludes the requested lock, return BUSY.
2585 */
2586 if( (pFile->locktype!=pLock->locktype &&
2587 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
2588 ){
2589 rc = SQLITE_BUSY;
2590 goto afp_end_lock;
2591 }
2592
2593 /* If a SHARED lock is requested, and some thread using this PID already
2594 ** has a SHARED or RESERVED lock, then increment reference counts and
2595 ** return SQLITE_OK.
2596 */
2597 if( locktype==SHARED_LOCK &&
2598 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
2599 assert( locktype==SHARED_LOCK );
2600 assert( pFile->locktype==0 );
2601 assert( pLock->cnt>0 );
2602 pFile->locktype = SHARED_LOCK;
2603 pLock->cnt++;
2604 pFile->pOpen->nLock++;
2605 goto afp_end_lock;
2606 }
drhbfe66312006-10-03 17:40:40 +00002607
2608 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002609 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2610 ** be released.
2611 */
drhbfe66312006-10-03 17:40:40 +00002612 if( locktype==SHARED_LOCK
2613 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002614 ){
2615 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002616 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002617 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002618 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002619 goto afp_end_lock;
2620 }
2621 }
2622
2623 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002624 ** operating system calls for the specified lock.
2625 */
drhbfe66312006-10-03 17:40:40 +00002626 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002627 int lrc1, lrc2, lrc1Errno;
2628 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002629
drh7ed97b92010-01-20 13:07:21 +00002630 assert( pLock->cnt==0 );
2631 assert( pLock->locktype==0 );
2632
2633 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002634 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002635 /* note that the quality of the randomness doesn't matter that much */
2636 lk = random();
drh7ed97b92010-01-20 13:07:21 +00002637 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002638 lrc1 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002639 SHARED_FIRST+pLock->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002640 if( IS_LOCK_ERROR(lrc1) ){
2641 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002642 }
aswift5b1a2562008-08-22 00:22:35 +00002643 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002644 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002645
aswift5b1a2562008-08-22 00:22:35 +00002646 if( IS_LOCK_ERROR(lrc1) ) {
2647 pFile->lastErrno = lrc1Errno;
2648 rc = lrc1;
2649 goto afp_end_lock;
2650 } else if( IS_LOCK_ERROR(lrc2) ){
2651 rc = lrc2;
2652 goto afp_end_lock;
2653 } else if( lrc1 != SQLITE_OK ) {
2654 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002655 } else {
2656 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002657 pFile->pOpen->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002658 pLock->cnt = 1;
drhbfe66312006-10-03 17:40:40 +00002659 }
drh7ed97b92010-01-20 13:07:21 +00002660 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
2661 /* We are trying for an exclusive lock but another thread in this
2662 ** same process is still holding a shared lock. */
2663 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002664 }else{
2665 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2666 ** assumed that there is a SHARED or greater lock on the file
2667 ** already.
2668 */
2669 int failed = 0;
2670 assert( 0!=pFile->locktype );
2671 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2672 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002673 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002674 if( !failed ){
2675 context->reserved = 1;
2676 }
drhbfe66312006-10-03 17:40:40 +00002677 }
2678 if (!failed && locktype == EXCLUSIVE_LOCK) {
2679 /* Acquire an EXCLUSIVE lock */
2680
2681 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002682 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002683 */
drh6b9d6dd2008-12-03 19:34:47 +00002684 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh7ed97b92010-01-20 13:07:21 +00002685 pLock->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002686 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002687 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002688 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002689 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002690 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002691 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002692 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2693 ** a critical I/O error
2694 */
2695 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2696 SQLITE_IOERR_LOCK;
2697 goto afp_end_lock;
2698 }
2699 }else{
aswift5b1a2562008-08-22 00:22:35 +00002700 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002701 }
2702 }
aswift5b1a2562008-08-22 00:22:35 +00002703 if( failed ){
2704 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002705 }
2706 }
2707
2708 if( rc==SQLITE_OK ){
2709 pFile->locktype = locktype;
drh7ed97b92010-01-20 13:07:21 +00002710 pLock->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002711 }else if( locktype==EXCLUSIVE_LOCK ){
2712 pFile->locktype = PENDING_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002713 pLock->locktype = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002714 }
2715
2716afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002717 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002718 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002719 rc==SQLITE_OK ? "ok" : "failed");
2720 return rc;
2721}
2722
2723/*
drh339eb0b2008-03-07 15:34:11 +00002724** Lower the locking level on file descriptor pFile to locktype. locktype
2725** must be either NO_LOCK or SHARED_LOCK.
2726**
2727** If the locking level of the file descriptor is already at or below
2728** the requested locking level, this routine is a no-op.
2729*/
danielk1977e339d652008-06-28 11:23:00 +00002730static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002731 int rc = SQLITE_OK;
2732 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002733 struct unixLockInfo *pLock;
2734 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2735 int skipShared = 0;
2736#ifdef SQLITE_TEST
2737 int h = pFile->h;
2738#endif
drhbfe66312006-10-03 17:40:40 +00002739
2740 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002741 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
2742 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002743
drhbfe66312006-10-03 17:40:40 +00002744 assert( locktype<=SHARED_LOCK );
2745 if( pFile->locktype<=locktype ){
2746 return SQLITE_OK;
2747 }
2748 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00002749 return SQLITE_MISUSE_BKPT;
drhbfe66312006-10-03 17:40:40 +00002750 }
drh6c7d5c52008-11-21 20:32:33 +00002751 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00002752 pLock = pFile->pLock;
2753 assert( pLock->cnt!=0 );
drhbfe66312006-10-03 17:40:40 +00002754 if( pFile->locktype>SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002755 assert( pLock->locktype==pFile->locktype );
2756 SimulateIOErrorBenign(1);
2757 SimulateIOError( h=(-1) )
2758 SimulateIOErrorBenign(0);
2759
2760#ifndef NDEBUG
2761 /* When reducing a lock such that other processes can start
2762 ** reading the database file again, make sure that the
2763 ** transaction counter was updated if any part of the database
2764 ** file changed. If the transaction counter is not updated,
2765 ** other connections to the same file might not realize that
2766 ** the file has changed and hence might not know to flush their
2767 ** cache. The use of a stale cache can lead to database corruption.
2768 */
2769 assert( pFile->inNormalWrite==0
2770 || pFile->dbUpdate==0
2771 || pFile->transCntrChng==1 );
2772 pFile->inNormalWrite = 0;
2773#endif
aswiftaebf4132008-11-21 00:10:35 +00002774
2775 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002776 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2777 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002778 /* only re-establish the shared lock if necessary */
drh7ed97b92010-01-20 13:07:21 +00002779 int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2780 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2781 } else {
2782 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002783 }
2784 }
2785 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002786 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002787 }
drh7ed97b92010-01-20 13:07:21 +00002788 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
2789 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2790 if( !rc ){
2791 context->reserved = 0;
2792 }
aswiftaebf4132008-11-21 00:10:35 +00002793 }
drh7ed97b92010-01-20 13:07:21 +00002794 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
2795 pLock->locktype = SHARED_LOCK;
2796 }
aswiftaebf4132008-11-21 00:10:35 +00002797 }
drh7ed97b92010-01-20 13:07:21 +00002798 if( rc==SQLITE_OK && locktype==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002799
drh7ed97b92010-01-20 13:07:21 +00002800 /* Decrement the shared lock counter. Release the lock using an
2801 ** OS call only when all threads in this same process have released
2802 ** the lock.
2803 */
2804 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2805 pLock->cnt--;
2806 if( pLock->cnt==0 ){
2807 SimulateIOErrorBenign(1);
2808 SimulateIOError( h=(-1) )
2809 SimulateIOErrorBenign(0);
2810 if( !skipShared ){
2811 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2812 }
2813 if( !rc ){
2814 pLock->locktype = NO_LOCK;
2815 pFile->locktype = NO_LOCK;
2816 }
2817 }
2818 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002819 struct unixOpenCnt *pOpen = pFile->pOpen;
drh7ed97b92010-01-20 13:07:21 +00002820
aswiftaebf4132008-11-21 00:10:35 +00002821 pOpen->nLock--;
2822 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002823 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002824 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002825 }
2826 }
drhbfe66312006-10-03 17:40:40 +00002827 }
drh7ed97b92010-01-20 13:07:21 +00002828
drh6c7d5c52008-11-21 20:32:33 +00002829 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00002830 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002831 return rc;
2832}
2833
2834/*
drh339eb0b2008-03-07 15:34:11 +00002835** Close a file & cleanup AFP specific locking context
2836*/
danielk1977e339d652008-06-28 11:23:00 +00002837static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002838 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002839 if( id ){
2840 unixFile *pFile = (unixFile*)id;
2841 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002842 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002843 if( pFile->pOpen && pFile->pOpen->nLock ){
2844 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002845 ** yet because that would clear those locks. Instead, add the file
2846 ** descriptor to pOpen->aPending. It will be automatically closed when
2847 ** the last lock is cleared.
2848 */
dan08da86a2009-08-21 17:18:03 +00002849 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002850 }
drh7ed97b92010-01-20 13:07:21 +00002851 releaseLockInfo(pFile->pLock);
aswiftaebf4132008-11-21 00:10:35 +00002852 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002853 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002854 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002855 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002856 }
drh7ed97b92010-01-20 13:07:21 +00002857 return rc;
drhbfe66312006-10-03 17:40:40 +00002858}
2859
drhd2cb50b2009-01-09 21:41:17 +00002860#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002861/*
2862** The code above is the AFP lock implementation. The code is specific
2863** to MacOSX and does not work on other unix platforms. No alternative
2864** is available. If you don't compile for a mac, then the "unix-afp"
2865** VFS is not available.
2866**
2867********************* End of the AFP lock implementation **********************
2868******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002869
drh7ed97b92010-01-20 13:07:21 +00002870/******************************************************************************
2871*************************** Begin NFS Locking ********************************/
2872
2873#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2874/*
2875 ** Lower the locking level on file descriptor pFile to locktype. locktype
2876 ** must be either NO_LOCK or SHARED_LOCK.
2877 **
2878 ** If the locking level of the file descriptor is already at or below
2879 ** the requested locking level, this routine is a no-op.
2880 */
2881static int nfsUnlock(sqlite3_file *id, int locktype){
2882 return _posixUnlock(id, locktype, 1);
2883}
2884
2885#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2886/*
2887** The code above is the NFS lock implementation. The code is specific
2888** to MacOSX and does not work on other unix platforms. No alternative
2889** is available.
2890**
2891********************* End of the NFS lock implementation **********************
2892******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002893
2894/******************************************************************************
2895**************** Non-locking sqlite3_file methods *****************************
2896**
2897** The next division contains implementations for all methods of the
2898** sqlite3_file object other than the locking methods. The locking
2899** methods were defined in divisions above (one locking method per
2900** division). Those methods that are common to all locking modes
2901** are gather together into this division.
2902*/
drhbfe66312006-10-03 17:40:40 +00002903
2904/*
drh734c9862008-11-28 15:37:20 +00002905** Seek to the offset passed as the second argument, then read cnt
2906** bytes into pBuf. Return the number of bytes actually read.
2907**
2908** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2909** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2910** one system to another. Since SQLite does not define USE_PREAD
2911** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2912** See tickets #2741 and #2681.
2913**
2914** To avoid stomping the errno value on a failed read the lastErrno value
2915** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002916*/
drh734c9862008-11-28 15:37:20 +00002917static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2918 int got;
drh7ed97b92010-01-20 13:07:21 +00002919#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002920 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002921#endif
drh734c9862008-11-28 15:37:20 +00002922 TIMER_START;
2923#if defined(USE_PREAD)
2924 got = pread(id->h, pBuf, cnt, offset);
2925 SimulateIOError( got = -1 );
2926#elif defined(USE_PREAD64)
2927 got = pread64(id->h, pBuf, cnt, offset);
2928 SimulateIOError( got = -1 );
2929#else
2930 newOffset = lseek(id->h, offset, SEEK_SET);
2931 SimulateIOError( newOffset-- );
2932 if( newOffset!=offset ){
2933 if( newOffset == -1 ){
2934 ((unixFile*)id)->lastErrno = errno;
2935 }else{
2936 ((unixFile*)id)->lastErrno = 0;
2937 }
2938 return -1;
2939 }
2940 got = read(id->h, pBuf, cnt);
2941#endif
2942 TIMER_END;
2943 if( got<0 ){
2944 ((unixFile*)id)->lastErrno = errno;
2945 }
2946 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2947 return got;
drhbfe66312006-10-03 17:40:40 +00002948}
2949
2950/*
drh734c9862008-11-28 15:37:20 +00002951** Read data from a file into a buffer. Return SQLITE_OK if all
2952** bytes were read successfully and SQLITE_IOERR if anything goes
2953** wrong.
drh339eb0b2008-03-07 15:34:11 +00002954*/
drh734c9862008-11-28 15:37:20 +00002955static int unixRead(
2956 sqlite3_file *id,
2957 void *pBuf,
2958 int amt,
2959 sqlite3_int64 offset
2960){
dan08da86a2009-08-21 17:18:03 +00002961 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002962 int got;
2963 assert( id );
drh08c6d442009-02-09 17:34:07 +00002964
dan08da86a2009-08-21 17:18:03 +00002965 /* If this is a database file (not a journal, master-journal or temp
2966 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002967#if 0
dane946c392009-08-22 11:39:46 +00002968 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002969 || offset>=PENDING_BYTE+512
2970 || offset+amt<=PENDING_BYTE
2971 );
dan7c246102010-04-12 19:00:29 +00002972#endif
drh08c6d442009-02-09 17:34:07 +00002973
dan08da86a2009-08-21 17:18:03 +00002974 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002975 if( got==amt ){
2976 return SQLITE_OK;
2977 }else if( got<0 ){
2978 /* lastErrno set by seekAndRead */
2979 return SQLITE_IOERR_READ;
2980 }else{
dan08da86a2009-08-21 17:18:03 +00002981 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002982 /* Unread parts of the buffer must be zero-filled */
2983 memset(&((char*)pBuf)[got], 0, amt-got);
2984 return SQLITE_IOERR_SHORT_READ;
2985 }
2986}
2987
2988/*
2989** Seek to the offset in id->offset then read cnt bytes into pBuf.
2990** Return the number of bytes actually read. Update the offset.
2991**
2992** To avoid stomping the errno value on a failed write the lastErrno value
2993** is set before returning.
2994*/
2995static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2996 int got;
drh7ed97b92010-01-20 13:07:21 +00002997#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002998 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002999#endif
drh734c9862008-11-28 15:37:20 +00003000 TIMER_START;
3001#if defined(USE_PREAD)
3002 got = pwrite(id->h, pBuf, cnt, offset);
3003#elif defined(USE_PREAD64)
3004 got = pwrite64(id->h, pBuf, cnt, offset);
3005#else
3006 newOffset = lseek(id->h, offset, SEEK_SET);
3007 if( newOffset!=offset ){
3008 if( newOffset == -1 ){
3009 ((unixFile*)id)->lastErrno = errno;
3010 }else{
3011 ((unixFile*)id)->lastErrno = 0;
3012 }
3013 return -1;
3014 }
3015 got = write(id->h, pBuf, cnt);
3016#endif
3017 TIMER_END;
3018 if( got<0 ){
3019 ((unixFile*)id)->lastErrno = errno;
3020 }
3021
3022 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3023 return got;
3024}
3025
3026
3027/*
3028** Write data from a buffer into a file. Return SQLITE_OK on success
3029** or some other error code on failure.
3030*/
3031static int unixWrite(
3032 sqlite3_file *id,
3033 const void *pBuf,
3034 int amt,
3035 sqlite3_int64 offset
3036){
dan08da86a2009-08-21 17:18:03 +00003037 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003038 int wrote = 0;
3039 assert( id );
3040 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003041
dan08da86a2009-08-21 17:18:03 +00003042 /* If this is a database file (not a journal, master-journal or temp
3043 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003044#if 0
dane946c392009-08-22 11:39:46 +00003045 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003046 || offset>=PENDING_BYTE+512
3047 || offset+amt<=PENDING_BYTE
3048 );
dan7c246102010-04-12 19:00:29 +00003049#endif
drh08c6d442009-02-09 17:34:07 +00003050
drh8f941bc2009-01-14 23:03:40 +00003051#ifndef NDEBUG
3052 /* If we are doing a normal write to a database file (as opposed to
3053 ** doing a hot-journal rollback or a write to some file other than a
3054 ** normal database file) then record the fact that the database
3055 ** has changed. If the transaction counter is modified, record that
3056 ** fact too.
3057 */
dan08da86a2009-08-21 17:18:03 +00003058 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003059 pFile->dbUpdate = 1; /* The database has been modified */
3060 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003061 int rc;
drh8f941bc2009-01-14 23:03:40 +00003062 char oldCntr[4];
3063 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003064 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003065 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003066 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003067 pFile->transCntrChng = 1; /* The transaction counter has changed */
3068 }
3069 }
3070 }
3071#endif
3072
dan08da86a2009-08-21 17:18:03 +00003073 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003074 amt -= wrote;
3075 offset += wrote;
3076 pBuf = &((char*)pBuf)[wrote];
3077 }
3078 SimulateIOError(( wrote=(-1), amt=1 ));
3079 SimulateDiskfullError(( wrote=0, amt=1 ));
3080 if( amt>0 ){
3081 if( wrote<0 ){
3082 /* lastErrno set by seekAndWrite */
3083 return SQLITE_IOERR_WRITE;
3084 }else{
dan08da86a2009-08-21 17:18:03 +00003085 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003086 return SQLITE_FULL;
3087 }
3088 }
3089 return SQLITE_OK;
3090}
3091
3092#ifdef SQLITE_TEST
3093/*
3094** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003095** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003096*/
3097int sqlite3_sync_count = 0;
3098int sqlite3_fullsync_count = 0;
3099#endif
3100
3101/*
drh89240432009-03-25 01:06:01 +00003102** We do not trust systems to provide a working fdatasync(). Some do.
3103** Others do no. To be safe, we will stick with the (slower) fsync().
3104** If you know that your system does support fdatasync() correctly,
3105** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003106*/
drh89240432009-03-25 01:06:01 +00003107#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003108# define fdatasync fsync
3109#endif
3110
3111/*
3112** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3113** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3114** only available on Mac OS X. But that could change.
3115*/
3116#ifdef F_FULLFSYNC
3117# define HAVE_FULLFSYNC 1
3118#else
3119# define HAVE_FULLFSYNC 0
3120#endif
3121
3122
3123/*
3124** The fsync() system call does not work as advertised on many
3125** unix systems. The following procedure is an attempt to make
3126** it work better.
3127**
3128** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3129** for testing when we want to run through the test suite quickly.
3130** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3131** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3132** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003133**
3134** SQLite sets the dataOnly flag if the size of the file is unchanged.
3135** The idea behind dataOnly is that it should only write the file content
3136** to disk, not the inode. We only set dataOnly if the file size is
3137** unchanged since the file size is part of the inode. However,
3138** Ted Ts'o tells us that fdatasync() will also write the inode if the
3139** file size has changed. The only real difference between fdatasync()
3140** and fsync(), Ted tells us, is that fdatasync() will not flush the
3141** inode if the mtime or owner or other inode attributes have changed.
3142** We only care about the file size, not the other file attributes, so
3143** as far as SQLite is concerned, an fdatasync() is always adequate.
3144** So, we always use fdatasync() if it is available, regardless of
3145** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003146*/
3147static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003148 int rc;
drh734c9862008-11-28 15:37:20 +00003149
3150 /* The following "ifdef/elif/else/" block has the same structure as
3151 ** the one below. It is replicated here solely to avoid cluttering
3152 ** up the real code with the UNUSED_PARAMETER() macros.
3153 */
3154#ifdef SQLITE_NO_SYNC
3155 UNUSED_PARAMETER(fd);
3156 UNUSED_PARAMETER(fullSync);
3157 UNUSED_PARAMETER(dataOnly);
3158#elif HAVE_FULLFSYNC
3159 UNUSED_PARAMETER(dataOnly);
3160#else
3161 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003162 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003163#endif
3164
3165 /* Record the number of times that we do a normal fsync() and
3166 ** FULLSYNC. This is used during testing to verify that this procedure
3167 ** gets called with the correct arguments.
3168 */
3169#ifdef SQLITE_TEST
3170 if( fullSync ) sqlite3_fullsync_count++;
3171 sqlite3_sync_count++;
3172#endif
3173
3174 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3175 ** no-op
3176 */
3177#ifdef SQLITE_NO_SYNC
3178 rc = SQLITE_OK;
3179#elif HAVE_FULLFSYNC
3180 if( fullSync ){
3181 rc = fcntl(fd, F_FULLFSYNC, 0);
3182 }else{
3183 rc = 1;
3184 }
3185 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003186 ** It shouldn't be possible for fullfsync to fail on the local
3187 ** file system (on OSX), so failure indicates that FULLFSYNC
3188 ** isn't supported for this file system. So, attempt an fsync
3189 ** and (for now) ignore the overhead of a superfluous fcntl call.
3190 ** It'd be better to detect fullfsync support once and avoid
3191 ** the fcntl call every time sync is called.
3192 */
drh734c9862008-11-28 15:37:20 +00003193 if( rc ) rc = fsync(fd);
3194
drh7ed97b92010-01-20 13:07:21 +00003195#elif defined(__APPLE__)
3196 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3197 ** so currently we default to the macro that redefines fdatasync to fsync
3198 */
3199 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003200#else
drh0b647ff2009-03-21 14:41:04 +00003201 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003202#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003203 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003204 rc = fsync(fd);
3205 }
drh0b647ff2009-03-21 14:41:04 +00003206#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003207#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3208
3209 if( OS_VXWORKS && rc!= -1 ){
3210 rc = 0;
3211 }
chw97185482008-11-17 08:05:31 +00003212 return rc;
drhbfe66312006-10-03 17:40:40 +00003213}
3214
drh734c9862008-11-28 15:37:20 +00003215/*
3216** Make sure all writes to a particular file are committed to disk.
3217**
3218** If dataOnly==0 then both the file itself and its metadata (file
3219** size, access time, etc) are synced. If dataOnly!=0 then only the
3220** file data is synced.
3221**
3222** Under Unix, also make sure that the directory entry for the file
3223** has been created by fsync-ing the directory that contains the file.
3224** If we do not do this and we encounter a power failure, the directory
3225** entry for the journal might not exist after we reboot. The next
3226** SQLite to access the file will not know that the journal exists (because
3227** the directory entry for the journal was never created) and the transaction
3228** will not roll back - possibly leading to database corruption.
3229*/
3230static int unixSync(sqlite3_file *id, int flags){
3231 int rc;
3232 unixFile *pFile = (unixFile*)id;
3233
3234 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3235 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3236
3237 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3238 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3239 || (flags&0x0F)==SQLITE_SYNC_FULL
3240 );
3241
3242 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3243 ** line is to test that doing so does not cause any problems.
3244 */
3245 SimulateDiskfullError( return SQLITE_FULL );
3246
3247 assert( pFile );
3248 OSTRACE2("SYNC %-3d\n", pFile->h);
3249 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3250 SimulateIOError( rc=1 );
3251 if( rc ){
3252 pFile->lastErrno = errno;
3253 return SQLITE_IOERR_FSYNC;
3254 }
3255 if( pFile->dirfd>=0 ){
3256 int err;
3257 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3258 HAVE_FULLFSYNC, isFullsync);
3259#ifndef SQLITE_DISABLE_DIRSYNC
3260 /* The directory sync is only attempted if full_fsync is
3261 ** turned off or unavailable. If a full_fsync occurred above,
3262 ** then the directory sync is superfluous.
3263 */
3264 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3265 /*
3266 ** We have received multiple reports of fsync() returning
3267 ** errors when applied to directories on certain file systems.
3268 ** A failed directory sync is not a big deal. So it seems
3269 ** better to ignore the error. Ticket #1657
3270 */
3271 /* pFile->lastErrno = errno; */
3272 /* return SQLITE_IOERR; */
3273 }
3274#endif
3275 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3276 if( err==0 ){ /* directory when we are done */
3277 pFile->dirfd = -1;
3278 }else{
3279 pFile->lastErrno = errno;
3280 rc = SQLITE_IOERR_DIR_CLOSE;
3281 }
3282 }
3283 return rc;
3284}
3285
3286/*
3287** Truncate an open file to a specified size
3288*/
3289static int unixTruncate(sqlite3_file *id, i64 nByte){
3290 int rc;
3291 assert( id );
3292 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3293 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3294 if( rc ){
3295 ((unixFile*)id)->lastErrno = errno;
3296 return SQLITE_IOERR_TRUNCATE;
3297 }else{
drh3313b142009-11-06 04:13:18 +00003298#ifndef NDEBUG
3299 /* If we are doing a normal write to a database file (as opposed to
3300 ** doing a hot-journal rollback or a write to some file other than a
3301 ** normal database file) and we truncate the file to zero length,
3302 ** that effectively updates the change counter. This might happen
3303 ** when restoring a database using the backup API from a zero-length
3304 ** source.
3305 */
3306 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3307 ((unixFile*)id)->transCntrChng = 1;
3308 }
3309#endif
3310
drh734c9862008-11-28 15:37:20 +00003311 return SQLITE_OK;
3312 }
3313}
3314
3315/*
3316** Determine the current size of a file in bytes
3317*/
3318static int unixFileSize(sqlite3_file *id, i64 *pSize){
3319 int rc;
3320 struct stat buf;
3321 assert( id );
3322 rc = fstat(((unixFile*)id)->h, &buf);
3323 SimulateIOError( rc=1 );
3324 if( rc!=0 ){
3325 ((unixFile*)id)->lastErrno = errno;
3326 return SQLITE_IOERR_FSTAT;
3327 }
3328 *pSize = buf.st_size;
3329
3330 /* When opening a zero-size database, the findLockInfo() procedure
3331 ** writes a single byte into that file in order to work around a bug
3332 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3333 ** layers, we need to report this file size as zero even though it is
3334 ** really 1. Ticket #3260.
3335 */
3336 if( *pSize==1 ) *pSize = 0;
3337
3338
3339 return SQLITE_OK;
3340}
3341
drhd2cb50b2009-01-09 21:41:17 +00003342#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003343/*
3344** Handler for proxy-locking file-control verbs. Defined below in the
3345** proxying locking division.
3346*/
3347static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003348#endif
drh715ff302008-12-03 22:32:44 +00003349
danielk1977ad94b582007-08-20 06:44:22 +00003350
danielk1977e3026632004-06-22 11:29:02 +00003351/*
drh9e33c2c2007-08-31 18:34:59 +00003352** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003353*/
drhcc6bb3e2007-08-31 16:11:35 +00003354static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003355 switch( op ){
3356 case SQLITE_FCNTL_LOCKSTATE: {
3357 *(int*)pArg = ((unixFile*)id)->locktype;
3358 return SQLITE_OK;
3359 }
drh7708e972008-11-29 00:56:52 +00003360 case SQLITE_LAST_ERRNO: {
3361 *(int*)pArg = ((unixFile*)id)->lastErrno;
3362 return SQLITE_OK;
3363 }
drh8f941bc2009-01-14 23:03:40 +00003364#ifndef NDEBUG
3365 /* The pager calls this method to signal that it has done
3366 ** a rollback and that the database is therefore unchanged and
3367 ** it hence it is OK for the transaction change counter to be
3368 ** unchanged.
3369 */
3370 case SQLITE_FCNTL_DB_UNCHANGED: {
3371 ((unixFile*)id)->dbUpdate = 0;
3372 return SQLITE_OK;
3373 }
3374#endif
drhd2cb50b2009-01-09 21:41:17 +00003375#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003376 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003377 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003378 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003379 }
drhd2cb50b2009-01-09 21:41:17 +00003380#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003381 }
drhcc6bb3e2007-08-31 16:11:35 +00003382 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003383}
3384
3385/*
danielk1977a3d4c882007-03-23 10:08:38 +00003386** Return the sector size in bytes of the underlying block device for
3387** the specified file. This is almost always 512 bytes, but may be
3388** larger for some devices.
3389**
3390** SQLite code assumes this function cannot fail. It also assumes that
3391** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003392** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003393** same for both.
3394*/
danielk1977397d65f2008-11-19 11:35:39 +00003395static int unixSectorSize(sqlite3_file *NotUsed){
3396 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003397 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003398}
3399
danielk197790949c22007-08-17 16:50:38 +00003400/*
danielk1977397d65f2008-11-19 11:35:39 +00003401** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003402*/
danielk1977397d65f2008-11-19 11:35:39 +00003403static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3404 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003405 return 0;
3406}
3407
drhd9e5c4f2010-05-12 18:01:39 +00003408#ifndef SQLITE_OMIT_WAL
3409
3410
3411/*
3412** Object used to represent a single file opened and mmapped to provide
3413** shared memory. When multiple threads all reference the same
3414** log-summary, each thread has its own unixFile object, but they all
3415** point to a single instance of this object. In other words, each
3416** log-summary is opened only once per process.
3417**
3418** unixMutexHeld() must be true when creating or destroying
3419** this object or while reading or writing the following fields:
3420**
3421** nRef
3422** pNext
3423**
3424** The following fields are read-only after the object is created:
3425**
3426** fid
3427** zFilename
3428**
3429** Either unixShmFile.mutex must be held or unixShmFile.nRef==0 and
3430** unixMutexHeld() is true when reading or writing any other field
3431** in this structure.
3432**
3433** To avoid deadlocks, mutex and mutexBuf are always released in the
3434** reverse order that they are acquired. mutexBuf is always acquired
3435** first and released last. This invariant is check by asserting
3436** sqlite3_mutex_notheld() on mutex whenever mutexBuf is acquired or
3437** released.
3438*/
3439struct unixShmFile {
3440 struct unixFileId fid; /* Unique file identifier */
3441 sqlite3_mutex *mutex; /* Mutex to access this object */
3442 sqlite3_mutex *mutexBuf; /* Mutex to access zBuf[] */
3443 char *zFilename; /* Name of the mmapped file */
3444 int h; /* Open file descriptor */
3445 int szMap; /* Size of the mapping of file into memory */
3446 char *pMMapBuf; /* Where currently mmapped(). NULL if unmapped */
3447 int nRef; /* Number of unixShm objects pointing to this */
3448 unixShm *pFirst; /* All unixShm objects pointing to this */
3449 unixShmFile *pNext; /* Next in list of all unixShmFile objects */
3450#ifdef SQLITE_DEBUG
3451 u8 exclMask; /* Mask of exclusive locks held */
3452 u8 sharedMask; /* Mask of shared locks held */
3453 u8 nextShmId; /* Next available unixShm.id value */
3454#endif
3455};
3456
3457/*
3458** A global array of all unixShmFile objects.
3459**
3460** The unixMutexHeld() must be true while reading or writing this list.
3461*/
3462static unixShmFile *unixShmFileList = 0;
3463
3464/*
3465** Structure used internally by this VFS to record the state of an
3466** open shared memory connection.
3467**
3468** unixShm.pFile->mutex must be held while reading or writing the
3469** unixShm.pNext and unixShm.locks[] elements.
3470**
3471** The unixShm.pFile element is initialized when the object is created
3472** and is read-only thereafter.
3473*/
3474struct unixShm {
3475 unixShmFile *pFile; /* The underlying unixShmFile object */
3476 unixShm *pNext; /* Next unixShm with the same unixShmFile */
3477 u8 lockState; /* Current lock state */
3478 u8 hasMutex; /* True if holding the unixShmFile mutex */
3479 u8 hasMutexBuf; /* True if holding pFile->mutexBuf */
3480 u8 sharedMask; /* Mask of shared locks held */
3481 u8 exclMask; /* Mask of exclusive locks held */
3482#ifdef SQLITE_DEBUG
3483 u8 id; /* Id of this connection with its unixShmFile */
3484#endif
3485};
3486
3487/*
3488** Size increment by which shared memory grows
3489*/
3490#define SQLITE_UNIX_SHM_INCR 4096
3491
3492/*
3493** Constants used for locking
3494*/
3495#define UNIX_SHM_BASE 32 /* Byte offset of the first lock byte */
3496#define UNIX_SHM_DMS 0x01 /* Mask for Dead-Man-Switch lock */
3497#define UNIX_SHM_A 0x10 /* Mask for region locks... */
3498#define UNIX_SHM_B 0x20
3499#define UNIX_SHM_C 0x40
3500#define UNIX_SHM_D 0x80
3501
3502#ifdef SQLITE_DEBUG
3503/*
3504** Return a pointer to a nul-terminated string in static memory that
3505** describes a locking mask. The string is of the form "MSABCD" with
3506** each character representing a lock. "M" for MUTEX, "S" for DMS,
3507** and "A" through "D" for the region locks. If a lock is held, the
3508** letter is shown. If the lock is not held, the letter is converted
3509** to ".".
3510**
3511** This routine is for debugging purposes only and does not appear
3512** in a production build.
3513*/
3514static const char *unixShmLockString(u8 mask){
3515 static char zBuf[48];
3516 static int iBuf = 0;
3517 char *z;
3518
3519 z = &zBuf[iBuf];
3520 iBuf += 8;
3521 if( iBuf>=sizeof(zBuf) ) iBuf = 0;
3522
3523 z[0] = (mask & UNIX_SHM_DMS) ? 'S' : '.';
3524 z[1] = (mask & UNIX_SHM_A) ? 'A' : '.';
3525 z[2] = (mask & UNIX_SHM_B) ? 'B' : '.';
3526 z[3] = (mask & UNIX_SHM_C) ? 'C' : '.';
3527 z[4] = (mask & UNIX_SHM_D) ? 'D' : '.';
3528 z[5] = 0;
3529 return z;
3530}
3531#endif /* SQLITE_DEBUG */
3532
3533/*
3534** Apply posix advisory locks for all bytes identified in lockMask.
3535**
3536** lockMask might contain multiple bits but all bits are guaranteed
3537** to be contiguous.
3538**
3539** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3540** otherwise.
3541*/
3542static int unixShmSystemLock(
3543 unixShmFile *pFile, /* Apply locks to this open shared-memory segment */
3544 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
3545 u8 lockMask /* Which bytes to lock or unlock */
3546){
3547 struct flock f; /* The posix advisory locking structure */
3548 int lockOp; /* The opcode for fcntl() */
3549 int i; /* Offset into the locking byte range */
3550 int rc; /* Result code form fcntl() */
3551 u8 mask; /* Mask of bits in lockMask */
3552
3553 /* Access to the unixShmFile object is serialized by the caller */
3554 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
3555
3556 /* Initialize the locking parameters */
3557 memset(&f, 0, sizeof(f));
3558 f.l_type = lockType;
3559 f.l_whence = SEEK_SET;
3560 if( lockMask==UNIX_SHM_C && lockType!=F_UNLCK ){
3561 lockOp = F_SETLKW;
3562 OSTRACE(("SHM-LOCK requesting blocking lock\n"));
3563 }else{
3564 lockOp = F_SETLK;
3565 }
3566
3567 /* Find the first bit in lockMask that is set */
3568 for(i=0, mask=0x01; mask!=0 && (lockMask&mask)==0; mask <<= 1, i++){}
3569 assert( mask!=0 );
3570 f.l_start = i+UNIX_SHM_BASE;
3571 f.l_len = 1;
3572
3573 /* Extend the locking range for each additional bit that is set */
3574 mask <<= 1;
3575 while( mask!=0 && (lockMask & mask)!=0 ){
3576 f.l_len++;
3577 mask <<= 1;
3578 }
3579
3580 /* Verify that all bits set in lockMask are contiguous */
3581 assert( mask==0 || (lockMask & ~(mask | (mask-1)))==0 );
3582
3583 /* Acquire the system-level lock */
3584 rc = fcntl(pFile->h, lockOp, &f);
3585 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3586
3587 /* Update the global lock state and do debug tracing */
3588#ifdef SQLITE_DEBUG
3589 OSTRACE(("SHM-LOCK "));
3590 if( rc==SQLITE_OK ){
3591 if( lockType==F_UNLCK ){
3592 OSTRACE(("unlock ok"));
3593 pFile->exclMask &= ~lockMask;
3594 pFile->sharedMask &= ~lockMask;
3595 }else if( lockType==F_RDLCK ){
3596 OSTRACE(("read-lock ok"));
3597 pFile->exclMask &= ~lockMask;
3598 pFile->sharedMask |= lockMask;
3599 }else{
3600 assert( lockType==F_WRLCK );
3601 OSTRACE(("write-lock ok"));
3602 pFile->exclMask |= lockMask;
3603 pFile->sharedMask &= ~lockMask;
3604 }
3605 }else{
3606 if( lockType==F_UNLCK ){
3607 OSTRACE(("unlock failed"));
3608 }else if( lockType==F_RDLCK ){
3609 OSTRACE(("read-lock failed"));
3610 }else{
3611 assert( lockType==F_WRLCK );
3612 OSTRACE(("write-lock failed"));
3613 }
3614 }
3615 OSTRACE((" - change requested %s - afterwards %s:%s\n",
3616 unixShmLockString(lockMask),
3617 unixShmLockString(pFile->sharedMask),
3618 unixShmLockString(pFile->exclMask)));
3619#endif
3620
3621 return rc;
3622}
3623
3624/*
3625** For connection p, unlock all of the locks identified by the unlockMask
3626** parameter.
3627*/
3628static int unixShmUnlock(
3629 unixShmFile *pFile, /* The underlying shared-memory file */
3630 unixShm *p, /* The connection to be unlocked */
3631 u8 unlockMask /* Mask of locks to be unlocked */
3632){
3633 int rc; /* Result code */
3634 unixShm *pX; /* For looping over all sibling connections */
3635 u8 allMask; /* Union of locks held by connections other than "p" */
3636
3637 /* Access to the unixShmFile object is serialized by the caller */
3638 assert( sqlite3_mutex_held(pFile->mutex) );
3639
3640 /* Compute locks held by sibling connections */
3641 allMask = 0;
3642 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3643 if( pX==p ) continue;
3644 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3645 allMask |= pX->sharedMask;
3646 }
3647
3648 /* Unlock the system-level locks */
3649 if( (unlockMask & allMask)!=unlockMask ){
3650 rc = unixShmSystemLock(pFile, F_UNLCK, unlockMask & ~allMask);
3651 }else{
3652 rc = SQLITE_OK;
3653 }
3654
3655 /* Undo the local locks */
3656 if( rc==SQLITE_OK ){
3657 p->exclMask &= ~unlockMask;
3658 p->sharedMask &= ~unlockMask;
3659 }
3660 return rc;
3661}
3662
3663/*
3664** Get reader locks for connection p on all locks in the readMask parameter.
3665*/
3666static int unixShmSharedLock(
3667 unixShmFile *pFile, /* The underlying shared-memory file */
3668 unixShm *p, /* The connection to get the shared locks */
3669 u8 readMask /* Mask of shared locks to be acquired */
3670){
3671 int rc; /* Result code */
3672 unixShm *pX; /* For looping over all sibling connections */
3673 u8 allShared; /* Union of locks held by connections other than "p" */
3674
3675 /* Access to the unixShmFile object is serialized by the caller */
3676 assert( sqlite3_mutex_held(pFile->mutex) );
3677
3678 /* Find out which shared locks are already held by sibling connections.
3679 ** If any sibling already holds an exclusive lock, go ahead and return
3680 ** SQLITE_BUSY.
3681 */
3682 allShared = 0;
3683 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3684 if( pX==p ) continue;
3685 if( (pX->exclMask & readMask)!=0 ) return SQLITE_BUSY;
3686 allShared |= pX->sharedMask;
3687 }
3688
3689 /* Get shared locks at the system level, if necessary */
3690 if( (~allShared) & readMask ){
3691 rc = unixShmSystemLock(pFile, F_RDLCK, readMask);
3692 }else{
3693 rc = SQLITE_OK;
3694 }
3695
3696 /* Get the local shared locks */
3697 if( rc==SQLITE_OK ){
3698 p->sharedMask |= readMask;
3699 }
3700 return rc;
3701}
3702
3703/*
3704** For connection p, get an exclusive lock on all locks identified in
3705** the writeMask parameter.
3706*/
3707static int unixShmExclusiveLock(
3708 unixShmFile *pFile, /* The underlying shared-memory file */
3709 unixShm *p, /* The connection to get the exclusive locks */
3710 u8 writeMask /* Mask of exclusive locks to be acquired */
3711){
3712 int rc; /* Result code */
3713 unixShm *pX; /* For looping over all sibling connections */
3714
3715 /* Access to the unixShmFile object is serialized by the caller */
3716 assert( sqlite3_mutex_held(pFile->mutex) );
3717
3718 /* Make sure no sibling connections hold locks that will block this
3719 ** lock. If any do, return SQLITE_BUSY right away.
3720 */
3721 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3722 if( pX==p ) continue;
3723 if( (pX->exclMask & writeMask)!=0 ) return SQLITE_BUSY;
3724 if( (pX->sharedMask & writeMask)!=0 ) return SQLITE_BUSY;
3725 }
3726
3727 /* Get the exclusive locks at the system level. Then if successful
3728 ** also mark the local connection as being locked.
3729 */
3730 rc = unixShmSystemLock(pFile, F_WRLCK, writeMask);
3731 if( rc==SQLITE_OK ){
3732 p->sharedMask &= ~writeMask;
3733 p->exclMask |= writeMask;
3734 }
3735 return rc;
3736}
3737
3738/*
3739** Purge the unixShmFileList list of all entries with unixShmFile.nRef==0.
3740**
3741** This is not a VFS shared-memory method; it is a utility function called
3742** by VFS shared-memory methods.
3743*/
3744static void unixShmPurge(void){
3745 unixShmFile **pp;
3746 unixShmFile *p;
3747 assert( unixMutexHeld() );
3748 pp = &unixShmFileList;
3749 while( (p = *pp)!=0 ){
3750 if( p->nRef==0 ){
3751 if( p->mutex ) sqlite3_mutex_free(p->mutex);
3752 if( p->mutexBuf ) sqlite3_mutex_free(p->mutexBuf);
3753 if( p->h>=0 ) close(p->h);
3754 *pp = p->pNext;
3755 sqlite3_free(p);
3756 }else{
3757 pp = &p->pNext;
3758 }
3759 }
3760}
3761
3762/*
3763** Open a shared-memory area. This particular implementation uses
3764** mmapped files.
3765**
3766** zName is a filename used to identify the shared-memory area. The
3767** implementation does not (and perhaps should not) use this name
3768** directly, but rather use it as a template for finding an appropriate
3769** name for the shared-memory storage. In this implementation, the
3770** string "-index" is appended to zName and used as the name of the
3771** mmapped file.
3772**
3773** When opening a new shared-memory file, if no other instances of that
3774** file are currently open, in this process or in other processes, then
3775** the file must be truncated to zero length or have its header cleared.
3776*/
3777static int unixShmOpen(
3778 sqlite3_file *fd /* The file descriptor of the associated database */
3779){
3780 struct unixShm *p = 0; /* The connection to be opened */
3781 struct unixShmFile *pFile = 0; /* The underlying mmapped file */
3782 int rc; /* Result code */
3783 struct unixFileId fid; /* Unix file identifier */
3784 struct unixShmFile *pNew; /* Newly allocated pFile */
3785 struct stat sStat; /* Result from stat() an fstat() */
3786 struct unixFile *pDbFd; /* Underlying database file */
3787 int nPath; /* Size of pDbFd->zPath in bytes */
3788
3789 /* Allocate space for the new sqlite3_shm object. Also speculatively
3790 ** allocate space for a new unixShmFile and filename.
3791 */
3792 p = sqlite3_malloc( sizeof(*p) );
3793 if( p==0 ) return SQLITE_NOMEM;
3794 memset(p, 0, sizeof(*p));
3795 pDbFd = (struct unixFile*)fd;
3796 assert( pDbFd->pShm==0 );
3797 nPath = strlen(pDbFd->zPath);
3798 pNew = sqlite3_malloc( sizeof(*pFile) + nPath + 15 );
3799 if( pNew==0 ){
3800 sqlite3_free(p);
3801 return SQLITE_NOMEM;
3802 }
3803 memset(pNew, 0, sizeof(*pNew));
3804 pNew->zFilename = (char*)&pNew[1];
3805 sqlite3_snprintf(nPath+15, pNew->zFilename, "%s-wal-index", pDbFd->zPath);
3806
3807 /* Look to see if there is an existing unixShmFile that can be used.
3808 ** If no matching unixShmFile currently exists, create a new one.
3809 */
3810 unixEnterMutex();
3811 rc = stat(pNew->zFilename, &sStat);
3812 if( rc==0 ){
3813 memset(&fid, 0, sizeof(fid));
3814 fid.dev = sStat.st_dev;
3815 fid.ino = sStat.st_ino;
3816 for(pFile = unixShmFileList; pFile; pFile=pFile->pNext){
3817 if( memcmp(&pFile->fid, &fid, sizeof(fid))==0 ) break;
3818 }
3819 }
3820 if( pFile ){
3821 sqlite3_free(pNew);
3822 }else{
3823 pFile = pNew;
3824 pNew = 0;
3825 pFile->h = -1;
3826 pFile->pNext = unixShmFileList;
3827 unixShmFileList = pFile;
3828
3829 pFile->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3830 if( pFile->mutex==0 ){
3831 rc = SQLITE_NOMEM;
3832 goto shm_open_err;
3833 }
3834 pFile->mutexBuf = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3835 if( pFile->mutexBuf==0 ){
3836 rc = SQLITE_NOMEM;
3837 goto shm_open_err;
3838 }
3839
3840 pFile->h = open(pFile->zFilename, O_RDWR|O_CREAT, 0664);
3841 if( pFile->h<0 ){
3842 rc = SQLITE_CANTOPEN_BKPT;
3843 goto shm_open_err;
3844 }
3845
3846 rc = fstat(pFile->h, &sStat);
3847 if( rc ){
3848 rc = SQLITE_CANTOPEN_BKPT;
3849 goto shm_open_err;
3850 }
3851 pFile->fid.dev = sStat.st_dev;
3852 pFile->fid.ino = sStat.st_ino;
3853
3854 /* Check to see if another process is holding the dead-man switch.
3855 ** If not, truncate the file to zero length.
3856 */
3857 if( unixShmSystemLock(pFile, F_WRLCK, UNIX_SHM_DMS)==SQLITE_OK ){
3858 if( ftruncate(pFile->h, 0) ){
3859 rc = SQLITE_IOERR;
3860 }
3861 }
3862 if( rc==SQLITE_OK ){
3863 rc = unixShmSystemLock(pFile, F_RDLCK, UNIX_SHM_DMS);
3864 }
3865 if( rc ) goto shm_open_err;
3866 }
3867
3868 /* Make the new connection a child of the unixShmFile */
3869 p->pFile = pFile;
3870 p->pNext = pFile->pFirst;
3871#ifdef SQLITE_DEBUG
3872 p->id = pFile->nextShmId++;
3873#endif
3874 pFile->pFirst = p;
3875 pFile->nRef++;
3876 pDbFd->pShm = p;
3877 unixLeaveMutex();
3878 return SQLITE_OK;
3879
3880 /* Jump here on any error */
3881shm_open_err:
3882 unixShmPurge(); /* This call frees pFile if required */
3883 sqlite3_free(p);
3884 sqlite3_free(pNew);
3885 unixLeaveMutex();
3886 return rc;
3887}
3888
3889/*
3890** Close a connection to shared-memory. Delete the underlying
3891** storage if deleteFlag is true.
3892*/
3893static int unixShmClose(
3894 sqlite3_file *fd, /* The underlying database file */
3895 int deleteFlag /* Delete shared-memory if true */
3896){
3897 unixShm *p; /* The connection to be closed */
3898 unixShmFile *pFile; /* The underlying shared-memory file */
3899 unixShm **pp; /* For looping over sibling connections */
3900 unixFile *pDbFd; /* The underlying database file */
3901
3902 pDbFd = (unixFile*)fd;
3903 p = pDbFd->pShm;
3904 if( p==0 ) return SQLITE_OK;
3905 pFile = p->pFile;
3906
3907 /* Verify that the connection being closed holds no locks */
3908 assert( p->exclMask==0 );
3909 assert( p->sharedMask==0 );
3910
3911 /* Remove connection p from the set of connections associated with pFile */
3912 sqlite3_mutex_enter(pFile->mutex);
3913 for(pp=&pFile->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3914 *pp = p->pNext;
3915
3916 /* Free the connection p */
3917 sqlite3_free(p);
3918 pDbFd->pShm = 0;
3919 sqlite3_mutex_leave(pFile->mutex);
3920
3921 /* If pFile->nRef has reached 0, then close the underlying
3922 ** shared-memory file, too */
3923 unixEnterMutex();
3924 assert( pFile->nRef>0 );
3925 pFile->nRef--;
3926 if( pFile->nRef==0 ){
3927 if( deleteFlag ) unlink(pFile->zFilename);
3928 unixShmPurge();
3929 }
3930 unixLeaveMutex();
3931
3932 return SQLITE_OK;
3933}
3934
3935/*
3936** Query and/or changes the size of the underlying storage for
3937** a shared-memory segment. The reqSize parameter is the new size
3938** of the underlying storage, or -1 to do just a query. The size
3939** of the underlying storage (after resizing if resizing occurs) is
3940** written into pNewSize.
3941**
3942** This routine does not (necessarily) change the size of the mapping
3943** of the underlying storage into memory. Use xShmGet() to change
3944** the mapping size.
3945**
3946** The reqSize parameter is the minimum size requested. The implementation
3947** is free to expand the storage to some larger amount if it chooses.
3948*/
3949static int unixShmSize(
3950 sqlite3_file *fd, /* The open database file holding SHM */
3951 int reqSize, /* Requested size. -1 for query only */
3952 int *pNewSize /* Write new size here */
3953){
3954 unixFile *pDbFd = (unixFile*)fd;
3955 unixShm *p = pDbFd->pShm;
3956 unixShmFile *pFile = p->pFile;
3957 int rc = SQLITE_OK;
3958 struct stat sStat;
3959
3960 if( reqSize>=0 ){
3961 reqSize = (reqSize + SQLITE_UNIX_SHM_INCR - 1)/SQLITE_UNIX_SHM_INCR;
3962 reqSize *= SQLITE_UNIX_SHM_INCR;
3963 rc = ftruncate(pFile->h, reqSize);
3964 }
3965 if( fstat(pFile->h, &sStat)==0 ){
3966 *pNewSize = (int)sStat.st_size;
3967 }else{
3968 *pNewSize = 0;
3969 rc = SQLITE_IOERR;
3970 }
3971 return rc;
3972}
3973
3974
3975/*
3976** Map the shared storage into memory. The minimum size of the
3977** mapping should be reqMapSize if reqMapSize is positive. If
3978** reqMapSize is zero or negative, the implementation can choose
3979** whatever mapping size is convenient.
3980**
3981** *ppBuf is made to point to the memory which is a mapping of the
3982** underlying storage. A mutex is acquired to prevent other threads
3983** from running while *ppBuf is in use in order to prevent other threads
3984** remapping *ppBuf out from under this thread. The unixShmRelease()
3985** call will release the mutex. However, if the lock state is CHECKPOINT,
3986** the mutex is not acquired because CHECKPOINT will never remap the
3987** buffer. RECOVER might remap, though, so CHECKPOINT will acquire
3988** the mutex if and when it promotes to RECOVER.
3989**
3990** RECOVER needs to be atomic. The same mutex that prevents *ppBuf from
3991** being remapped also prevents more than one thread from being in
3992** RECOVER at a time. But, RECOVER sometimes wants to remap itself.
3993** To prevent RECOVER from losing its lock while remapping, the
3994** mutex is not released by unixShmRelease() when in RECOVER.
3995**
3996** *pNewMapSize is set to the size of the mapping.
3997**
3998** *ppBuf and *pNewMapSize might be NULL and zero if no space has
3999** yet been allocated to the underlying storage.
4000*/
4001static int unixShmGet(
4002 sqlite3_file *fd, /* Database file holding shared memory */
4003 int reqMapSize, /* Requested size of mapping. -1 means don't care */
4004 int *pNewMapSize, /* Write new size of mapping here */
4005 void **ppBuf /* Write mapping buffer origin here */
4006){
4007 unixFile *pDbFd = (unixFile*)fd;
4008 unixShm *p = pDbFd->pShm;
4009 unixShmFile *pFile = p->pFile;
4010 int rc = SQLITE_OK;
4011
4012 if( p->lockState!=SQLITE_SHM_CHECKPOINT && p->hasMutexBuf==0 ){
4013 assert( sqlite3_mutex_notheld(pFile->mutex) );
4014 sqlite3_mutex_enter(pFile->mutexBuf);
4015 p->hasMutexBuf = 1;
4016 }
4017 sqlite3_mutex_enter(pFile->mutex);
4018 if( pFile->szMap==0 || reqMapSize>pFile->szMap ){
4019 int actualSize;
4020 if( unixShmSize(fd, -1, &actualSize)==SQLITE_OK
4021 && reqMapSize<actualSize
4022 ){
4023 reqMapSize = actualSize;
4024 }
4025 if( pFile->pMMapBuf ){
4026 munmap(pFile->pMMapBuf, pFile->szMap);
4027 }
4028 pFile->pMMapBuf = mmap(0, reqMapSize, PROT_READ|PROT_WRITE, MAP_SHARED,
4029 pFile->h, 0);
4030 pFile->szMap = pFile->pMMapBuf ? reqMapSize : 0;
4031 }
4032 *pNewMapSize = pFile->szMap;
4033 *ppBuf = pFile->pMMapBuf;
4034 sqlite3_mutex_leave(pFile->mutex);
4035 return rc;
4036}
4037
4038/*
4039** Release the lock held on the shared memory segment to that other
4040** threads are free to resize it if necessary.
4041**
4042** If the lock is not currently held, this routine is a harmless no-op.
4043**
4044** If the shared-memory object is in lock state RECOVER, then we do not
4045** really want to release the lock, so in that case too, this routine
4046** is a no-op.
4047*/
4048static int unixShmRelease(sqlite3_file *fd){
4049 unixFile *pDbFd = (unixFile*)fd;
4050 unixShm *p = pDbFd->pShm;
4051
4052 if( p->hasMutexBuf && p->lockState!=SQLITE_SHM_RECOVER ){
4053 assert( sqlite3_mutex_notheld(p->pFile->mutex) );
4054 sqlite3_mutex_leave(p->pFile->mutexBuf);
4055 p->hasMutexBuf = 0;
4056 }
4057 return SQLITE_OK;
4058}
4059
4060/*
4061** Symbolic names for LOCK states used for debugging.
4062*/
4063#ifdef SQLITE_DEBUG
4064static const char *azLkName[] = {
4065 "UNLOCK",
4066 "READ",
4067 "READ_FULL",
4068 "WRITE",
4069 "PENDING",
4070 "CHECKPOINT",
4071 "RECOVER"
4072};
4073#endif
4074
4075
4076/*
4077** Change the lock state for a shared-memory segment.
4078*/
4079static int unixShmLock(
4080 sqlite3_file *fd, /* Database file holding the shared memory */
4081 int desiredLock, /* One of SQLITE_SHM_xxxxx locking states */
4082 int *pGotLock /* The lock you actually got */
4083){
4084 unixFile *pDbFd = (unixFile*)fd;
4085 unixShm *p = pDbFd->pShm;
4086 unixShmFile *pFile = p->pFile;
4087 int rc = SQLITE_PROTOCOL;
4088
4089 /* Note that SQLITE_SHM_READ_FULL and SQLITE_SHM_PENDING are never
4090 ** directly requested; they are side effects from requesting
4091 ** SQLITE_SHM_READ and SQLITE_SHM_CHECKPOINT, respectively.
4092 */
4093 assert( desiredLock==SQLITE_SHM_UNLOCK
4094 || desiredLock==SQLITE_SHM_READ
4095 || desiredLock==SQLITE_SHM_WRITE
4096 || desiredLock==SQLITE_SHM_CHECKPOINT
4097 || desiredLock==SQLITE_SHM_RECOVER );
4098
4099 /* Return directly if this is just a lock state query, or if
4100 ** the connection is already in the desired locking state.
4101 */
4102 if( desiredLock==p->lockState
4103 || (desiredLock==SQLITE_SHM_READ && p->lockState==SQLITE_SHM_READ_FULL)
4104 ){
4105 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s and got %s\n",
4106 p->id, getpid(), azLkName[desiredLock], azLkName[p->lockState]));
4107 if( pGotLock ) *pGotLock = p->lockState;
4108 return SQLITE_OK;
4109 }
4110
4111 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s->%s\n",
4112 p->id, getpid(), azLkName[p->lockState], azLkName[desiredLock]));
4113
4114 if( desiredLock==SQLITE_SHM_RECOVER && !p->hasMutexBuf ){
4115 assert( sqlite3_mutex_notheld(pFile->mutex) );
4116 sqlite3_mutex_enter(pFile->mutexBuf);
4117 p->hasMutexBuf = 1;
4118 }
4119 sqlite3_mutex_enter(pFile->mutex);
4120 switch( desiredLock ){
4121 case SQLITE_SHM_UNLOCK: {
4122 assert( p->lockState!=SQLITE_SHM_RECOVER );
4123 unixShmUnlock(pFile, p, UNIX_SHM_A|UNIX_SHM_B|UNIX_SHM_C|UNIX_SHM_D);
4124 rc = SQLITE_OK;
4125 p->lockState = SQLITE_SHM_UNLOCK;
4126 break;
4127 }
4128 case SQLITE_SHM_READ: {
4129 if( p->lockState==SQLITE_SHM_UNLOCK ){
4130 int nAttempt;
4131 rc = SQLITE_BUSY;
4132 assert( p->lockState==SQLITE_SHM_UNLOCK );
4133 for(nAttempt=0; nAttempt<5 && rc==SQLITE_BUSY; nAttempt++){
4134 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A|UNIX_SHM_B);
4135 if( rc==SQLITE_BUSY ){
4136 rc = unixShmSharedLock(pFile, p, UNIX_SHM_D);
4137 if( rc==SQLITE_OK ){
4138 p->lockState = SQLITE_SHM_READ_FULL;
4139 }
4140 }else{
4141 unixShmUnlock(pFile, p, UNIX_SHM_B);
4142 p->lockState = SQLITE_SHM_READ;
4143 }
4144 }
4145 }else{
4146 assert( p->lockState==SQLITE_SHM_WRITE
4147 || p->lockState==SQLITE_SHM_RECOVER );
4148 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A);
4149 unixShmUnlock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
4150 p->lockState = SQLITE_SHM_READ;
4151 }
4152 break;
4153 }
4154 case SQLITE_SHM_WRITE: {
4155 assert( p->lockState==SQLITE_SHM_READ
4156 || p->lockState==SQLITE_SHM_READ_FULL );
4157 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
4158 if( rc==SQLITE_OK ){
4159 p->lockState = SQLITE_SHM_WRITE;
4160 }
4161 break;
4162 }
4163 case SQLITE_SHM_CHECKPOINT: {
4164 assert( p->lockState==SQLITE_SHM_UNLOCK
4165 || p->lockState==SQLITE_SHM_PENDING
4166 );
4167 if( p->lockState==SQLITE_SHM_UNLOCK ){
4168 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_B|UNIX_SHM_C);
4169 if( rc==SQLITE_OK ){
4170 p->lockState = SQLITE_SHM_PENDING;
4171 }
4172 }
4173 if( p->lockState==SQLITE_SHM_PENDING ){
4174 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_A);
4175 if( rc==SQLITE_OK ){
4176 p->lockState = SQLITE_SHM_CHECKPOINT;
4177 }
4178 }
4179 break;
4180 }
4181 default: {
4182 assert( desiredLock==SQLITE_SHM_RECOVER );
4183 assert( p->lockState==SQLITE_SHM_READ
4184 || p->lockState==SQLITE_SHM_READ_FULL
4185 );
4186 assert( sqlite3_mutex_held(pFile->mutexBuf) );
4187 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C);
4188 if( rc==SQLITE_OK ){
4189 p->lockState = SQLITE_SHM_RECOVER;
4190 }
4191 break;
4192 }
4193 }
4194 sqlite3_mutex_leave(pFile->mutex);
4195 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %s\n",
4196 p->id, getpid(), azLkName[p->lockState]));
4197 if( pGotLock ) *pGotLock = p->lockState;
4198 return rc;
4199}
4200
4201#else
4202# define unixShmOpen 0
4203# define unixShmSize 0
4204# define unixShmGet 0
4205# define unixShmRelease 0
4206# define unixShmLock 0
4207# define unixShmClose 0
4208#endif /* #ifndef SQLITE_OMIT_WAL */
4209
drh734c9862008-11-28 15:37:20 +00004210/*
4211** Here ends the implementation of all sqlite3_file methods.
4212**
4213********************** End sqlite3_file Methods *******************************
4214******************************************************************************/
4215
4216/*
drh6b9d6dd2008-12-03 19:34:47 +00004217** This division contains definitions of sqlite3_io_methods objects that
4218** implement various file locking strategies. It also contains definitions
4219** of "finder" functions. A finder-function is used to locate the appropriate
4220** sqlite3_io_methods object for a particular database file. The pAppData
4221** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4222** the correct finder-function for that VFS.
4223**
4224** Most finder functions return a pointer to a fixed sqlite3_io_methods
4225** object. The only interesting finder-function is autolockIoFinder, which
4226** looks at the filesystem type and tries to guess the best locking
4227** strategy from that.
4228**
drh1875f7a2008-12-08 18:19:17 +00004229** For finder-funtion F, two objects are created:
4230**
4231** (1) The real finder-function named "FImpt()".
4232**
dane946c392009-08-22 11:39:46 +00004233** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004234**
4235**
4236** A pointer to the F pointer is used as the pAppData value for VFS
4237** objects. We have to do this instead of letting pAppData point
4238** directly at the finder-function since C90 rules prevent a void*
4239** from be cast into a function pointer.
4240**
drh6b9d6dd2008-12-03 19:34:47 +00004241**
drh7708e972008-11-29 00:56:52 +00004242** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004243**
drh7708e972008-11-29 00:56:52 +00004244** * A constant sqlite3_io_methods object call METHOD that has locking
4245** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4246**
4247** * An I/O method finder function called FINDER that returns a pointer
4248** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004249*/
drhd9e5c4f2010-05-12 18:01:39 +00004250#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004251static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004252 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004253 CLOSE, /* xClose */ \
4254 unixRead, /* xRead */ \
4255 unixWrite, /* xWrite */ \
4256 unixTruncate, /* xTruncate */ \
4257 unixSync, /* xSync */ \
4258 unixFileSize, /* xFileSize */ \
4259 LOCK, /* xLock */ \
4260 UNLOCK, /* xUnlock */ \
4261 CKLOCK, /* xCheckReservedLock */ \
4262 unixFileControl, /* xFileControl */ \
4263 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004264 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
4265 unixShmOpen, /* xShmOpen */ \
4266 unixShmSize, /* xShmSize */ \
4267 unixShmGet, /* xShmGet */ \
4268 unixShmRelease, /* xShmRelease */ \
4269 unixShmLock, /* xShmLock */ \
4270 unixShmClose /* xShmClose */ \
drh7708e972008-11-29 00:56:52 +00004271}; \
drh0c2694b2009-09-03 16:23:44 +00004272static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4273 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004274 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004275} \
drh0c2694b2009-09-03 16:23:44 +00004276static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004277 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004278
4279/*
4280** Here are all of the sqlite3_io_methods objects for each of the
4281** locking strategies. Functions that return pointers to these methods
4282** are also created.
4283*/
4284IOMETHODS(
4285 posixIoFinder, /* Finder function name */
4286 posixIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004287 2, /* ShmOpen is enabled */
drh7708e972008-11-29 00:56:52 +00004288 unixClose, /* xClose method */
4289 unixLock, /* xLock method */
4290 unixUnlock, /* xUnlock method */
4291 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004292)
drh7708e972008-11-29 00:56:52 +00004293IOMETHODS(
4294 nolockIoFinder, /* Finder function name */
4295 nolockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004296 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004297 nolockClose, /* xClose method */
4298 nolockLock, /* xLock method */
4299 nolockUnlock, /* xUnlock method */
4300 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004301)
drh7708e972008-11-29 00:56:52 +00004302IOMETHODS(
4303 dotlockIoFinder, /* Finder function name */
4304 dotlockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004305 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004306 dotlockClose, /* xClose method */
4307 dotlockLock, /* xLock method */
4308 dotlockUnlock, /* xUnlock method */
4309 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004310)
drh7708e972008-11-29 00:56:52 +00004311
chw78a13182009-04-07 05:35:03 +00004312#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004313IOMETHODS(
4314 flockIoFinder, /* Finder function name */
4315 flockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004316 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004317 flockClose, /* xClose method */
4318 flockLock, /* xLock method */
4319 flockUnlock, /* xUnlock method */
4320 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004321)
drh7708e972008-11-29 00:56:52 +00004322#endif
4323
drh6c7d5c52008-11-21 20:32:33 +00004324#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004325IOMETHODS(
4326 semIoFinder, /* Finder function name */
4327 semIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004328 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004329 semClose, /* xClose method */
4330 semLock, /* xLock method */
4331 semUnlock, /* xUnlock method */
4332 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004333)
aswiftaebf4132008-11-21 00:10:35 +00004334#endif
drh7708e972008-11-29 00:56:52 +00004335
drhd2cb50b2009-01-09 21:41:17 +00004336#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004337IOMETHODS(
4338 afpIoFinder, /* Finder function name */
4339 afpIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004340 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004341 afpClose, /* xClose method */
4342 afpLock, /* xLock method */
4343 afpUnlock, /* xUnlock method */
4344 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004345)
drh715ff302008-12-03 22:32:44 +00004346#endif
4347
4348/*
4349** The proxy locking method is a "super-method" in the sense that it
4350** opens secondary file descriptors for the conch and lock files and
4351** it uses proxy, dot-file, AFP, and flock() locking methods on those
4352** secondary files. For this reason, the division that implements
4353** proxy locking is located much further down in the file. But we need
4354** to go ahead and define the sqlite3_io_methods and finder function
4355** for proxy locking here. So we forward declare the I/O methods.
4356*/
drhd2cb50b2009-01-09 21:41:17 +00004357#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004358static int proxyClose(sqlite3_file*);
4359static int proxyLock(sqlite3_file*, int);
4360static int proxyUnlock(sqlite3_file*, int);
4361static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004362IOMETHODS(
4363 proxyIoFinder, /* Finder function name */
4364 proxyIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004365 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004366 proxyClose, /* xClose method */
4367 proxyLock, /* xLock method */
4368 proxyUnlock, /* xUnlock method */
4369 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004370)
aswiftaebf4132008-11-21 00:10:35 +00004371#endif
drh7708e972008-11-29 00:56:52 +00004372
drh7ed97b92010-01-20 13:07:21 +00004373/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4374#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4375IOMETHODS(
4376 nfsIoFinder, /* Finder function name */
4377 nfsIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004378 1, /* ShmOpen is disabled */
drh7ed97b92010-01-20 13:07:21 +00004379 unixClose, /* xClose method */
4380 unixLock, /* xLock method */
4381 nfsUnlock, /* xUnlock method */
4382 unixCheckReservedLock /* xCheckReservedLock method */
4383)
4384#endif
drh7708e972008-11-29 00:56:52 +00004385
drhd2cb50b2009-01-09 21:41:17 +00004386#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004387/*
drh6b9d6dd2008-12-03 19:34:47 +00004388** This "finder" function attempts to determine the best locking strategy
4389** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004390** object that implements that strategy.
4391**
4392** This is for MacOSX only.
4393*/
drh1875f7a2008-12-08 18:19:17 +00004394static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004395 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004396 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004397){
4398 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004399 const char *zFilesystem; /* Filesystem type name */
4400 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004401 } aMap[] = {
4402 { "hfs", &posixIoMethods },
4403 { "ufs", &posixIoMethods },
4404 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004405 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004406 { "webdav", &nolockIoMethods },
4407 { 0, 0 }
4408 };
4409 int i;
4410 struct statfs fsInfo;
4411 struct flock lockInfo;
4412
4413 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004414 /* If filePath==NULL that means we are dealing with a transient file
4415 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004416 return &nolockIoMethods;
4417 }
4418 if( statfs(filePath, &fsInfo) != -1 ){
4419 if( fsInfo.f_flags & MNT_RDONLY ){
4420 return &nolockIoMethods;
4421 }
4422 for(i=0; aMap[i].zFilesystem; i++){
4423 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4424 return aMap[i].pMethods;
4425 }
4426 }
4427 }
4428
4429 /* Default case. Handles, amongst others, "nfs".
4430 ** Test byte-range lock using fcntl(). If the call succeeds,
4431 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004432 */
drh7708e972008-11-29 00:56:52 +00004433 lockInfo.l_len = 1;
4434 lockInfo.l_start = 0;
4435 lockInfo.l_whence = SEEK_SET;
4436 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004437 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004438 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4439 return &nfsIoMethods;
4440 } else {
4441 return &posixIoMethods;
4442 }
drh7708e972008-11-29 00:56:52 +00004443 }else{
4444 return &dotlockIoMethods;
4445 }
4446}
drh0c2694b2009-09-03 16:23:44 +00004447static const sqlite3_io_methods
4448 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004449
drhd2cb50b2009-01-09 21:41:17 +00004450#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004451
chw78a13182009-04-07 05:35:03 +00004452#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4453/*
4454** This "finder" function attempts to determine the best locking strategy
4455** for the database file "filePath". It then returns the sqlite3_io_methods
4456** object that implements that strategy.
4457**
4458** This is for VXWorks only.
4459*/
4460static const sqlite3_io_methods *autolockIoFinderImpl(
4461 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004462 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004463){
4464 struct flock lockInfo;
4465
4466 if( !filePath ){
4467 /* If filePath==NULL that means we are dealing with a transient file
4468 ** that does not need to be locked. */
4469 return &nolockIoMethods;
4470 }
4471
4472 /* Test if fcntl() is supported and use POSIX style locks.
4473 ** Otherwise fall back to the named semaphore method.
4474 */
4475 lockInfo.l_len = 1;
4476 lockInfo.l_start = 0;
4477 lockInfo.l_whence = SEEK_SET;
4478 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004479 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004480 return &posixIoMethods;
4481 }else{
4482 return &semIoMethods;
4483 }
4484}
drh0c2694b2009-09-03 16:23:44 +00004485static const sqlite3_io_methods
4486 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004487
4488#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4489
drh7708e972008-11-29 00:56:52 +00004490/*
4491** An abstract type for a pointer to a IO method finder function:
4492*/
drh0c2694b2009-09-03 16:23:44 +00004493typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004494
aswiftaebf4132008-11-21 00:10:35 +00004495
drh734c9862008-11-28 15:37:20 +00004496/****************************************************************************
4497**************************** sqlite3_vfs methods ****************************
4498**
4499** This division contains the implementation of methods on the
4500** sqlite3_vfs object.
4501*/
4502
danielk1977a3d4c882007-03-23 10:08:38 +00004503/*
danielk1977e339d652008-06-28 11:23:00 +00004504** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004505*/
4506static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004507 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004508 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004509 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004510 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004511 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004512 int noLock, /* Omit locking if true */
4513 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004514){
drh7708e972008-11-29 00:56:52 +00004515 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004516 unixFile *pNew = (unixFile *)pId;
4517 int rc = SQLITE_OK;
4518
danielk197717b90b52008-06-06 11:11:25 +00004519 assert( pNew->pLock==NULL );
4520 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00004521
dane946c392009-08-22 11:39:46 +00004522 /* Parameter isDelete is only used on vxworks. Express this explicitly
4523 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004524 */
drh7708e972008-11-29 00:56:52 +00004525 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004526
drh218c5082008-03-07 00:27:10 +00004527 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00004528 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004529 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00004530 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00004531 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004532 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
4533 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004534
drh6c7d5c52008-11-21 20:32:33 +00004535#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004536 pNew->pId = vxworksFindFileId(zFilename);
4537 if( pNew->pId==0 ){
4538 noLock = 1;
4539 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004540 }
4541#endif
4542
drhda0e7682008-07-30 15:27:54 +00004543 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004544 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004545 }else{
drh0c2694b2009-09-03 16:23:44 +00004546 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004547#if SQLITE_ENABLE_LOCKING_STYLE
4548 /* Cache zFilename in the locking context (AFP and dotlock override) for
4549 ** proxyLock activation is possible (remote proxy is based on db name)
4550 ** zFilename remains valid until file is closed, to support */
4551 pNew->lockingContext = (void*)zFilename;
4552#endif
drhda0e7682008-07-30 15:27:54 +00004553 }
danielk1977e339d652008-06-28 11:23:00 +00004554
drh7ed97b92010-01-20 13:07:21 +00004555 if( pLockingStyle == &posixIoMethods
4556#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4557 || pLockingStyle == &nfsIoMethods
4558#endif
4559 ){
drh7708e972008-11-29 00:56:52 +00004560 unixEnterMutex();
4561 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00004562 if( rc!=SQLITE_OK ){
4563 /* If an error occured in findLockInfo(), close the file descriptor
4564 ** immediately, before releasing the mutex. findLockInfo() may fail
4565 ** in two scenarios:
4566 **
4567 ** (a) A call to fstat() failed.
4568 ** (b) A malloc failed.
4569 **
4570 ** Scenario (b) may only occur if the process is holding no other
4571 ** file descriptors open on the same file. If there were other file
4572 ** descriptors on this file, then no malloc would be required by
4573 ** findLockInfo(). If this is the case, it is quite safe to close
4574 ** handle h - as it is guaranteed that no posix locks will be released
4575 ** by doing so.
4576 **
4577 ** If scenario (a) caused the error then things are not so safe. The
4578 ** implicit assumption here is that if fstat() fails, things are in
4579 ** such bad shape that dropping a lock or two doesn't matter much.
4580 */
4581 close(h);
4582 h = -1;
4583 }
drh7708e972008-11-29 00:56:52 +00004584 unixLeaveMutex();
4585 }
danielk1977e339d652008-06-28 11:23:00 +00004586
drhd2cb50b2009-01-09 21:41:17 +00004587#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004588 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004589 /* AFP locking uses the file path so it needs to be included in
4590 ** the afpLockingContext.
4591 */
4592 afpLockingContext *pCtx;
4593 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4594 if( pCtx==0 ){
4595 rc = SQLITE_NOMEM;
4596 }else{
4597 /* NB: zFilename exists and remains valid until the file is closed
4598 ** according to requirement F11141. So we do not need to make a
4599 ** copy of the filename. */
4600 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004601 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004602 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004603 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00004604 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
4605 if( rc!=SQLITE_OK ){
4606 sqlite3_free(pNew->lockingContext);
4607 close(h);
4608 h = -1;
4609 }
drh7708e972008-11-29 00:56:52 +00004610 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004611 }
drh7708e972008-11-29 00:56:52 +00004612 }
4613#endif
danielk1977e339d652008-06-28 11:23:00 +00004614
drh7708e972008-11-29 00:56:52 +00004615 else if( pLockingStyle == &dotlockIoMethods ){
4616 /* Dotfile locking uses the file path so it needs to be included in
4617 ** the dotlockLockingContext
4618 */
4619 char *zLockFile;
4620 int nFilename;
drhea678832008-12-10 19:26:22 +00004621 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004622 zLockFile = (char *)sqlite3_malloc(nFilename);
4623 if( zLockFile==0 ){
4624 rc = SQLITE_NOMEM;
4625 }else{
4626 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004627 }
drh7708e972008-11-29 00:56:52 +00004628 pNew->lockingContext = zLockFile;
4629 }
danielk1977e339d652008-06-28 11:23:00 +00004630
drh6c7d5c52008-11-21 20:32:33 +00004631#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004632 else if( pLockingStyle == &semIoMethods ){
4633 /* Named semaphore locking uses the file path so it needs to be
4634 ** included in the semLockingContext
4635 */
4636 unixEnterMutex();
4637 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
4638 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
4639 char *zSemName = pNew->pOpen->aSemName;
4640 int n;
drh2238dcc2009-08-27 17:56:20 +00004641 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004642 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004643 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004644 if( zSemName[n]=='/' ) zSemName[n] = '_';
4645 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4646 if( pNew->pOpen->pSem == SEM_FAILED ){
4647 rc = SQLITE_NOMEM;
4648 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004649 }
chw97185482008-11-17 08:05:31 +00004650 }
drh7708e972008-11-29 00:56:52 +00004651 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004652 }
drh7708e972008-11-29 00:56:52 +00004653#endif
aswift5b1a2562008-08-22 00:22:35 +00004654
4655 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004656#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004657 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004658 if( h>=0 ) close(h);
4659 h = -1;
chw97185482008-11-17 08:05:31 +00004660 unlink(zFilename);
4661 isDelete = 0;
4662 }
4663 pNew->isDelete = isDelete;
4664#endif
danielk1977e339d652008-06-28 11:23:00 +00004665 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004666 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004667 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004668 }else{
drh7708e972008-11-29 00:56:52 +00004669 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004670 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004671 }
danielk1977e339d652008-06-28 11:23:00 +00004672 return rc;
drh054889e2005-11-30 03:20:31 +00004673}
drh9c06c952005-11-26 00:25:00 +00004674
danielk1977ad94b582007-08-20 06:44:22 +00004675/*
4676** Open a file descriptor to the directory containing file zFilename.
4677** If successful, *pFd is set to the opened file descriptor and
4678** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4679** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4680** value.
4681**
4682** If SQLITE_OK is returned, the caller is responsible for closing
4683** the file descriptor *pFd using close().
4684*/
danielk1977fee2d252007-08-18 10:59:19 +00004685static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004686 int ii;
drh777b17a2007-09-20 10:02:54 +00004687 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004688 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004689
drh153c62c2007-08-24 03:51:33 +00004690 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004691 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004692 if( ii>0 ){
4693 zDirname[ii] = '\0';
4694 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004695 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004696#ifdef FD_CLOEXEC
4697 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4698#endif
4699 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
4700 }
4701 }
danielk1977fee2d252007-08-18 10:59:19 +00004702 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004703 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004704}
4705
danielk1977b4b47412007-08-17 15:53:36 +00004706/*
danielk197717b90b52008-06-06 11:11:25 +00004707** Create a temporary file name in zBuf. zBuf must be allocated
4708** by the calling process and must be big enough to hold at least
4709** pVfs->mxPathname bytes.
4710*/
4711static int getTempname(int nBuf, char *zBuf){
4712 static const char *azDirs[] = {
4713 0,
aswiftaebf4132008-11-21 00:10:35 +00004714 0,
danielk197717b90b52008-06-06 11:11:25 +00004715 "/var/tmp",
4716 "/usr/tmp",
4717 "/tmp",
4718 ".",
4719 };
4720 static const unsigned char zChars[] =
4721 "abcdefghijklmnopqrstuvwxyz"
4722 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4723 "0123456789";
drh41022642008-11-21 00:24:42 +00004724 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00004725 struct stat buf;
4726 const char *zDir = ".";
4727
4728 /* It's odd to simulate an io-error here, but really this is just
4729 ** using the io-error infrastructure to test that SQLite handles this
4730 ** function failing.
4731 */
4732 SimulateIOError( return SQLITE_IOERR );
4733
4734 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00004735 if (NULL == azDirs[1]) {
4736 azDirs[1] = getenv("TMPDIR");
4737 }
4738
4739 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00004740 if( azDirs[i]==0 ) continue;
4741 if( stat(azDirs[i], &buf) ) continue;
4742 if( !S_ISDIR(buf.st_mode) ) continue;
4743 if( access(azDirs[i], 07) ) continue;
4744 zDir = azDirs[i];
4745 break;
4746 }
4747
4748 /* Check that the output buffer is large enough for the temporary file
4749 ** name. If it is not, return SQLITE_ERROR.
4750 */
danielk197700e13612008-11-17 19:18:54 +00004751 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004752 return SQLITE_ERROR;
4753 }
4754
4755 do{
4756 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004757 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004758 sqlite3_randomness(15, &zBuf[j]);
4759 for(i=0; i<15; i++, j++){
4760 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4761 }
4762 zBuf[j] = 0;
4763 }while( access(zBuf,0)==0 );
4764 return SQLITE_OK;
4765}
4766
drhd2cb50b2009-01-09 21:41:17 +00004767#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004768/*
4769** Routine to transform a unixFile into a proxy-locking unixFile.
4770** Implementation in the proxy-lock division, but used by unixOpen()
4771** if SQLITE_PREFER_PROXY_LOCKING is defined.
4772*/
4773static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004774#endif
drhc66d5b62008-12-03 22:48:32 +00004775
dan08da86a2009-08-21 17:18:03 +00004776/*
4777** Search for an unused file descriptor that was opened on the database
4778** file (not a journal or master-journal file) identified by pathname
4779** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4780** argument to this function.
4781**
4782** Such a file descriptor may exist if a database connection was closed
4783** but the associated file descriptor could not be closed because some
4784** other file descriptor open on the same file is holding a file-lock.
4785** Refer to comments in the unixClose() function and the lengthy comment
4786** describing "Posix Advisory Locking" at the start of this file for
4787** further details. Also, ticket #4018.
4788**
4789** If a suitable file descriptor is found, then it is returned. If no
4790** such file descriptor is located, -1 is returned.
4791*/
dane946c392009-08-22 11:39:46 +00004792static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4793 UnixUnusedFd *pUnused = 0;
4794
4795 /* Do not search for an unused file descriptor on vxworks. Not because
4796 ** vxworks would not benefit from the change (it might, we're not sure),
4797 ** but because no way to test it is currently available. It is better
4798 ** not to risk breaking vxworks support for the sake of such an obscure
4799 ** feature. */
4800#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004801 struct stat sStat; /* Results of stat() call */
4802
4803 /* A stat() call may fail for various reasons. If this happens, it is
4804 ** almost certain that an open() call on the same path will also fail.
4805 ** For this reason, if an error occurs in the stat() call here, it is
4806 ** ignored and -1 is returned. The caller will try to open a new file
4807 ** descriptor on the same path, fail, and return an error to SQLite.
4808 **
4809 ** Even if a subsequent open() call does succeed, the consequences of
4810 ** not searching for a resusable file descriptor are not dire. */
4811 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00004812 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00004813
4814 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00004815 pOpen = openList;
4816 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
4817 || pOpen->fileId.ino!=sStat.st_ino) ){
4818 pOpen = pOpen->pNext;
4819 }
4820 if( pOpen ){
dane946c392009-08-22 11:39:46 +00004821 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00004822 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004823 pUnused = *pp;
4824 if( pUnused ){
4825 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004826 }
4827 }
4828 unixLeaveMutex();
4829 }
dane946c392009-08-22 11:39:46 +00004830#endif /* if !OS_VXWORKS */
4831 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004832}
danielk197717b90b52008-06-06 11:11:25 +00004833
4834/*
danielk1977ad94b582007-08-20 06:44:22 +00004835** Open the file zPath.
4836**
danielk1977b4b47412007-08-17 15:53:36 +00004837** Previously, the SQLite OS layer used three functions in place of this
4838** one:
4839**
4840** sqlite3OsOpenReadWrite();
4841** sqlite3OsOpenReadOnly();
4842** sqlite3OsOpenExclusive();
4843**
4844** These calls correspond to the following combinations of flags:
4845**
4846** ReadWrite() -> (READWRITE | CREATE)
4847** ReadOnly() -> (READONLY)
4848** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4849**
4850** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4851** true, the file was configured to be automatically deleted when the
4852** file handle closed. To achieve the same effect using this new
4853** interface, add the DELETEONCLOSE flag to those specified above for
4854** OpenExclusive().
4855*/
4856static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004857 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4858 const char *zPath, /* Pathname of file to be opened */
4859 sqlite3_file *pFile, /* The file descriptor to be filled in */
4860 int flags, /* Input flags to control the opening */
4861 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004862){
dan08da86a2009-08-21 17:18:03 +00004863 unixFile *p = (unixFile *)pFile;
4864 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004865 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004866 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004867 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004868 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004869 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004870
4871 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4872 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4873 int isCreate = (flags & SQLITE_OPEN_CREATE);
4874 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4875 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004876#if SQLITE_ENABLE_LOCKING_STYLE
4877 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4878#endif
danielk1977b4b47412007-08-17 15:53:36 +00004879
danielk1977fee2d252007-08-18 10:59:19 +00004880 /* If creating a master or main-file journal, this function will open
4881 ** a file-descriptor on the directory too. The first time unixSync()
4882 ** is called the directory file descriptor will be fsync()ed and close()d.
4883 */
4884 int isOpenDirectory = (isCreate &&
4885 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4886 );
4887
danielk197717b90b52008-06-06 11:11:25 +00004888 /* If argument zPath is a NULL pointer, this function is required to open
4889 ** a temporary file. Use this buffer to store the file name in.
4890 */
4891 char zTmpname[MAX_PATHNAME+1];
4892 const char *zName = zPath;
4893
danielk1977fee2d252007-08-18 10:59:19 +00004894 /* Check the following statements are true:
4895 **
4896 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4897 ** (b) if CREATE is set, then READWRITE must also be set, and
4898 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004899 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004900 */
danielk1977b4b47412007-08-17 15:53:36 +00004901 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004902 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004903 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004904 assert(isDelete==0 || isCreate);
4905
drh33f4e022007-09-03 15:19:34 +00004906 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004907 ** deleted. Nor are they ever temporary files. */
4908 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4909 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4910 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004911
danielk1977fee2d252007-08-18 10:59:19 +00004912 /* Assert that the upper layer has set one of the "file-type" flags. */
4913 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4914 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4915 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004916 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004917 );
4918
dan08da86a2009-08-21 17:18:03 +00004919 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004920
dan08da86a2009-08-21 17:18:03 +00004921 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004922 UnixUnusedFd *pUnused;
4923 pUnused = findReusableFd(zName, flags);
4924 if( pUnused ){
4925 fd = pUnused->fd;
4926 }else{
dan6aa657f2009-08-24 18:57:58 +00004927 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004928 if( !pUnused ){
4929 return SQLITE_NOMEM;
4930 }
4931 }
4932 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004933 }else if( !zName ){
4934 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004935 assert(isDelete && !isOpenDirectory);
4936 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4937 if( rc!=SQLITE_OK ){
4938 return rc;
4939 }
4940 zName = zTmpname;
4941 }
4942
dan08da86a2009-08-21 17:18:03 +00004943 /* Determine the value of the flags parameter passed to POSIX function
4944 ** open(). These must be calculated even if open() is not called, as
4945 ** they may be stored as part of the file handle and used by the
4946 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004947 if( isReadonly ) openFlags |= O_RDONLY;
4948 if( isReadWrite ) openFlags |= O_RDWR;
4949 if( isCreate ) openFlags |= O_CREAT;
4950 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4951 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004952
danielk1977b4b47412007-08-17 15:53:36 +00004953 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004954 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4955 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004956 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
4957 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4958 /* Failed to open the file for read/write access. Try read-only. */
4959 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004960 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004961 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004962 openFlags |= O_RDONLY;
4963 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004964 }
4965 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004966 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004967 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004968 }
danielk1977b4b47412007-08-17 15:53:36 +00004969 }
dan08da86a2009-08-21 17:18:03 +00004970 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004971 if( pOutFlags ){
4972 *pOutFlags = flags;
4973 }
4974
dane946c392009-08-22 11:39:46 +00004975 if( p->pUnused ){
4976 p->pUnused->fd = fd;
4977 p->pUnused->flags = flags;
4978 }
4979
danielk1977b4b47412007-08-17 15:53:36 +00004980 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004981#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004982 zPath = zName;
4983#else
danielk197717b90b52008-06-06 11:11:25 +00004984 unlink(zName);
chw97185482008-11-17 08:05:31 +00004985#endif
danielk1977b4b47412007-08-17 15:53:36 +00004986 }
drh41022642008-11-21 00:24:42 +00004987#if SQLITE_ENABLE_LOCKING_STYLE
4988 else{
dan08da86a2009-08-21 17:18:03 +00004989 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004990 }
4991#endif
4992
danielk1977fee2d252007-08-18 10:59:19 +00004993 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004994 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004995 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004996 /* It is safe to close fd at this point, because it is guaranteed not
4997 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004998 ** it would not be safe to close as this would release any locks held
4999 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005000 assert( eType!=SQLITE_OPEN_MAIN_DB );
5001 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00005002 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005003 }
5004 }
danielk1977e339d652008-06-28 11:23:00 +00005005
5006#ifdef FD_CLOEXEC
5007 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
5008#endif
5009
drhda0e7682008-07-30 15:27:54 +00005010 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005011
drh7ed97b92010-01-20 13:07:21 +00005012
5013#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5014 struct statfs fsInfo;
5015 if( fstatfs(fd, &fsInfo) == -1 ){
5016 ((unixFile*)pFile)->lastErrno = errno;
5017 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
5018 close(fd); /* silently leak if fail, in error */
5019 return SQLITE_IOERR_ACCESS;
5020 }
5021 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5022 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5023 }
5024#endif
5025
5026#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005027#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005028 isAutoProxy = 1;
5029#endif
5030 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005031 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5032 int useProxy = 0;
5033
dan08da86a2009-08-21 17:18:03 +00005034 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5035 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005036 if( envforce!=NULL ){
5037 useProxy = atoi(envforce)>0;
5038 }else{
5039 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005040 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005041 /* In theory, the close(fd) call is sub-optimal. If the file opened
5042 ** with fd is a database file, and there are other connections open
5043 ** on that file that are currently holding advisory locks on it,
5044 ** then the call to close() will cancel those locks. In practice,
5045 ** we're assuming that statfs() doesn't fail very often. At least
5046 ** not while other file descriptors opened by the same process on
5047 ** the same file are working. */
5048 p->lastErrno = errno;
5049 if( dirfd>=0 ){
5050 close(dirfd); /* silently leak if fail, in error */
5051 }
aswiftaebf4132008-11-21 00:10:35 +00005052 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00005053 rc = SQLITE_IOERR_ACCESS;
5054 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005055 }
5056 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5057 }
5058 if( useProxy ){
5059 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
5060 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005061 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005062 if( rc!=SQLITE_OK ){
5063 /* Use unixClose to clean up the resources added in fillInUnixFile
5064 ** and clear all the structure's references. Specifically,
5065 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5066 */
5067 unixClose(pFile);
5068 return rc;
5069 }
aswiftaebf4132008-11-21 00:10:35 +00005070 }
dane946c392009-08-22 11:39:46 +00005071 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005072 }
5073 }
5074#endif
5075
dane946c392009-08-22 11:39:46 +00005076 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
5077open_finished:
5078 if( rc!=SQLITE_OK ){
5079 sqlite3_free(p->pUnused);
5080 }
5081 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005082}
5083
dane946c392009-08-22 11:39:46 +00005084
danielk1977b4b47412007-08-17 15:53:36 +00005085/*
danielk1977fee2d252007-08-18 10:59:19 +00005086** Delete the file at zPath. If the dirSync argument is true, fsync()
5087** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005088*/
drh6b9d6dd2008-12-03 19:34:47 +00005089static int unixDelete(
5090 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5091 const char *zPath, /* Name of file to be deleted */
5092 int dirSync /* If true, fsync() directory after deleting file */
5093){
danielk1977fee2d252007-08-18 10:59:19 +00005094 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005095 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005096 SimulateIOError(return SQLITE_IOERR_DELETE);
5097 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00005098#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005099 if( dirSync ){
5100 int fd;
5101 rc = openDirectory(zPath, &fd);
5102 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005103#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005104 if( fsync(fd)==-1 )
5105#else
5106 if( fsync(fd) )
5107#endif
5108 {
danielk1977fee2d252007-08-18 10:59:19 +00005109 rc = SQLITE_IOERR_DIR_FSYNC;
5110 }
aswiftaebf4132008-11-21 00:10:35 +00005111 if( close(fd)&&!rc ){
5112 rc = SQLITE_IOERR_DIR_CLOSE;
5113 }
danielk1977fee2d252007-08-18 10:59:19 +00005114 }
5115 }
danielk1977d138dd82008-10-15 16:02:48 +00005116#endif
danielk1977fee2d252007-08-18 10:59:19 +00005117 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005118}
5119
danielk197790949c22007-08-17 16:50:38 +00005120/*
5121** Test the existance of or access permissions of file zPath. The
5122** test performed depends on the value of flags:
5123**
5124** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5125** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5126** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5127**
5128** Otherwise return 0.
5129*/
danielk1977861f7452008-06-05 11:39:11 +00005130static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005131 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5132 const char *zPath, /* Path of the file to examine */
5133 int flags, /* What do we want to learn about the zPath file? */
5134 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005135){
rse25c0d1a2007-09-20 08:38:14 +00005136 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005137 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005138 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005139 switch( flags ){
5140 case SQLITE_ACCESS_EXISTS:
5141 amode = F_OK;
5142 break;
5143 case SQLITE_ACCESS_READWRITE:
5144 amode = W_OK|R_OK;
5145 break;
drh50d3f902007-08-27 21:10:36 +00005146 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005147 amode = R_OK;
5148 break;
5149
5150 default:
5151 assert(!"Invalid flags argument");
5152 }
danielk1977861f7452008-06-05 11:39:11 +00005153 *pResOut = (access(zPath, amode)==0);
5154 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005155}
5156
danielk1977b4b47412007-08-17 15:53:36 +00005157
5158/*
5159** Turn a relative pathname into a full pathname. The relative path
5160** is stored as a nul-terminated string in the buffer pointed to by
5161** zPath.
5162**
5163** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5164** (in this case, MAX_PATHNAME bytes). The full-path is written to
5165** this buffer before returning.
5166*/
danielk1977adfb9b02007-09-17 07:02:56 +00005167static int unixFullPathname(
5168 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5169 const char *zPath, /* Possibly relative input path */
5170 int nOut, /* Size of output buffer in bytes */
5171 char *zOut /* Output buffer */
5172){
danielk1977843e65f2007-09-01 16:16:15 +00005173
5174 /* It's odd to simulate an io-error here, but really this is just
5175 ** using the io-error infrastructure to test that SQLite handles this
5176 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005177 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005178 */
5179 SimulateIOError( return SQLITE_ERROR );
5180
drh153c62c2007-08-24 03:51:33 +00005181 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005182 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005183
drh3c7f2dc2007-12-06 13:26:20 +00005184 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005185 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005186 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005187 }else{
5188 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00005189 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00005190 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00005191 }
drhea678832008-12-10 19:26:22 +00005192 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005193 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005194 }
5195 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005196}
5197
drh0ccebe72005-06-07 22:22:50 +00005198
drh761df872006-12-21 01:29:22 +00005199#ifndef SQLITE_OMIT_LOAD_EXTENSION
5200/*
5201** Interfaces for opening a shared library, finding entry points
5202** within the shared library, and closing the shared library.
5203*/
5204#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005205static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5206 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005207 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5208}
danielk197795c8a542007-09-01 06:51:27 +00005209
5210/*
5211** SQLite calls this function immediately after a call to unixDlSym() or
5212** unixDlOpen() fails (returns a null pointer). If a more detailed error
5213** message is available, it is written to zBufOut. If no error message
5214** is available, zBufOut is left unmodified and SQLite uses a default
5215** error message.
5216*/
danielk1977397d65f2008-11-19 11:35:39 +00005217static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00005218 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005219 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005220 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005221 zErr = dlerror();
5222 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005223 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005224 }
drh6c7d5c52008-11-21 20:32:33 +00005225 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005226}
drh1875f7a2008-12-08 18:19:17 +00005227static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5228 /*
5229 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5230 ** cast into a pointer to a function. And yet the library dlsym() routine
5231 ** returns a void* which is really a pointer to a function. So how do we
5232 ** use dlsym() with -pedantic-errors?
5233 **
5234 ** Variable x below is defined to be a pointer to a function taking
5235 ** parameters void* and const char* and returning a pointer to a function.
5236 ** We initialize x by assigning it a pointer to the dlsym() function.
5237 ** (That assignment requires a cast.) Then we call the function that
5238 ** x points to.
5239 **
5240 ** This work-around is unlikely to work correctly on any system where
5241 ** you really cannot cast a function pointer into void*. But then, on the
5242 ** other hand, dlsym() will not work on such a system either, so we have
5243 ** not really lost anything.
5244 */
5245 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005246 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005247 x = (void(*(*)(void*,const char*))(void))dlsym;
5248 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005249}
danielk1977397d65f2008-11-19 11:35:39 +00005250static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5251 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005252 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005253}
danielk1977b4b47412007-08-17 15:53:36 +00005254#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5255 #define unixDlOpen 0
5256 #define unixDlError 0
5257 #define unixDlSym 0
5258 #define unixDlClose 0
5259#endif
5260
5261/*
danielk197790949c22007-08-17 16:50:38 +00005262** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005263*/
danielk1977397d65f2008-11-19 11:35:39 +00005264static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5265 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005266 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005267
drhbbd42a62004-05-22 17:41:58 +00005268 /* We have to initialize zBuf to prevent valgrind from reporting
5269 ** errors. The reports issued by valgrind are incorrect - we would
5270 ** prefer that the randomness be increased by making use of the
5271 ** uninitialized space in zBuf - but valgrind errors tend to worry
5272 ** some users. Rather than argue, it seems easier just to initialize
5273 ** the whole array and silence valgrind, even if that means less randomness
5274 ** in the random seed.
5275 **
5276 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005277 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005278 ** tests repeatable.
5279 */
danielk1977b4b47412007-08-17 15:53:36 +00005280 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005281#if !defined(SQLITE_TEST)
5282 {
drh842b8642005-01-21 17:53:17 +00005283 int pid, fd;
5284 fd = open("/dev/urandom", O_RDONLY);
5285 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005286 time_t t;
5287 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005288 memcpy(zBuf, &t, sizeof(t));
5289 pid = getpid();
5290 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005291 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005292 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005293 }else{
drh72cbd072008-10-14 17:58:38 +00005294 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00005295 close(fd);
5296 }
drhbbd42a62004-05-22 17:41:58 +00005297 }
5298#endif
drh72cbd072008-10-14 17:58:38 +00005299 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005300}
5301
danielk1977b4b47412007-08-17 15:53:36 +00005302
drhbbd42a62004-05-22 17:41:58 +00005303/*
5304** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005305** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005306** The return value is the number of microseconds of sleep actually
5307** requested from the underlying operating system, a number which
5308** might be greater than or equal to the argument, but not less
5309** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005310*/
danielk1977397d65f2008-11-19 11:35:39 +00005311static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005312#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005313 struct timespec sp;
5314
5315 sp.tv_sec = microseconds / 1000000;
5316 sp.tv_nsec = (microseconds % 1000000) * 1000;
5317 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005318 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005319 return microseconds;
5320#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005321 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005322 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005323 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005324#else
danielk1977b4b47412007-08-17 15:53:36 +00005325 int seconds = (microseconds+999999)/1000000;
5326 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005327 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005328 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005329#endif
drh88f474a2006-01-02 20:00:12 +00005330}
5331
5332/*
drh6b9d6dd2008-12-03 19:34:47 +00005333** The following variable, if set to a non-zero value, is interpreted as
5334** the number of seconds since 1970 and is used to set the result of
5335** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005336*/
5337#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005338int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005339#endif
5340
5341/*
drhb7e8ea22010-05-03 14:32:30 +00005342** Find the current time (in Universal Coordinated Time). Write into *piNow
5343** the current time and date as a Julian Day number times 86_400_000. In
5344** other words, write into *piNow the number of milliseconds since the Julian
5345** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5346** proleptic Gregorian calendar.
5347**
5348** On success, return 0. Return 1 if the time and date cannot be found.
5349*/
5350static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5351 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5352#if defined(NO_GETTOD)
5353 time_t t;
5354 time(&t);
5355 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
5356#elif OS_VXWORKS
5357 struct timespec sNow;
5358 clock_gettime(CLOCK_REALTIME, &sNow);
5359 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5360#else
5361 struct timeval sNow;
5362 gettimeofday(&sNow, 0);
5363 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5364#endif
5365
5366#ifdef SQLITE_TEST
5367 if( sqlite3_current_time ){
5368 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5369 }
5370#endif
5371 UNUSED_PARAMETER(NotUsed);
5372 return 0;
5373}
5374
5375/*
drhbbd42a62004-05-22 17:41:58 +00005376** Find the current time (in Universal Coordinated Time). Write the
5377** current time and date as a Julian Day number into *prNow and
5378** return 0. Return 1 if the time and date cannot be found.
5379*/
danielk1977397d65f2008-11-19 11:35:39 +00005380static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005381 sqlite3_int64 i;
5382 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005383 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005384 return 0;
5385}
danielk1977b4b47412007-08-17 15:53:36 +00005386
drh6b9d6dd2008-12-03 19:34:47 +00005387/*
5388** We added the xGetLastError() method with the intention of providing
5389** better low-level error messages when operating-system problems come up
5390** during SQLite operation. But so far, none of that has been implemented
5391** in the core. So this routine is never called. For now, it is merely
5392** a place-holder.
5393*/
danielk1977397d65f2008-11-19 11:35:39 +00005394static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5395 UNUSED_PARAMETER(NotUsed);
5396 UNUSED_PARAMETER(NotUsed2);
5397 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005398 return 0;
5399}
5400
drhf2424c52010-04-26 00:04:55 +00005401
5402/*
drh734c9862008-11-28 15:37:20 +00005403************************ End of sqlite3_vfs methods ***************************
5404******************************************************************************/
5405
drh715ff302008-12-03 22:32:44 +00005406/******************************************************************************
5407************************** Begin Proxy Locking ********************************
5408**
5409** Proxy locking is a "uber-locking-method" in this sense: It uses the
5410** other locking methods on secondary lock files. Proxy locking is a
5411** meta-layer over top of the primitive locking implemented above. For
5412** this reason, the division that implements of proxy locking is deferred
5413** until late in the file (here) after all of the other I/O methods have
5414** been defined - so that the primitive locking methods are available
5415** as services to help with the implementation of proxy locking.
5416**
5417****
5418**
5419** The default locking schemes in SQLite use byte-range locks on the
5420** database file to coordinate safe, concurrent access by multiple readers
5421** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5422** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5423** as POSIX read & write locks over fixed set of locations (via fsctl),
5424** on AFP and SMB only exclusive byte-range locks are available via fsctl
5425** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5426** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5427** address in the shared range is taken for a SHARED lock, the entire
5428** shared range is taken for an EXCLUSIVE lock):
5429**
5430** PENDING_BYTE 0x40000000
5431** RESERVED_BYTE 0x40000001
5432** SHARED_RANGE 0x40000002 -> 0x40000200
5433**
5434** This works well on the local file system, but shows a nearly 100x
5435** slowdown in read performance on AFP because the AFP client disables
5436** the read cache when byte-range locks are present. Enabling the read
5437** cache exposes a cache coherency problem that is present on all OS X
5438** supported network file systems. NFS and AFP both observe the
5439** close-to-open semantics for ensuring cache coherency
5440** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5441** address the requirements for concurrent database access by multiple
5442** readers and writers
5443** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5444**
5445** To address the performance and cache coherency issues, proxy file locking
5446** changes the way database access is controlled by limiting access to a
5447** single host at a time and moving file locks off of the database file
5448** and onto a proxy file on the local file system.
5449**
5450**
5451** Using proxy locks
5452** -----------------
5453**
5454** C APIs
5455**
5456** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5457** <proxy_path> | ":auto:");
5458** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5459**
5460**
5461** SQL pragmas
5462**
5463** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5464** PRAGMA [database.]lock_proxy_file
5465**
5466** Specifying ":auto:" means that if there is a conch file with a matching
5467** host ID in it, the proxy path in the conch file will be used, otherwise
5468** a proxy path based on the user's temp dir
5469** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5470** actual proxy file name is generated from the name and path of the
5471** database file. For example:
5472**
5473** For database path "/Users/me/foo.db"
5474** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5475**
5476** Once a lock proxy is configured for a database connection, it can not
5477** be removed, however it may be switched to a different proxy path via
5478** the above APIs (assuming the conch file is not being held by another
5479** connection or process).
5480**
5481**
5482** How proxy locking works
5483** -----------------------
5484**
5485** Proxy file locking relies primarily on two new supporting files:
5486**
5487** * conch file to limit access to the database file to a single host
5488** at a time
5489**
5490** * proxy file to act as a proxy for the advisory locks normally
5491** taken on the database
5492**
5493** The conch file - to use a proxy file, sqlite must first "hold the conch"
5494** by taking an sqlite-style shared lock on the conch file, reading the
5495** contents and comparing the host's unique host ID (see below) and lock
5496** proxy path against the values stored in the conch. The conch file is
5497** stored in the same directory as the database file and the file name
5498** is patterned after the database file name as ".<databasename>-conch".
5499** If the conch file does not exist, or it's contents do not match the
5500** host ID and/or proxy path, then the lock is escalated to an exclusive
5501** lock and the conch file contents is updated with the host ID and proxy
5502** path and the lock is downgraded to a shared lock again. If the conch
5503** is held by another process (with a shared lock), the exclusive lock
5504** will fail and SQLITE_BUSY is returned.
5505**
5506** The proxy file - a single-byte file used for all advisory file locks
5507** normally taken on the database file. This allows for safe sharing
5508** of the database file for multiple readers and writers on the same
5509** host (the conch ensures that they all use the same local lock file).
5510**
drh715ff302008-12-03 22:32:44 +00005511** Requesting the lock proxy does not immediately take the conch, it is
5512** only taken when the first request to lock database file is made.
5513** This matches the semantics of the traditional locking behavior, where
5514** opening a connection to a database file does not take a lock on it.
5515** The shared lock and an open file descriptor are maintained until
5516** the connection to the database is closed.
5517**
5518** The proxy file and the lock file are never deleted so they only need
5519** to be created the first time they are used.
5520**
5521** Configuration options
5522** ---------------------
5523**
5524** SQLITE_PREFER_PROXY_LOCKING
5525**
5526** Database files accessed on non-local file systems are
5527** automatically configured for proxy locking, lock files are
5528** named automatically using the same logic as
5529** PRAGMA lock_proxy_file=":auto:"
5530**
5531** SQLITE_PROXY_DEBUG
5532**
5533** Enables the logging of error messages during host id file
5534** retrieval and creation
5535**
drh715ff302008-12-03 22:32:44 +00005536** LOCKPROXYDIR
5537**
5538** Overrides the default directory used for lock proxy files that
5539** are named automatically via the ":auto:" setting
5540**
5541** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5542**
5543** Permissions to use when creating a directory for storing the
5544** lock proxy files, only used when LOCKPROXYDIR is not set.
5545**
5546**
5547** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5548** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5549** force proxy locking to be used for every database file opened, and 0
5550** will force automatic proxy locking to be disabled for all database
5551** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5552** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5553*/
5554
5555/*
5556** Proxy locking is only available on MacOSX
5557*/
drhd2cb50b2009-01-09 21:41:17 +00005558#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005559
drh715ff302008-12-03 22:32:44 +00005560/*
5561** The proxyLockingContext has the path and file structures for the remote
5562** and local proxy files in it
5563*/
5564typedef struct proxyLockingContext proxyLockingContext;
5565struct proxyLockingContext {
5566 unixFile *conchFile; /* Open conch file */
5567 char *conchFilePath; /* Name of the conch file */
5568 unixFile *lockProxy; /* Open proxy lock file */
5569 char *lockProxyPath; /* Name of the proxy lock file */
5570 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005571 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005572 void *oldLockingContext; /* Original lockingcontext to restore on close */
5573 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5574};
5575
drh7ed97b92010-01-20 13:07:21 +00005576/*
5577** The proxy lock file path for the database at dbPath is written into lPath,
5578** which must point to valid, writable memory large enough for a maxLen length
5579** file path.
drh715ff302008-12-03 22:32:44 +00005580*/
drh715ff302008-12-03 22:32:44 +00005581static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5582 int len;
5583 int dbLen;
5584 int i;
5585
5586#ifdef LOCKPROXYDIR
5587 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5588#else
5589# ifdef _CS_DARWIN_USER_TEMP_DIR
5590 {
drh7ed97b92010-01-20 13:07:21 +00005591 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
5592 OSTRACE4("GETLOCKPATH failed %s errno=%d pid=%d\n",
5593 lPath, errno, getpid());
5594 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005595 }
drh7ed97b92010-01-20 13:07:21 +00005596 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005597 }
5598# else
5599 len = strlcpy(lPath, "/tmp/", maxLen);
5600# endif
5601#endif
5602
5603 if( lPath[len-1]!='/' ){
5604 len = strlcat(lPath, "/", maxLen);
5605 }
5606
5607 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005608 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00005609 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
5610 char c = dbPath[i];
5611 lPath[i+len] = (c=='/')?'_':c;
5612 }
5613 lPath[i+len]='\0';
5614 strlcat(lPath, ":auto:", maxLen);
drh7ed97b92010-01-20 13:07:21 +00005615 OSTRACE3("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid());
drh715ff302008-12-03 22:32:44 +00005616 return SQLITE_OK;
5617}
5618
drh7ed97b92010-01-20 13:07:21 +00005619/*
5620 ** Creates the lock file and any missing directories in lockPath
5621 */
5622static int proxyCreateLockPath(const char *lockPath){
5623 int i, len;
5624 char buf[MAXPATHLEN];
5625 int start = 0;
5626
5627 assert(lockPath!=NULL);
5628 /* try to create all the intermediate directories */
5629 len = (int)strlen(lockPath);
5630 buf[0] = lockPath[0];
5631 for( i=1; i<len; i++ ){
5632 if( lockPath[i] == '/' && (i - start > 0) ){
5633 /* only mkdir if leaf dir != "." or "/" or ".." */
5634 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5635 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5636 buf[i]='\0';
5637 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5638 int err=errno;
5639 if( err!=EEXIST ) {
5640 OSTRACE5("CREATELOCKPATH FAILED creating %s, "
5641 "'%s' proxy lock path=%s pid=%d\n",
5642 buf, strerror(err), lockPath, getpid());
5643 return err;
5644 }
5645 }
5646 }
5647 start=i+1;
5648 }
5649 buf[i] = lockPath[i];
5650 }
5651 OSTRACE3("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid());
5652 return 0;
5653}
5654
drh715ff302008-12-03 22:32:44 +00005655/*
5656** Create a new VFS file descriptor (stored in memory obtained from
5657** sqlite3_malloc) and open the file named "path" in the file descriptor.
5658**
5659** The caller is responsible not only for closing the file descriptor
5660** but also for freeing the memory associated with the file descriptor.
5661*/
drh7ed97b92010-01-20 13:07:21 +00005662static int proxyCreateUnixFile(
5663 const char *path, /* path for the new unixFile */
5664 unixFile **ppFile, /* unixFile created and returned by ref */
5665 int islockfile /* if non zero missing dirs will be created */
5666) {
5667 int fd = -1;
5668 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005669 unixFile *pNew;
5670 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005671 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005672 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005673 int terrno = 0;
5674 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005675
drh7ed97b92010-01-20 13:07:21 +00005676 /* 1. first try to open/create the file
5677 ** 2. if that fails, and this is a lock file (not-conch), try creating
5678 ** the parent directories and then try again.
5679 ** 3. if that fails, try to open the file read-only
5680 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5681 */
5682 pUnused = findReusableFd(path, openFlags);
5683 if( pUnused ){
5684 fd = pUnused->fd;
5685 }else{
5686 pUnused = sqlite3_malloc(sizeof(*pUnused));
5687 if( !pUnused ){
5688 return SQLITE_NOMEM;
5689 }
5690 }
5691 if( fd<0 ){
5692 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5693 terrno = errno;
5694 if( fd<0 && errno==ENOENT && islockfile ){
5695 if( proxyCreateLockPath(path) == SQLITE_OK ){
5696 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5697 }
5698 }
5699 }
5700 if( fd<0 ){
5701 openFlags = O_RDONLY;
5702 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5703 terrno = errno;
5704 }
5705 if( fd<0 ){
5706 if( islockfile ){
5707 return SQLITE_BUSY;
5708 }
5709 switch (terrno) {
5710 case EACCES:
5711 return SQLITE_PERM;
5712 case EIO:
5713 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5714 default:
drh9978c972010-02-23 17:36:32 +00005715 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005716 }
5717 }
5718
5719 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5720 if( pNew==NULL ){
5721 rc = SQLITE_NOMEM;
5722 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005723 }
5724 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005725 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005726 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005727 pUnused->fd = fd;
5728 pUnused->flags = openFlags;
5729 pNew->pUnused = pUnused;
5730
5731 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5732 if( rc==SQLITE_OK ){
5733 *ppFile = pNew;
5734 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005735 }
drh7ed97b92010-01-20 13:07:21 +00005736end_create_proxy:
5737 close(fd); /* silently leak fd if error, we're already in error */
5738 sqlite3_free(pNew);
5739 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005740 return rc;
5741}
5742
drh7ed97b92010-01-20 13:07:21 +00005743#ifdef SQLITE_TEST
5744/* simulate multiple hosts by creating unique hostid file paths */
5745int sqlite3_hostid_num = 0;
5746#endif
5747
5748#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5749
5750/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5751** bytes of writable memory.
5752*/
5753static int proxyGetHostID(unsigned char *pHostID, int *pError){
5754 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5755
5756 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5757 memset(pHostID, 0, PROXY_HOSTIDLEN);
5758 if( gethostuuid(pHostID, &timeout) ){
5759 int err = errno;
5760 if( pError ){
5761 *pError = err;
5762 }
5763 return SQLITE_IOERR;
5764 }
5765#ifdef SQLITE_TEST
5766 /* simulate multiple hosts by creating unique hostid file paths */
5767 if( sqlite3_hostid_num != 0){
5768 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5769 }
5770#endif
5771
5772 return SQLITE_OK;
5773}
5774
5775/* The conch file contains the header, host id and lock file path
5776 */
5777#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5778#define PROXY_HEADERLEN 1 /* conch file header length */
5779#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5780#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5781
5782/*
5783** Takes an open conch file, copies the contents to a new path and then moves
5784** it back. The newly created file's file descriptor is assigned to the
5785** conch file structure and finally the original conch file descriptor is
5786** closed. Returns zero if successful.
5787*/
5788static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5789 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5790 unixFile *conchFile = pCtx->conchFile;
5791 char tPath[MAXPATHLEN];
5792 char buf[PROXY_MAXCONCHLEN];
5793 char *cPath = pCtx->conchFilePath;
5794 size_t readLen = 0;
5795 size_t pathLen = 0;
5796 char errmsg[64] = "";
5797 int fd = -1;
5798 int rc = -1;
5799
5800 /* create a new path by replace the trailing '-conch' with '-break' */
5801 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5802 if( pathLen>MAXPATHLEN || pathLen<6 ||
5803 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5804 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5805 goto end_breaklock;
5806 }
5807 /* read the conch content */
5808 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5809 if( readLen<PROXY_PATHINDEX ){
5810 sprintf(errmsg, "read error (len %d)", (int)readLen);
5811 goto end_breaklock;
5812 }
5813 /* write it out to the temporary break file */
5814 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5815 if( fd<0 ){
5816 sprintf(errmsg, "create failed (%d)", errno);
5817 goto end_breaklock;
5818 }
5819 if( pwrite(fd, buf, readLen, 0) != readLen ){
5820 sprintf(errmsg, "write failed (%d)", errno);
5821 goto end_breaklock;
5822 }
5823 if( rename(tPath, cPath) ){
5824 sprintf(errmsg, "rename failed (%d)", errno);
5825 goto end_breaklock;
5826 }
5827 rc = 0;
5828 fprintf(stderr, "broke stale lock on %s\n", cPath);
5829 close(conchFile->h);
5830 conchFile->h = fd;
5831 conchFile->openFlags = O_RDWR | O_CREAT;
5832
5833end_breaklock:
5834 if( rc ){
5835 if( fd>=0 ){
5836 unlink(tPath);
5837 close(fd);
5838 }
5839 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5840 }
5841 return rc;
5842}
5843
5844/* Take the requested lock on the conch file and break a stale lock if the
5845** host id matches.
5846*/
5847static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5848 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5849 unixFile *conchFile = pCtx->conchFile;
5850 int rc = SQLITE_OK;
5851 int nTries = 0;
5852 struct timespec conchModTime;
5853
5854 do {
5855 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5856 nTries ++;
5857 if( rc==SQLITE_BUSY ){
5858 /* If the lock failed (busy):
5859 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5860 * 2nd try: fail if the mod time changed or host id is different, wait
5861 * 10 sec and try again
5862 * 3rd try: break the lock unless the mod time has changed.
5863 */
5864 struct stat buf;
5865 if( fstat(conchFile->h, &buf) ){
5866 pFile->lastErrno = errno;
5867 return SQLITE_IOERR_LOCK;
5868 }
5869
5870 if( nTries==1 ){
5871 conchModTime = buf.st_mtimespec;
5872 usleep(500000); /* wait 0.5 sec and try the lock again*/
5873 continue;
5874 }
5875
5876 assert( nTries>1 );
5877 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5878 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5879 return SQLITE_BUSY;
5880 }
5881
5882 if( nTries==2 ){
5883 char tBuf[PROXY_MAXCONCHLEN];
5884 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5885 if( len<0 ){
5886 pFile->lastErrno = errno;
5887 return SQLITE_IOERR_LOCK;
5888 }
5889 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5890 /* don't break the lock if the host id doesn't match */
5891 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5892 return SQLITE_BUSY;
5893 }
5894 }else{
5895 /* don't break the lock on short read or a version mismatch */
5896 return SQLITE_BUSY;
5897 }
5898 usleep(10000000); /* wait 10 sec and try the lock again */
5899 continue;
5900 }
5901
5902 assert( nTries==3 );
5903 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5904 rc = SQLITE_OK;
5905 if( lockType==EXCLUSIVE_LOCK ){
5906 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5907 }
5908 if( !rc ){
5909 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5910 }
5911 }
5912 }
5913 } while( rc==SQLITE_BUSY && nTries<3 );
5914
5915 return rc;
5916}
5917
5918/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005919** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5920** lockPath means that the lockPath in the conch file will be used if the
5921** host IDs match, or a new lock path will be generated automatically
5922** and written to the conch file.
5923*/
5924static int proxyTakeConch(unixFile *pFile){
5925 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5926
drh7ed97b92010-01-20 13:07:21 +00005927 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005928 return SQLITE_OK;
5929 }else{
5930 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005931 uuid_t myHostID;
5932 int pError = 0;
5933 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005934 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005935 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005936 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005937 int createConch = 0;
5938 int hostIdMatch = 0;
5939 int readLen = 0;
5940 int tryOldLockPath = 0;
5941 int forceNewLockPath = 0;
5942
drh715ff302008-12-03 22:32:44 +00005943 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5944 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
5945
drh7ed97b92010-01-20 13:07:21 +00005946 rc = proxyGetHostID(myHostID, &pError);
5947 if( (rc&0xff)==SQLITE_IOERR ){
5948 pFile->lastErrno = pError;
5949 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005950 }
drh7ed97b92010-01-20 13:07:21 +00005951 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005952 if( rc!=SQLITE_OK ){
5953 goto end_takeconch;
5954 }
drh7ed97b92010-01-20 13:07:21 +00005955 /* read the existing conch file */
5956 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5957 if( readLen<0 ){
5958 /* I/O error: lastErrno set by seekAndRead */
5959 pFile->lastErrno = conchFile->lastErrno;
5960 rc = SQLITE_IOERR_READ;
5961 goto end_takeconch;
5962 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5963 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5964 /* a short read or version format mismatch means we need to create a new
5965 ** conch file.
5966 */
5967 createConch = 1;
5968 }
5969 /* if the host id matches and the lock path already exists in the conch
5970 ** we'll try to use the path there, if we can't open that path, we'll
5971 ** retry with a new auto-generated path
5972 */
5973 do { /* in case we need to try again for an :auto: named lock file */
5974
5975 if( !createConch && !forceNewLockPath ){
5976 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5977 PROXY_HOSTIDLEN);
5978 /* if the conch has data compare the contents */
5979 if( !pCtx->lockProxyPath ){
5980 /* for auto-named local lock file, just check the host ID and we'll
5981 ** use the local lock file path that's already in there
5982 */
5983 if( hostIdMatch ){
5984 size_t pathLen = (readLen - PROXY_PATHINDEX);
5985
5986 if( pathLen>=MAXPATHLEN ){
5987 pathLen=MAXPATHLEN-1;
5988 }
5989 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5990 lockPath[pathLen] = 0;
5991 tempLockPath = lockPath;
5992 tryOldLockPath = 1;
5993 /* create a copy of the lock path if the conch is taken */
5994 goto end_takeconch;
5995 }
5996 }else if( hostIdMatch
5997 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5998 readLen-PROXY_PATHINDEX)
5999 ){
6000 /* conch host and lock path match */
6001 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006002 }
drh7ed97b92010-01-20 13:07:21 +00006003 }
6004
6005 /* if the conch isn't writable and doesn't match, we can't take it */
6006 if( (conchFile->openFlags&O_RDWR) == 0 ){
6007 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006008 goto end_takeconch;
6009 }
drh7ed97b92010-01-20 13:07:21 +00006010
6011 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006012 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006013 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6014 tempLockPath = lockPath;
6015 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006016 }
drh7ed97b92010-01-20 13:07:21 +00006017
6018 /* update conch with host and path (this will fail if other process
6019 ** has a shared lock already), if the host id matches, use the big
6020 ** stick.
drh715ff302008-12-03 22:32:44 +00006021 */
drh7ed97b92010-01-20 13:07:21 +00006022 futimes(conchFile->h, NULL);
6023 if( hostIdMatch && !createConch ){
6024 if( conchFile->pLock && conchFile->pLock->cnt>1 ){
6025 /* We are trying for an exclusive lock but another thread in this
6026 ** same process is still holding a shared lock. */
6027 rc = SQLITE_BUSY;
6028 } else {
6029 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006030 }
drh715ff302008-12-03 22:32:44 +00006031 }else{
drh7ed97b92010-01-20 13:07:21 +00006032 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006033 }
drh7ed97b92010-01-20 13:07:21 +00006034 if( rc==SQLITE_OK ){
6035 char writeBuffer[PROXY_MAXCONCHLEN];
6036 int writeSize = 0;
6037
6038 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6039 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6040 if( pCtx->lockProxyPath!=NULL ){
6041 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6042 }else{
6043 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6044 }
6045 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
6046 ftruncate(conchFile->h, writeSize);
6047 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6048 fsync(conchFile->h);
6049 /* If we created a new conch file (not just updated the contents of a
6050 ** valid conch file), try to match the permissions of the database
6051 */
6052 if( rc==SQLITE_OK && createConch ){
6053 struct stat buf;
6054 int err = fstat(pFile->h, &buf);
6055 if( err==0 ){
6056 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6057 S_IROTH|S_IWOTH);
6058 /* try to match the database file R/W permissions, ignore failure */
6059#ifndef SQLITE_PROXY_DEBUG
6060 fchmod(conchFile->h, cmode);
6061#else
6062 if( fchmod(conchFile->h, cmode)!=0 ){
6063 int code = errno;
6064 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6065 cmode, code, strerror(code));
6066 } else {
6067 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6068 }
6069 }else{
6070 int code = errno;
6071 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6072 err, code, strerror(code));
6073#endif
6074 }
drh715ff302008-12-03 22:32:44 +00006075 }
6076 }
drh7ed97b92010-01-20 13:07:21 +00006077 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6078
6079 end_takeconch:
6080 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
6081 if( rc==SQLITE_OK && pFile->openFlags ){
6082 if( pFile->h>=0 ){
6083#ifdef STRICT_CLOSE_ERROR
6084 if( close(pFile->h) ){
6085 pFile->lastErrno = errno;
6086 return SQLITE_IOERR_CLOSE;
6087 }
6088#else
6089 close(pFile->h); /* silently leak fd if fail */
6090#endif
6091 }
6092 pFile->h = -1;
6093 int fd = open(pCtx->dbPath, pFile->openFlags,
6094 SQLITE_DEFAULT_FILE_PERMISSIONS);
6095 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
6096 if( fd>=0 ){
6097 pFile->h = fd;
6098 }else{
drh9978c972010-02-23 17:36:32 +00006099 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006100 during locking */
6101 }
6102 }
6103 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6104 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6105 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6106 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6107 /* we couldn't create the proxy lock file with the old lock file path
6108 ** so try again via auto-naming
6109 */
6110 forceNewLockPath = 1;
6111 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006112 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006113 }
6114 }
6115 if( rc==SQLITE_OK ){
6116 /* Need to make a copy of path if we extracted the value
6117 ** from the conch file or the path was allocated on the stack
6118 */
6119 if( tempLockPath ){
6120 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6121 if( !pCtx->lockProxyPath ){
6122 rc = SQLITE_NOMEM;
6123 }
6124 }
6125 }
6126 if( rc==SQLITE_OK ){
6127 pCtx->conchHeld = 1;
6128
6129 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6130 afpLockingContext *afpCtx;
6131 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6132 afpCtx->dbPath = pCtx->lockProxyPath;
6133 }
6134 } else {
6135 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6136 }
6137 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
6138 return rc;
6139 } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006140 }
6141}
6142
6143/*
6144** If pFile holds a lock on a conch file, then release that lock.
6145*/
6146static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006147 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006148 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6149 unixFile *conchFile; /* Name of the conch file */
6150
6151 pCtx = (proxyLockingContext *)pFile->lockingContext;
6152 conchFile = pCtx->conchFile;
6153 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
6154 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6155 getpid());
drh7ed97b92010-01-20 13:07:21 +00006156 if( pCtx->conchHeld>0 ){
6157 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6158 }
drh715ff302008-12-03 22:32:44 +00006159 pCtx->conchHeld = 0;
drh715ff302008-12-03 22:32:44 +00006160 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
6161 (rc==SQLITE_OK ? "ok" : "failed"));
6162 return rc;
6163}
6164
6165/*
6166** Given the name of a database file, compute the name of its conch file.
6167** Store the conch filename in memory obtained from sqlite3_malloc().
6168** Make *pConchPath point to the new name. Return SQLITE_OK on success
6169** or SQLITE_NOMEM if unable to obtain memory.
6170**
6171** The caller is responsible for ensuring that the allocated memory
6172** space is eventually freed.
6173**
6174** *pConchPath is set to NULL if a memory allocation error occurs.
6175*/
6176static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6177 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006178 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006179 char *conchPath; /* buffer in which to construct conch name */
6180
6181 /* Allocate space for the conch filename and initialize the name to
6182 ** the name of the original database file. */
6183 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6184 if( conchPath==0 ){
6185 return SQLITE_NOMEM;
6186 }
6187 memcpy(conchPath, dbPath, len+1);
6188
6189 /* now insert a "." before the last / character */
6190 for( i=(len-1); i>=0; i-- ){
6191 if( conchPath[i]=='/' ){
6192 i++;
6193 break;
6194 }
6195 }
6196 conchPath[i]='.';
6197 while ( i<len ){
6198 conchPath[i+1]=dbPath[i];
6199 i++;
6200 }
6201
6202 /* append the "-conch" suffix to the file */
6203 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006204 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006205
6206 return SQLITE_OK;
6207}
6208
6209
6210/* Takes a fully configured proxy locking-style unix file and switches
6211** the local lock file path
6212*/
6213static int switchLockProxyPath(unixFile *pFile, const char *path) {
6214 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6215 char *oldPath = pCtx->lockProxyPath;
6216 int rc = SQLITE_OK;
6217
6218 if( pFile->locktype!=NO_LOCK ){
6219 return SQLITE_BUSY;
6220 }
6221
6222 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6223 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6224 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6225 return SQLITE_OK;
6226 }else{
6227 unixFile *lockProxy = pCtx->lockProxy;
6228 pCtx->lockProxy=NULL;
6229 pCtx->conchHeld = 0;
6230 if( lockProxy!=NULL ){
6231 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6232 if( rc ) return rc;
6233 sqlite3_free(lockProxy);
6234 }
6235 sqlite3_free(oldPath);
6236 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6237 }
6238
6239 return rc;
6240}
6241
6242/*
6243** pFile is a file that has been opened by a prior xOpen call. dbPath
6244** is a string buffer at least MAXPATHLEN+1 characters in size.
6245**
6246** This routine find the filename associated with pFile and writes it
6247** int dbPath.
6248*/
6249static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006250#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006251 if( pFile->pMethod == &afpIoMethods ){
6252 /* afp style keeps a reference to the db path in the filePath field
6253 ** of the struct */
drhea678832008-12-10 19:26:22 +00006254 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006255 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6256 } else
drh715ff302008-12-03 22:32:44 +00006257#endif
6258 if( pFile->pMethod == &dotlockIoMethods ){
6259 /* dot lock style uses the locking context to store the dot lock
6260 ** file path */
6261 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6262 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6263 }else{
6264 /* all other styles use the locking context to store the db file path */
6265 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006266 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006267 }
6268 return SQLITE_OK;
6269}
6270
6271/*
6272** Takes an already filled in unix file and alters it so all file locking
6273** will be performed on the local proxy lock file. The following fields
6274** are preserved in the locking context so that they can be restored and
6275** the unix structure properly cleaned up at close time:
6276** ->lockingContext
6277** ->pMethod
6278*/
6279static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6280 proxyLockingContext *pCtx;
6281 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6282 char *lockPath=NULL;
6283 int rc = SQLITE_OK;
6284
6285 if( pFile->locktype!=NO_LOCK ){
6286 return SQLITE_BUSY;
6287 }
6288 proxyGetDbPathForUnixFile(pFile, dbPath);
6289 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6290 lockPath=NULL;
6291 }else{
6292 lockPath=(char *)path;
6293 }
6294
6295 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6296 (lockPath ? lockPath : ":auto:"), getpid());
6297
6298 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6299 if( pCtx==0 ){
6300 return SQLITE_NOMEM;
6301 }
6302 memset(pCtx, 0, sizeof(*pCtx));
6303
6304 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6305 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006306 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6307 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6308 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6309 ** (c) the file system is read-only, then enable no-locking access.
6310 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6311 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6312 */
6313 struct statfs fsInfo;
6314 struct stat conchInfo;
6315 int goLockless = 0;
6316
6317 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6318 int err = errno;
6319 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6320 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6321 }
6322 }
6323 if( goLockless ){
6324 pCtx->conchHeld = -1; /* read only FS/ lockless */
6325 rc = SQLITE_OK;
6326 }
6327 }
drh715ff302008-12-03 22:32:44 +00006328 }
6329 if( rc==SQLITE_OK && lockPath ){
6330 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6331 }
6332
6333 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006334 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6335 if( pCtx->dbPath==NULL ){
6336 rc = SQLITE_NOMEM;
6337 }
6338 }
6339 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006340 /* all memory is allocated, proxys are created and assigned,
6341 ** switch the locking context and pMethod then return.
6342 */
drh715ff302008-12-03 22:32:44 +00006343 pCtx->oldLockingContext = pFile->lockingContext;
6344 pFile->lockingContext = pCtx;
6345 pCtx->pOldMethod = pFile->pMethod;
6346 pFile->pMethod = &proxyIoMethods;
6347 }else{
6348 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006349 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006350 sqlite3_free(pCtx->conchFile);
6351 }
drh7ed97b92010-01-20 13:07:21 +00006352 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006353 sqlite3_free(pCtx->conchFilePath);
6354 sqlite3_free(pCtx);
6355 }
6356 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
6357 (rc==SQLITE_OK ? "ok" : "failed"));
6358 return rc;
6359}
6360
6361
6362/*
6363** This routine handles sqlite3_file_control() calls that are specific
6364** to proxy locking.
6365*/
6366static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6367 switch( op ){
6368 case SQLITE_GET_LOCKPROXYFILE: {
6369 unixFile *pFile = (unixFile*)id;
6370 if( pFile->pMethod == &proxyIoMethods ){
6371 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6372 proxyTakeConch(pFile);
6373 if( pCtx->lockProxyPath ){
6374 *(const char **)pArg = pCtx->lockProxyPath;
6375 }else{
6376 *(const char **)pArg = ":auto: (not held)";
6377 }
6378 } else {
6379 *(const char **)pArg = NULL;
6380 }
6381 return SQLITE_OK;
6382 }
6383 case SQLITE_SET_LOCKPROXYFILE: {
6384 unixFile *pFile = (unixFile*)id;
6385 int rc = SQLITE_OK;
6386 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6387 if( pArg==NULL || (const char *)pArg==0 ){
6388 if( isProxyStyle ){
6389 /* turn off proxy locking - not supported */
6390 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6391 }else{
6392 /* turn off proxy locking - already off - NOOP */
6393 rc = SQLITE_OK;
6394 }
6395 }else{
6396 const char *proxyPath = (const char *)pArg;
6397 if( isProxyStyle ){
6398 proxyLockingContext *pCtx =
6399 (proxyLockingContext*)pFile->lockingContext;
6400 if( !strcmp(pArg, ":auto:")
6401 || (pCtx->lockProxyPath &&
6402 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6403 ){
6404 rc = SQLITE_OK;
6405 }else{
6406 rc = switchLockProxyPath(pFile, proxyPath);
6407 }
6408 }else{
6409 /* turn on proxy file locking */
6410 rc = proxyTransformUnixFile(pFile, proxyPath);
6411 }
6412 }
6413 return rc;
6414 }
6415 default: {
6416 assert( 0 ); /* The call assures that only valid opcodes are sent */
6417 }
6418 }
6419 /*NOTREACHED*/
6420 return SQLITE_ERROR;
6421}
6422
6423/*
6424** Within this division (the proxying locking implementation) the procedures
6425** above this point are all utilities. The lock-related methods of the
6426** proxy-locking sqlite3_io_method object follow.
6427*/
6428
6429
6430/*
6431** This routine checks if there is a RESERVED lock held on the specified
6432** file by this or any other process. If such a lock is held, set *pResOut
6433** to a non-zero value otherwise *pResOut is set to zero. The return value
6434** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6435*/
6436static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6437 unixFile *pFile = (unixFile*)id;
6438 int rc = proxyTakeConch(pFile);
6439 if( rc==SQLITE_OK ){
6440 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006441 if( pCtx->conchHeld>0 ){
6442 unixFile *proxy = pCtx->lockProxy;
6443 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6444 }else{ /* conchHeld < 0 is lockless */
6445 pResOut=0;
6446 }
drh715ff302008-12-03 22:32:44 +00006447 }
6448 return rc;
6449}
6450
6451/*
6452** Lock the file with the lock specified by parameter locktype - one
6453** of the following:
6454**
6455** (1) SHARED_LOCK
6456** (2) RESERVED_LOCK
6457** (3) PENDING_LOCK
6458** (4) EXCLUSIVE_LOCK
6459**
6460** Sometimes when requesting one lock state, additional lock states
6461** are inserted in between. The locking might fail on one of the later
6462** transitions leaving the lock state different from what it started but
6463** still short of its goal. The following chart shows the allowed
6464** transitions and the inserted intermediate states:
6465**
6466** UNLOCKED -> SHARED
6467** SHARED -> RESERVED
6468** SHARED -> (PENDING) -> EXCLUSIVE
6469** RESERVED -> (PENDING) -> EXCLUSIVE
6470** PENDING -> EXCLUSIVE
6471**
6472** This routine will only increase a lock. Use the sqlite3OsUnlock()
6473** routine to lower a locking level.
6474*/
6475static int proxyLock(sqlite3_file *id, int locktype) {
6476 unixFile *pFile = (unixFile*)id;
6477 int rc = proxyTakeConch(pFile);
6478 if( rc==SQLITE_OK ){
6479 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006480 if( pCtx->conchHeld>0 ){
6481 unixFile *proxy = pCtx->lockProxy;
6482 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
6483 pFile->locktype = proxy->locktype;
6484 }else{
6485 /* conchHeld < 0 is lockless */
6486 }
drh715ff302008-12-03 22:32:44 +00006487 }
6488 return rc;
6489}
6490
6491
6492/*
6493** Lower the locking level on file descriptor pFile to locktype. locktype
6494** must be either NO_LOCK or SHARED_LOCK.
6495**
6496** If the locking level of the file descriptor is already at or below
6497** the requested locking level, this routine is a no-op.
6498*/
6499static int proxyUnlock(sqlite3_file *id, int locktype) {
6500 unixFile *pFile = (unixFile*)id;
6501 int rc = proxyTakeConch(pFile);
6502 if( rc==SQLITE_OK ){
6503 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006504 if( pCtx->conchHeld>0 ){
6505 unixFile *proxy = pCtx->lockProxy;
6506 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
6507 pFile->locktype = proxy->locktype;
6508 }else{
6509 /* conchHeld < 0 is lockless */
6510 }
drh715ff302008-12-03 22:32:44 +00006511 }
6512 return rc;
6513}
6514
6515/*
6516** Close a file that uses proxy locks.
6517*/
6518static int proxyClose(sqlite3_file *id) {
6519 if( id ){
6520 unixFile *pFile = (unixFile*)id;
6521 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6522 unixFile *lockProxy = pCtx->lockProxy;
6523 unixFile *conchFile = pCtx->conchFile;
6524 int rc = SQLITE_OK;
6525
6526 if( lockProxy ){
6527 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6528 if( rc ) return rc;
6529 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6530 if( rc ) return rc;
6531 sqlite3_free(lockProxy);
6532 pCtx->lockProxy = 0;
6533 }
6534 if( conchFile ){
6535 if( pCtx->conchHeld ){
6536 rc = proxyReleaseConch(pFile);
6537 if( rc ) return rc;
6538 }
6539 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6540 if( rc ) return rc;
6541 sqlite3_free(conchFile);
6542 }
6543 sqlite3_free(pCtx->lockProxyPath);
6544 sqlite3_free(pCtx->conchFilePath);
6545 sqlite3_free(pCtx->dbPath);
6546 /* restore the original locking context and pMethod then close it */
6547 pFile->lockingContext = pCtx->oldLockingContext;
6548 pFile->pMethod = pCtx->pOldMethod;
6549 sqlite3_free(pCtx);
6550 return pFile->pMethod->xClose(id);
6551 }
6552 return SQLITE_OK;
6553}
6554
6555
6556
drhd2cb50b2009-01-09 21:41:17 +00006557#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006558/*
6559** The proxy locking style is intended for use with AFP filesystems.
6560** And since AFP is only supported on MacOSX, the proxy locking is also
6561** restricted to MacOSX.
6562**
6563**
6564******************* End of the proxy lock implementation **********************
6565******************************************************************************/
6566
drh734c9862008-11-28 15:37:20 +00006567/*
danielk1977e339d652008-06-28 11:23:00 +00006568** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006569**
6570** This routine registers all VFS implementations for unix-like operating
6571** systems. This routine, and the sqlite3_os_end() routine that follows,
6572** should be the only routines in this file that are visible from other
6573** files.
drh6b9d6dd2008-12-03 19:34:47 +00006574**
6575** This routine is called once during SQLite initialization and by a
6576** single thread. The memory allocation and mutex subsystems have not
6577** necessarily been initialized when this routine is called, and so they
6578** should not be used.
drh153c62c2007-08-24 03:51:33 +00006579*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006580int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006581 /*
6582 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006583 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6584 ** to the "finder" function. (pAppData is a pointer to a pointer because
6585 ** silly C90 rules prohibit a void* from being cast to a function pointer
6586 ** and so we have to go through the intermediate pointer to avoid problems
6587 ** when compiling with -pedantic-errors on GCC.)
6588 **
6589 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006590 ** finder-function. The finder-function returns a pointer to the
6591 ** sqlite_io_methods object that implements the desired locking
6592 ** behaviors. See the division above that contains the IOMETHODS
6593 ** macro for addition information on finder-functions.
6594 **
6595 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6596 ** object. But the "autolockIoFinder" available on MacOSX does a little
6597 ** more than that; it looks at the filesystem type that hosts the
6598 ** database file and tries to choose an locking method appropriate for
6599 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006600 */
drh7708e972008-11-29 00:56:52 +00006601 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006602 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006603 sizeof(unixFile), /* szOsFile */ \
6604 MAX_PATHNAME, /* mxPathname */ \
6605 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006606 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006607 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006608 unixOpen, /* xOpen */ \
6609 unixDelete, /* xDelete */ \
6610 unixAccess, /* xAccess */ \
6611 unixFullPathname, /* xFullPathname */ \
6612 unixDlOpen, /* xDlOpen */ \
6613 unixDlError, /* xDlError */ \
6614 unixDlSym, /* xDlSym */ \
6615 unixDlClose, /* xDlClose */ \
6616 unixRandomness, /* xRandomness */ \
6617 unixSleep, /* xSleep */ \
6618 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006619 unixGetLastError, /* xGetLastError */ \
drhf2424c52010-04-26 00:04:55 +00006620 0, /* xRename */ \
drhb7e8ea22010-05-03 14:32:30 +00006621 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006622 }
6623
drh6b9d6dd2008-12-03 19:34:47 +00006624 /*
6625 ** All default VFSes for unix are contained in the following array.
6626 **
6627 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6628 ** by the SQLite core when the VFS is registered. So the following
6629 ** array cannot be const.
6630 */
danielk1977e339d652008-06-28 11:23:00 +00006631 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006632#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006633 UNIXVFS("unix", autolockIoFinder ),
6634#else
6635 UNIXVFS("unix", posixIoFinder ),
6636#endif
6637 UNIXVFS("unix-none", nolockIoFinder ),
6638 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006639#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006640 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006641#endif
6642#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006643 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006644#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006645 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006646#endif
chw78a13182009-04-07 05:35:03 +00006647#endif
drhd2cb50b2009-01-09 21:41:17 +00006648#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006649 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006650 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006651 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006652#endif
drh153c62c2007-08-24 03:51:33 +00006653 };
drh6b9d6dd2008-12-03 19:34:47 +00006654 unsigned int i; /* Loop counter */
6655
6656 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006657 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006658 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006659 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006660 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006661}
danielk1977e339d652008-06-28 11:23:00 +00006662
6663/*
drh6b9d6dd2008-12-03 19:34:47 +00006664** Shutdown the operating system interface.
6665**
6666** Some operating systems might need to do some cleanup in this routine,
6667** to release dynamically allocated objects. But not on unix.
6668** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006669*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006670int sqlite3_os_end(void){
6671 return SQLITE_OK;
6672}
drhdce8bdb2007-08-16 13:01:44 +00006673
danielk197729bafea2008-06-26 10:41:19 +00006674#endif /* SQLITE_OS_UNIX */