blob: 473432be5fec39620f104768d3db84b90c849abd [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>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
209 int lastErrno; /* The unix errno from last I/O error */
210 void *lockingContext; /* Locking style specific state */
211 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
212 int fileFlags; /* Miscellanous flags */
213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 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
drh8af6c222010-05-14 12:43:01 +0000296** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000297** vxworksFileId objects used by this file, all of which may be
298** shared by multiple threads.
299**
300** Function unixMutexHeld() is used to assert() that the global mutex
301** is held when required. This function is only used as part of assert()
302** statements. e.g.
303**
304** unixEnterMutex()
305** assert( unixMutexHeld() );
306** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000307*/
308static void unixEnterMutex(void){
309 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
310}
311static void unixLeaveMutex(void){
312 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
313}
dan9359c7b2009-08-21 08:29:10 +0000314#ifdef SQLITE_DEBUG
315static int unixMutexHeld(void) {
316 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
317}
318#endif
drh107886a2008-11-21 22:21:50 +0000319
drh734c9862008-11-28 15:37:20 +0000320
321#ifdef SQLITE_DEBUG
322/*
323** Helper function for printing out trace information from debugging
324** binaries. This returns the string represetation of the supplied
325** integer lock-type.
326*/
drh308c2a52010-05-14 11:30:18 +0000327static const char *azFileLock(int eFileLock){
328 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000329 case NO_LOCK: return "NONE";
330 case SHARED_LOCK: return "SHARED";
331 case RESERVED_LOCK: return "RESERVED";
332 case PENDING_LOCK: return "PENDING";
333 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000334 }
335 return "ERROR";
336}
337#endif
338
339#ifdef SQLITE_LOCK_TRACE
340/*
341** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000342**
drh734c9862008-11-28 15:37:20 +0000343** This routine is used for troubleshooting locks on multithreaded
344** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
345** command-line option on the compiler. This code is normally
346** turned off.
347*/
348static int lockTrace(int fd, int op, struct flock *p){
349 char *zOpName, *zType;
350 int s;
351 int savedErrno;
352 if( op==F_GETLK ){
353 zOpName = "GETLK";
354 }else if( op==F_SETLK ){
355 zOpName = "SETLK";
356 }else{
357 s = fcntl(fd, op, p);
358 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
359 return s;
360 }
361 if( p->l_type==F_RDLCK ){
362 zType = "RDLCK";
363 }else if( p->l_type==F_WRLCK ){
364 zType = "WRLCK";
365 }else if( p->l_type==F_UNLCK ){
366 zType = "UNLCK";
367 }else{
368 assert( 0 );
369 }
370 assert( p->l_whence==SEEK_SET );
371 s = fcntl(fd, op, p);
372 savedErrno = errno;
373 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
374 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
375 (int)p->l_pid, s);
376 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
377 struct flock l2;
378 l2 = *p;
379 fcntl(fd, F_GETLK, &l2);
380 if( l2.l_type==F_RDLCK ){
381 zType = "RDLCK";
382 }else if( l2.l_type==F_WRLCK ){
383 zType = "WRLCK";
384 }else if( l2.l_type==F_UNLCK ){
385 zType = "UNLCK";
386 }else{
387 assert( 0 );
388 }
389 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
390 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
391 }
392 errno = savedErrno;
393 return s;
394}
395#define fcntl lockTrace
396#endif /* SQLITE_LOCK_TRACE */
397
398
drhff812312011-02-23 13:33:46 +0000399/*
400** Retry ftruncate() calls that fail due to EINTR
401*/
402#ifdef EINTR
403static int robust_ftruncate(int h, sqlite3_int64 sz){
404 int rc;
405 do{ rc = ftruncate(h,sz); }while( rc<0 && errno==EINTR );
406 return rc;
407}
408#else
409# define robust_ftruncate(a,b) ftruncate(a,b)
410#endif
411
drh734c9862008-11-28 15:37:20 +0000412
413/*
414** This routine translates a standard POSIX errno code into something
415** useful to the clients of the sqlite3 functions. Specifically, it is
416** intended to translate a variety of "try again" errors into SQLITE_BUSY
417** and a variety of "please close the file descriptor NOW" errors into
418** SQLITE_IOERR
419**
420** Errors during initialization of locks, or file system support for locks,
421** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
422*/
423static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
424 switch (posixError) {
425 case 0:
426 return SQLITE_OK;
427
428 case EAGAIN:
429 case ETIMEDOUT:
430 case EBUSY:
431 case EINTR:
432 case ENOLCK:
433 /* random NFS retry error, unless during file system support
434 * introspection, in which it actually means what it says */
435 return SQLITE_BUSY;
436
437 case EACCES:
438 /* EACCES is like EAGAIN during locking operations, but not any other time*/
439 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
440 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
441 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
442 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
443 return SQLITE_BUSY;
444 }
445 /* else fall through */
446 case EPERM:
447 return SQLITE_PERM;
448
449 case EDEADLK:
450 return SQLITE_IOERR_BLOCKED;
451
452#if EOPNOTSUPP!=ENOTSUP
453 case EOPNOTSUPP:
454 /* something went terribly awry, unless during file system support
455 * introspection, in which it actually means what it says */
456#endif
457#ifdef ENOTSUP
458 case ENOTSUP:
459 /* invalid fd, unless during file system support introspection, in which
460 * it actually means what it says */
461#endif
462 case EIO:
463 case EBADF:
464 case EINVAL:
465 case ENOTCONN:
466 case ENODEV:
467 case ENXIO:
468 case ENOENT:
469 case ESTALE:
470 case ENOSYS:
471 /* these should force the client to close the file and reconnect */
472
473 default:
474 return sqliteIOErr;
475 }
476}
477
478
479
480/******************************************************************************
481****************** Begin Unique File ID Utility Used By VxWorks ***************
482**
483** On most versions of unix, we can get a unique ID for a file by concatenating
484** the device number and the inode number. But this does not work on VxWorks.
485** On VxWorks, a unique file id must be based on the canonical filename.
486**
487** A pointer to an instance of the following structure can be used as a
488** unique file ID in VxWorks. Each instance of this structure contains
489** a copy of the canonical filename. There is also a reference count.
490** The structure is reclaimed when the number of pointers to it drops to
491** zero.
492**
493** There are never very many files open at one time and lookups are not
494** a performance-critical path, so it is sufficient to put these
495** structures on a linked list.
496*/
497struct vxworksFileId {
498 struct vxworksFileId *pNext; /* Next in a list of them all */
499 int nRef; /* Number of references to this one */
500 int nName; /* Length of the zCanonicalName[] string */
501 char *zCanonicalName; /* Canonical filename */
502};
503
504#if OS_VXWORKS
505/*
drh9b35ea62008-11-29 02:20:26 +0000506** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000507** variable:
508*/
509static struct vxworksFileId *vxworksFileList = 0;
510
511/*
512** Simplify a filename into its canonical form
513** by making the following changes:
514**
515** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000516** * convert /./ into just /
517** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000518**
519** Changes are made in-place. Return the new name length.
520**
521** The original filename is in z[0..n-1]. Return the number of
522** characters in the simplified name.
523*/
524static int vxworksSimplifyName(char *z, int n){
525 int i, j;
526 while( n>1 && z[n-1]=='/' ){ n--; }
527 for(i=j=0; i<n; i++){
528 if( z[i]=='/' ){
529 if( z[i+1]=='/' ) continue;
530 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
531 i += 1;
532 continue;
533 }
534 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
535 while( j>0 && z[j-1]!='/' ){ j--; }
536 if( j>0 ){ j--; }
537 i += 2;
538 continue;
539 }
540 }
541 z[j++] = z[i];
542 }
543 z[j] = 0;
544 return j;
545}
546
547/*
548** Find a unique file ID for the given absolute pathname. Return
549** a pointer to the vxworksFileId object. This pointer is the unique
550** file ID.
551**
552** The nRef field of the vxworksFileId object is incremented before
553** the object is returned. A new vxworksFileId object is created
554** and added to the global list if necessary.
555**
556** If a memory allocation error occurs, return NULL.
557*/
558static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
559 struct vxworksFileId *pNew; /* search key and new file ID */
560 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
561 int n; /* Length of zAbsoluteName string */
562
563 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000564 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000565 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
566 if( pNew==0 ) return 0;
567 pNew->zCanonicalName = (char*)&pNew[1];
568 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
569 n = vxworksSimplifyName(pNew->zCanonicalName, n);
570
571 /* Search for an existing entry that matching the canonical name.
572 ** If found, increment the reference count and return a pointer to
573 ** the existing file ID.
574 */
575 unixEnterMutex();
576 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
577 if( pCandidate->nName==n
578 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
579 ){
580 sqlite3_free(pNew);
581 pCandidate->nRef++;
582 unixLeaveMutex();
583 return pCandidate;
584 }
585 }
586
587 /* No match was found. We will make a new file ID */
588 pNew->nRef = 1;
589 pNew->nName = n;
590 pNew->pNext = vxworksFileList;
591 vxworksFileList = pNew;
592 unixLeaveMutex();
593 return pNew;
594}
595
596/*
597** Decrement the reference count on a vxworksFileId object. Free
598** the object when the reference count reaches zero.
599*/
600static void vxworksReleaseFileId(struct vxworksFileId *pId){
601 unixEnterMutex();
602 assert( pId->nRef>0 );
603 pId->nRef--;
604 if( pId->nRef==0 ){
605 struct vxworksFileId **pp;
606 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
607 assert( *pp==pId );
608 *pp = pId->pNext;
609 sqlite3_free(pId);
610 }
611 unixLeaveMutex();
612}
613#endif /* OS_VXWORKS */
614/*************** End of Unique File ID Utility Used By VxWorks ****************
615******************************************************************************/
616
617
618/******************************************************************************
619*************************** Posix Advisory Locking ****************************
620**
drh9b35ea62008-11-29 02:20:26 +0000621** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000622** section 6.5.2.2 lines 483 through 490 specify that when a process
623** sets or clears a lock, that operation overrides any prior locks set
624** by the same process. It does not explicitly say so, but this implies
625** that it overrides locks set by the same process using a different
626** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000627**
628** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000629** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
630**
631** Suppose ./file1 and ./file2 are really the same file (because
632** one is a hard or symbolic link to the other) then if you set
633** an exclusive lock on fd1, then try to get an exclusive lock
634** on fd2, it works. I would have expected the second lock to
635** fail since there was already a lock on the file due to fd1.
636** But not so. Since both locks came from the same process, the
637** second overrides the first, even though they were on different
638** file descriptors opened on different file names.
639**
drh734c9862008-11-28 15:37:20 +0000640** This means that we cannot use POSIX locks to synchronize file access
641** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000642** to synchronize access for threads in separate processes, but not
643** threads within the same process.
644**
645** To work around the problem, SQLite has to manage file locks internally
646** on its own. Whenever a new database is opened, we have to find the
647** specific inode of the database file (the inode is determined by the
648** st_dev and st_ino fields of the stat structure that fstat() fills in)
649** and check for locks already existing on that inode. When locks are
650** created or removed, we have to look at our own internal record of the
651** locks to see if another thread has previously set a lock on that same
652** inode.
653**
drh9b35ea62008-11-29 02:20:26 +0000654** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
655** For VxWorks, we have to use the alternative unique ID system based on
656** canonical filename and implemented in the previous division.)
657**
danielk1977ad94b582007-08-20 06:44:22 +0000658** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000659** descriptor. It is now a structure that holds the integer file
660** descriptor and a pointer to a structure that describes the internal
661** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000662** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000663** point to the same locking structure. The locking structure keeps
664** a reference count (so we will know when to delete it) and a "cnt"
665** field that tells us its internal lock status. cnt==0 means the
666** file is unlocked. cnt==-1 means the file has an exclusive lock.
667** cnt>0 means there are cnt shared locks on the file.
668**
669** Any attempt to lock or unlock a file first checks the locking
670** structure. The fcntl() system call is only invoked to set a
671** POSIX lock if the internal lock structure transitions between
672** a locked and an unlocked state.
673**
drh734c9862008-11-28 15:37:20 +0000674** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000675**
676** If you close a file descriptor that points to a file that has locks,
677** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000678** released. To work around this problem, each unixInodeInfo object
679** maintains a count of the number of pending locks on tha inode.
680** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000681** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000682** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000683** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000684** be closed and that list is walked (and cleared) when the last lock
685** clears.
686**
drh9b35ea62008-11-29 02:20:26 +0000687** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000688**
drh9b35ea62008-11-29 02:20:26 +0000689** Many older versions of linux use the LinuxThreads library which is
690** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000691** A cannot be modified or overridden by a different thread B.
692** Only thread A can modify the lock. Locking behavior is correct
693** if the appliation uses the newer Native Posix Thread Library (NPTL)
694** on linux - with NPTL a lock created by thread A can override locks
695** in thread B. But there is no way to know at compile-time which
696** threading library is being used. So there is no way to know at
697** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000698** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000699** current process.
drh5fdae772004-06-29 03:29:00 +0000700**
drh8af6c222010-05-14 12:43:01 +0000701** SQLite used to support LinuxThreads. But support for LinuxThreads
702** was dropped beginning with version 3.7.0. SQLite will still work with
703** LinuxThreads provided that (1) there is no more than one connection
704** per database file in the same process and (2) database connections
705** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000706*/
707
708/*
709** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000710** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000711*/
712struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000713 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000714#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000715 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000716#else
drh107886a2008-11-21 22:21:50 +0000717 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000718#endif
719};
720
721/*
drhbbd42a62004-05-22 17:41:58 +0000722** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000723** inode. Or, on LinuxThreads, there is one of these structures for
724** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000725**
danielk1977ad94b582007-08-20 06:44:22 +0000726** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000727** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000728** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000729*/
drh8af6c222010-05-14 12:43:01 +0000730struct unixInodeInfo {
731 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000732 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000733 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000734 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000735 unixShmNode *pShmNode; /* Shared memory associated with this inode */
736 int nLock; /* Number of outstanding file locks */
737 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
738 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
739 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000740#if defined(SQLITE_ENABLE_LOCKING_STYLE)
741 unsigned long long sharedByte; /* for AFP simulated shared lock */
742#endif
drh6c7d5c52008-11-21 20:32:33 +0000743#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000744 sem_t *pSem; /* Named POSIX semaphore */
745 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000746#endif
drhbbd42a62004-05-22 17:41:58 +0000747};
748
drhda0e7682008-07-30 15:27:54 +0000749/*
drh8af6c222010-05-14 12:43:01 +0000750** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000751*/
drhd91c68f2010-05-14 14:52:25 +0000752static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000753
drh5fdae772004-06-29 03:29:00 +0000754/*
dane18d4952011-02-21 11:46:24 +0000755**
756** This function - unixLogError_x(), is only ever called via the macro
757** unixLogError().
758**
759** It is invoked after an error occurs in an OS function and errno has been
760** set. It logs a message using sqlite3_log() containing the current value of
761** errno and, if possible, the human-readable equivalent from strerror() or
762** strerror_r().
763**
764** The first argument passed to the macro should be the error code that
765** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
766** The two subsequent arguments should be the name of the OS function that
767** failed (e.g. "unlink", "open") and the the associated file-system path,
768** if any.
769*/
770#define unixLogError(a,b,c) unixLogError_x(a,b,c,__LINE__)
771static int unixLogError_x(
772 int errcode, /* SQLite error code */
773 const char *zFunc, /* Name of OS function that failed */
774 const char *zPath, /* File path associated with error */
775 int iLine /* Source line number where error occurred */
776){
777 char *zErr; /* Message from strerror() or equivalent */
778
779 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
780 ** the strerror() function to obtain the human-readable error message
781 ** equivalent to errno. Otherwise, use strerror_r().
782 */
783#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
784 char aErr[80];
785 memset(aErr, 0, sizeof(aErr));
786 zErr = aErr;
787
788 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
789 ** assume that the system provides the the GNU version of strerror_r() that
790 ** returns a pointer to a buffer containing the error message. That pointer
791 ** may point to aErr[], or it may point to some static storage somewhere.
792 ** Otherwise, assume that the system provides the POSIX version of
793 ** strerror_r(), which always writes an error message into aErr[].
794 **
795 ** If the code incorrectly assumes that it is the POSIX version that is
796 ** available, the error message will often be an empty string. Not a
797 ** huge problem. Incorrectly concluding that the GNU version is available
798 ** could lead to a segfault though.
799 */
800#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
801 zErr =
802# endif
803 strerror_r(errno, aErr, sizeof(aErr)-1);
804
805#elif SQLITE_THREADSAFE
806 /* This is a threadsafe build, but strerror_r() is not available. */
807 zErr = "";
808#else
809 /* Non-threadsafe build, use strerror(). */
810 zErr = strerror(errno);
811#endif
812
813 assert( errcode!=SQLITE_OK );
814 sqlite3_log(errcode,
815 "os_unix.c: %s() at line %d - \"%s\" errno=%d path=%s",
816 zFunc, iLine, zErr, errno, (zPath ? zPath : "n/a")
817 );
818
819 return errcode;
820}
821
822
823/*
danb0ac3e32010-06-16 10:55:42 +0000824** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
825** If all such file descriptors are closed without error, the list is
826** cleared and SQLITE_OK returned.
827**
828** Otherwise, if an error occurs, then successfully closed file descriptor
829** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
830** not deleted and SQLITE_IOERR_CLOSE returned.
831*/
832static int closePendingFds(unixFile *pFile){
833 int rc = SQLITE_OK;
834 unixInodeInfo *pInode = pFile->pInode;
835 UnixUnusedFd *pError = 0;
836 UnixUnusedFd *p;
837 UnixUnusedFd *pNext;
838 for(p=pInode->pUnused; p; p=pNext){
839 pNext = p->pNext;
840 if( close(p->fd) ){
841 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +0000842 rc = unixLogError(SQLITE_IOERR_CLOSE, "close", pFile->zPath);
danb0ac3e32010-06-16 10:55:42 +0000843 p->pNext = pError;
844 pError = p;
845 }else{
846 sqlite3_free(p);
847 }
848 }
849 pInode->pUnused = pError;
850 return rc;
851}
852
853/*
drh8af6c222010-05-14 12:43:01 +0000854** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000855**
856** The mutex entered using the unixEnterMutex() function must be held
857** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000858*/
danb0ac3e32010-06-16 10:55:42 +0000859static void releaseInodeInfo(unixFile *pFile){
860 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000861 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000862 if( pInode ){
863 pInode->nRef--;
864 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000865 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000866 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000867 if( pInode->pPrev ){
868 assert( pInode->pPrev->pNext==pInode );
869 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000870 }else{
drh8af6c222010-05-14 12:43:01 +0000871 assert( inodeList==pInode );
872 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000873 }
drh8af6c222010-05-14 12:43:01 +0000874 if( pInode->pNext ){
875 assert( pInode->pNext->pPrev==pInode );
876 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000877 }
drh8af6c222010-05-14 12:43:01 +0000878 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000879 }
drhbbd42a62004-05-22 17:41:58 +0000880 }
881}
882
883/*
drh8af6c222010-05-14 12:43:01 +0000884** Given a file descriptor, locate the unixInodeInfo object that
885** describes that file descriptor. Create a new one if necessary. The
886** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000887**
dan9359c7b2009-08-21 08:29:10 +0000888** The mutex entered using the unixEnterMutex() function must be held
889** when this function is called.
890**
drh6c7d5c52008-11-21 20:32:33 +0000891** Return an appropriate error code.
892*/
drh8af6c222010-05-14 12:43:01 +0000893static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000894 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000895 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000896){
897 int rc; /* System call return code */
898 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000899 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
900 struct stat statbuf; /* Low-level file information */
901 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000902
dan9359c7b2009-08-21 08:29:10 +0000903 assert( unixMutexHeld() );
904
drh6c7d5c52008-11-21 20:32:33 +0000905 /* Get low-level information about the file that we can used to
906 ** create a unique name for the file.
907 */
908 fd = pFile->h;
909 rc = fstat(fd, &statbuf);
910 if( rc!=0 ){
911 pFile->lastErrno = errno;
912#ifdef EOVERFLOW
913 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
914#endif
915 return SQLITE_IOERR;
916 }
917
drheb0d74f2009-02-03 15:27:02 +0000918#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000919 /* On OS X on an msdos filesystem, the inode number is reported
920 ** incorrectly for zero-size files. See ticket #3260. To work
921 ** around this problem (we consider it a bug in OS X, not SQLite)
922 ** we always increase the file size to 1 by writing a single byte
923 ** prior to accessing the inode number. The one byte written is
924 ** an ASCII 'S' character which also happens to be the first byte
925 ** in the header of every SQLite database. In this way, if there
926 ** is a race condition such that another thread has already populated
927 ** the first page of the database, no damage is done.
928 */
drh7ed97b92010-01-20 13:07:21 +0000929 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhff812312011-02-23 13:33:46 +0000930 do{ rc = write(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +0000931 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000932 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000933 return SQLITE_IOERR;
934 }
drh6c7d5c52008-11-21 20:32:33 +0000935 rc = fstat(fd, &statbuf);
936 if( rc!=0 ){
937 pFile->lastErrno = errno;
938 return SQLITE_IOERR;
939 }
940 }
drheb0d74f2009-02-03 15:27:02 +0000941#endif
drh6c7d5c52008-11-21 20:32:33 +0000942
drh8af6c222010-05-14 12:43:01 +0000943 memset(&fileId, 0, sizeof(fileId));
944 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000945#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000946 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000947#else
drh8af6c222010-05-14 12:43:01 +0000948 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000949#endif
drh8af6c222010-05-14 12:43:01 +0000950 pInode = inodeList;
951 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
952 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000953 }
drh8af6c222010-05-14 12:43:01 +0000954 if( pInode==0 ){
955 pInode = sqlite3_malloc( sizeof(*pInode) );
956 if( pInode==0 ){
957 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000958 }
drh8af6c222010-05-14 12:43:01 +0000959 memset(pInode, 0, sizeof(*pInode));
960 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
961 pInode->nRef = 1;
962 pInode->pNext = inodeList;
963 pInode->pPrev = 0;
964 if( inodeList ) inodeList->pPrev = pInode;
965 inodeList = pInode;
966 }else{
967 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000968 }
drh8af6c222010-05-14 12:43:01 +0000969 *ppInode = pInode;
970 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000971}
drh6c7d5c52008-11-21 20:32:33 +0000972
aswift5b1a2562008-08-22 00:22:35 +0000973
974/*
danielk197713adf8a2004-06-03 16:08:41 +0000975** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000976** file by this or any other process. If such a lock is held, set *pResOut
977** to a non-zero value otherwise *pResOut is set to zero. The return value
978** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000979*/
danielk1977861f7452008-06-05 11:39:11 +0000980static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000981 int rc = SQLITE_OK;
982 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000983 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000984
danielk1977861f7452008-06-05 11:39:11 +0000985 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
986
drh054889e2005-11-30 03:20:31 +0000987 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000988 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000989
990 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000991 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000992 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000993 }
994
drh2ac3ee92004-06-07 16:27:46 +0000995 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000996 */
danielk197709480a92009-02-09 05:32:32 +0000997#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000998 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000999 struct flock lock;
1000 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001001 lock.l_start = RESERVED_BYTE;
1002 lock.l_len = 1;
1003 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001004 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1005 int tErrno = errno;
1006 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1007 pFile->lastErrno = tErrno;
1008 } else if( lock.l_type!=F_UNLCK ){
1009 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001010 }
1011 }
danielk197709480a92009-02-09 05:32:32 +00001012#endif
danielk197713adf8a2004-06-03 16:08:41 +00001013
drh6c7d5c52008-11-21 20:32:33 +00001014 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001015 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001016
aswift5b1a2562008-08-22 00:22:35 +00001017 *pResOut = reserved;
1018 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001019}
1020
1021/*
drh308c2a52010-05-14 11:30:18 +00001022** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001023** of the following:
1024**
drh2ac3ee92004-06-07 16:27:46 +00001025** (1) SHARED_LOCK
1026** (2) RESERVED_LOCK
1027** (3) PENDING_LOCK
1028** (4) EXCLUSIVE_LOCK
1029**
drhb3e04342004-06-08 00:47:47 +00001030** Sometimes when requesting one lock state, additional lock states
1031** are inserted in between. The locking might fail on one of the later
1032** transitions leaving the lock state different from what it started but
1033** still short of its goal. The following chart shows the allowed
1034** transitions and the inserted intermediate states:
1035**
1036** UNLOCKED -> SHARED
1037** SHARED -> RESERVED
1038** SHARED -> (PENDING) -> EXCLUSIVE
1039** RESERVED -> (PENDING) -> EXCLUSIVE
1040** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001041**
drha6abd042004-06-09 17:37:22 +00001042** This routine will only increase a lock. Use the sqlite3OsUnlock()
1043** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001044*/
drh308c2a52010-05-14 11:30:18 +00001045static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001046 /* The following describes the implementation of the various locks and
1047 ** lock transitions in terms of the POSIX advisory shared and exclusive
1048 ** lock primitives (called read-locks and write-locks below, to avoid
1049 ** confusion with SQLite lock names). The algorithms are complicated
1050 ** slightly in order to be compatible with windows systems simultaneously
1051 ** accessing the same database file, in case that is ever required.
1052 **
1053 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1054 ** byte', each single bytes at well known offsets, and the 'shared byte
1055 ** range', a range of 510 bytes at a well known offset.
1056 **
1057 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1058 ** byte'. If this is successful, a random byte from the 'shared byte
1059 ** range' is read-locked and the lock on the 'pending byte' released.
1060 **
danielk197790ba3bd2004-06-25 08:32:25 +00001061 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1062 ** A RESERVED lock is implemented by grabbing a write-lock on the
1063 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001064 **
1065 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001066 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1067 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1068 ** obtained, but existing SHARED locks are allowed to persist. A process
1069 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1070 ** This property is used by the algorithm for rolling back a journal file
1071 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001072 **
danielk197790ba3bd2004-06-25 08:32:25 +00001073 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1074 ** implemented by obtaining a write-lock on the entire 'shared byte
1075 ** range'. Since all other locks require a read-lock on one of the bytes
1076 ** within this range, this ensures that no other locks are held on the
1077 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001078 **
1079 ** The reason a single byte cannot be used instead of the 'shared byte
1080 ** range' is that some versions of windows do not support read-locks. By
1081 ** locking a random byte from a range, concurrent SHARED locks may exist
1082 ** even if the locking primitive used is always a write-lock.
1083 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001084 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001085 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001086 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001087 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001088 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001089 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001090
drh054889e2005-11-30 03:20:31 +00001091 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001092 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1093 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001094 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001095
1096 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001097 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001098 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001099 */
drh308c2a52010-05-14 11:30:18 +00001100 if( pFile->eFileLock>=eFileLock ){
1101 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1102 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001103 return SQLITE_OK;
1104 }
1105
drh0c2694b2009-09-03 16:23:44 +00001106 /* Make sure the locking sequence is correct.
1107 ** (1) We never move from unlocked to anything higher than shared lock.
1108 ** (2) SQLite never explicitly requests a pendig lock.
1109 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001110 */
drh308c2a52010-05-14 11:30:18 +00001111 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1112 assert( eFileLock!=PENDING_LOCK );
1113 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001114
drh8af6c222010-05-14 12:43:01 +00001115 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001116 */
drh6c7d5c52008-11-21 20:32:33 +00001117 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001118 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001119
danielk1977ad94b582007-08-20 06:44:22 +00001120 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001121 ** handle that precludes the requested lock, return BUSY.
1122 */
drh8af6c222010-05-14 12:43:01 +00001123 if( (pFile->eFileLock!=pInode->eFileLock &&
1124 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001125 ){
1126 rc = SQLITE_BUSY;
1127 goto end_lock;
1128 }
1129
1130 /* If a SHARED lock is requested, and some thread using this PID already
1131 ** has a SHARED or RESERVED lock, then increment reference counts and
1132 ** return SQLITE_OK.
1133 */
drh308c2a52010-05-14 11:30:18 +00001134 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001135 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001136 assert( eFileLock==SHARED_LOCK );
1137 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001138 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001139 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001140 pInode->nShared++;
1141 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001142 goto end_lock;
1143 }
1144
danielk19779a1d0ab2004-06-01 14:09:28 +00001145
drh3cde3bb2004-06-12 02:17:14 +00001146 /* A PENDING lock is needed before acquiring a SHARED lock and before
1147 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1148 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001149 */
drh0c2694b2009-09-03 16:23:44 +00001150 lock.l_len = 1L;
1151 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001152 if( eFileLock==SHARED_LOCK
1153 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001154 ){
drh308c2a52010-05-14 11:30:18 +00001155 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001156 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001157 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001158 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001159 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001160 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1161 if( IS_LOCK_ERROR(rc) ){
1162 pFile->lastErrno = tErrno;
1163 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001164 goto end_lock;
1165 }
drh3cde3bb2004-06-12 02:17:14 +00001166 }
1167
1168
1169 /* If control gets to this point, then actually go ahead and make
1170 ** operating system calls for the specified lock.
1171 */
drh308c2a52010-05-14 11:30:18 +00001172 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001173 assert( pInode->nShared==0 );
1174 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001175
drh2ac3ee92004-06-07 16:27:46 +00001176 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001177 lock.l_start = SHARED_FIRST;
1178 lock.l_len = SHARED_SIZE;
1179 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1180 tErrno = errno;
1181 }
drh2ac3ee92004-06-07 16:27:46 +00001182 /* Drop the temporary PENDING lock */
1183 lock.l_start = PENDING_BYTE;
1184 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001185 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001186 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001187 if( s != -1 ){
1188 /* This could happen with a network mount */
1189 tErrno = errno;
1190 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1191 if( IS_LOCK_ERROR(rc) ){
1192 pFile->lastErrno = tErrno;
1193 }
1194 goto end_lock;
1195 }
drh2b4b5962005-06-15 17:47:55 +00001196 }
drhe2396a12007-03-29 20:19:58 +00001197 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001198 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1199 if( IS_LOCK_ERROR(rc) ){
1200 pFile->lastErrno = tErrno;
1201 }
drhbbd42a62004-05-22 17:41:58 +00001202 }else{
drh308c2a52010-05-14 11:30:18 +00001203 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001204 pInode->nLock++;
1205 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001206 }
drh8af6c222010-05-14 12:43:01 +00001207 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001208 /* We are trying for an exclusive lock but another thread in this
1209 ** same process is still holding a shared lock. */
1210 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001211 }else{
drh3cde3bb2004-06-12 02:17:14 +00001212 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001213 ** assumed that there is a SHARED or greater lock on the file
1214 ** already.
1215 */
drh308c2a52010-05-14 11:30:18 +00001216 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001217 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001218 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001219 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001220 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001221 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001222 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001223 lock.l_start = SHARED_FIRST;
1224 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001225 break;
1226 default:
1227 assert(0);
1228 }
drh7ed97b92010-01-20 13:07:21 +00001229 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001230 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001231 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001232 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1233 if( IS_LOCK_ERROR(rc) ){
1234 pFile->lastErrno = tErrno;
1235 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001236 }
drhbbd42a62004-05-22 17:41:58 +00001237 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001238
drh8f941bc2009-01-14 23:03:40 +00001239
1240#ifndef NDEBUG
1241 /* Set up the transaction-counter change checking flags when
1242 ** transitioning from a SHARED to a RESERVED lock. The change
1243 ** from SHARED to RESERVED marks the beginning of a normal
1244 ** write operation (not a hot journal rollback).
1245 */
1246 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001247 && pFile->eFileLock<=SHARED_LOCK
1248 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001249 ){
1250 pFile->transCntrChng = 0;
1251 pFile->dbUpdate = 0;
1252 pFile->inNormalWrite = 1;
1253 }
1254#endif
1255
1256
danielk1977ecb2a962004-06-02 06:30:16 +00001257 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001258 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001259 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001260 }else if( eFileLock==EXCLUSIVE_LOCK ){
1261 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001262 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001263 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001264
1265end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001266 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001267 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1268 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001269 return rc;
1270}
1271
1272/*
dan08da86a2009-08-21 17:18:03 +00001273** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001274** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001275*/
1276static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001277 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001278 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001279 p->pNext = pInode->pUnused;
1280 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001281 pFile->h = -1;
1282 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001283}
1284
1285/*
drh308c2a52010-05-14 11:30:18 +00001286** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001287** must be either NO_LOCK or SHARED_LOCK.
1288**
1289** If the locking level of the file descriptor is already at or below
1290** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001291**
1292** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1293** the byte range is divided into 2 parts and the first part is unlocked then
1294** set to a read lock, then the other part is simply unlocked. This works
1295** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1296** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001297*/
drh308c2a52010-05-14 11:30:18 +00001298static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001299 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001300 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001301 struct flock lock;
1302 int rc = SQLITE_OK;
1303 int h;
drh0c2694b2009-09-03 16:23:44 +00001304 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001305
drh054889e2005-11-30 03:20:31 +00001306 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001307 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001308 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001309 getpid()));
drha6abd042004-06-09 17:37:22 +00001310
drh308c2a52010-05-14 11:30:18 +00001311 assert( eFileLock<=SHARED_LOCK );
1312 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001313 return SQLITE_OK;
1314 }
drh6c7d5c52008-11-21 20:32:33 +00001315 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001316 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001317 pInode = pFile->pInode;
1318 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001319 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001320 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001321 SimulateIOErrorBenign(1);
1322 SimulateIOError( h=(-1) )
1323 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001324
1325#ifndef NDEBUG
1326 /* When reducing a lock such that other processes can start
1327 ** reading the database file again, make sure that the
1328 ** transaction counter was updated if any part of the database
1329 ** file changed. If the transaction counter is not updated,
1330 ** other connections to the same file might not realize that
1331 ** the file has changed and hence might not know to flush their
1332 ** cache. The use of a stale cache can lead to database corruption.
1333 */
dan7c246102010-04-12 19:00:29 +00001334#if 0
drh8f941bc2009-01-14 23:03:40 +00001335 assert( pFile->inNormalWrite==0
1336 || pFile->dbUpdate==0
1337 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001338#endif
drh8f941bc2009-01-14 23:03:40 +00001339 pFile->inNormalWrite = 0;
1340#endif
1341
drh7ed97b92010-01-20 13:07:21 +00001342 /* downgrading to a shared lock on NFS involves clearing the write lock
1343 ** before establishing the readlock - to avoid a race condition we downgrade
1344 ** the lock in 2 blocks, so that part of the range will be covered by a
1345 ** write lock until the rest is covered by a read lock:
1346 ** 1: [WWWWW]
1347 ** 2: [....W]
1348 ** 3: [RRRRW]
1349 ** 4: [RRRR.]
1350 */
drh308c2a52010-05-14 11:30:18 +00001351 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001352
1353#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1354 assert( handleNFSUnlock==0 );
1355#endif
1356#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001357 if( handleNFSUnlock ){
1358 off_t divSize = SHARED_SIZE - 1;
1359
1360 lock.l_type = F_UNLCK;
1361 lock.l_whence = SEEK_SET;
1362 lock.l_start = SHARED_FIRST;
1363 lock.l_len = divSize;
1364 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001365 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001366 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1367 if( IS_LOCK_ERROR(rc) ){
1368 pFile->lastErrno = tErrno;
1369 }
1370 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001371 }
drh7ed97b92010-01-20 13:07:21 +00001372 lock.l_type = F_RDLCK;
1373 lock.l_whence = SEEK_SET;
1374 lock.l_start = SHARED_FIRST;
1375 lock.l_len = divSize;
1376 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001377 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001378 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1379 if( IS_LOCK_ERROR(rc) ){
1380 pFile->lastErrno = tErrno;
1381 }
1382 goto end_unlock;
1383 }
1384 lock.l_type = F_UNLCK;
1385 lock.l_whence = SEEK_SET;
1386 lock.l_start = SHARED_FIRST+divSize;
1387 lock.l_len = SHARED_SIZE-divSize;
1388 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001389 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001390 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1391 if( IS_LOCK_ERROR(rc) ){
1392 pFile->lastErrno = tErrno;
1393 }
1394 goto end_unlock;
1395 }
drh30f776f2011-02-25 03:25:07 +00001396 }else
1397#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1398 {
drh7ed97b92010-01-20 13:07:21 +00001399 lock.l_type = F_RDLCK;
1400 lock.l_whence = SEEK_SET;
1401 lock.l_start = SHARED_FIRST;
1402 lock.l_len = SHARED_SIZE;
1403 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001404 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001405 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1406 if( IS_LOCK_ERROR(rc) ){
1407 pFile->lastErrno = tErrno;
1408 }
1409 goto end_unlock;
1410 }
drh9c105bb2004-10-02 20:38:28 +00001411 }
1412 }
drhbbd42a62004-05-22 17:41:58 +00001413 lock.l_type = F_UNLCK;
1414 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001415 lock.l_start = PENDING_BYTE;
1416 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001417 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001418 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001419 }else{
drh0c2694b2009-09-03 16:23:44 +00001420 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001421 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1422 if( IS_LOCK_ERROR(rc) ){
1423 pFile->lastErrno = tErrno;
1424 }
drhcd731cf2009-03-28 23:23:02 +00001425 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001426 }
drhbbd42a62004-05-22 17:41:58 +00001427 }
drh308c2a52010-05-14 11:30:18 +00001428 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001429 /* Decrement the shared lock counter. Release the lock using an
1430 ** OS call only when all threads in this same process have released
1431 ** the lock.
1432 */
drh8af6c222010-05-14 12:43:01 +00001433 pInode->nShared--;
1434 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001435 lock.l_type = F_UNLCK;
1436 lock.l_whence = SEEK_SET;
1437 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001438 SimulateIOErrorBenign(1);
1439 SimulateIOError( h=(-1) )
1440 SimulateIOErrorBenign(0);
1441 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001442 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001443 }else{
drh0c2694b2009-09-03 16:23:44 +00001444 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001445 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001446 if( IS_LOCK_ERROR(rc) ){
1447 pFile->lastErrno = tErrno;
1448 }
drh8af6c222010-05-14 12:43:01 +00001449 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001450 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001451 }
drha6abd042004-06-09 17:37:22 +00001452 }
1453
drhbbd42a62004-05-22 17:41:58 +00001454 /* Decrement the count of locks against this same file. When the
1455 ** count reaches zero, close any other file descriptors whose close
1456 ** was deferred because of outstanding locks.
1457 */
drh8af6c222010-05-14 12:43:01 +00001458 pInode->nLock--;
1459 assert( pInode->nLock>=0 );
1460 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001461 int rc2 = closePendingFds(pFile);
1462 if( rc==SQLITE_OK ){
1463 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001464 }
drhbbd42a62004-05-22 17:41:58 +00001465 }
1466 }
aswift5b1a2562008-08-22 00:22:35 +00001467
1468end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001469 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001470 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001471 return rc;
drhbbd42a62004-05-22 17:41:58 +00001472}
1473
1474/*
drh308c2a52010-05-14 11:30:18 +00001475** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001476** must be either NO_LOCK or SHARED_LOCK.
1477**
1478** If the locking level of the file descriptor is already at or below
1479** the requested locking level, this routine is a no-op.
1480*/
drh308c2a52010-05-14 11:30:18 +00001481static int unixUnlock(sqlite3_file *id, int eFileLock){
1482 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001483}
1484
1485/*
danielk1977e339d652008-06-28 11:23:00 +00001486** This function performs the parts of the "close file" operation
1487** common to all locking schemes. It closes the directory and file
1488** handles, if they are valid, and sets all fields of the unixFile
1489** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001490**
1491** It is *not* necessary to hold the mutex when this routine is called,
1492** even on VxWorks. A mutex will be acquired on VxWorks by the
1493** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001494*/
1495static int closeUnixFile(sqlite3_file *id){
1496 unixFile *pFile = (unixFile*)id;
1497 if( pFile ){
1498 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001499 int err = close(pFile->dirfd);
1500 if( err ){
1501 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00001502 return unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", pFile->zPath);
aswiftaebf4132008-11-21 00:10:35 +00001503 }else{
1504 pFile->dirfd=-1;
1505 }
danielk1977e339d652008-06-28 11:23:00 +00001506 }
1507 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001508 int err = close(pFile->h);
1509 if( err ){
1510 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00001511 return unixLogError(SQLITE_IOERR_CLOSE, "close", pFile->zPath);
aswiftaebf4132008-11-21 00:10:35 +00001512 }
danielk1977e339d652008-06-28 11:23:00 +00001513 }
drh6c7d5c52008-11-21 20:32:33 +00001514#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001515 if( pFile->pId ){
1516 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001517 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001518 }
drh107886a2008-11-21 22:21:50 +00001519 vxworksReleaseFileId(pFile->pId);
1520 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001521 }
1522#endif
drhff59a112010-05-14 20:15:51 +00001523 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001524 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001525 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001526 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001527 }
1528 return SQLITE_OK;
1529}
1530
1531/*
danielk1977e3026632004-06-22 11:29:02 +00001532** Close a file.
1533*/
danielk197762079062007-08-15 17:08:46 +00001534static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001535 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001536 if( id ){
1537 unixFile *pFile = (unixFile *)id;
1538 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001539 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001540 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001541 /* If there are outstanding locks, do not actually close the file just
1542 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001543 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001544 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001545 */
dan08da86a2009-08-21 17:18:03 +00001546 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001547 }
danb0ac3e32010-06-16 10:55:42 +00001548 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001549 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001550 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001551 }
aswiftaebf4132008-11-21 00:10:35 +00001552 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001553}
1554
drh734c9862008-11-28 15:37:20 +00001555/************** End of the posix advisory lock implementation *****************
1556******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001557
drh734c9862008-11-28 15:37:20 +00001558/******************************************************************************
1559****************************** No-op Locking **********************************
1560**
1561** Of the various locking implementations available, this is by far the
1562** simplest: locking is ignored. No attempt is made to lock the database
1563** file for reading or writing.
1564**
1565** This locking mode is appropriate for use on read-only databases
1566** (ex: databases that are burned into CD-ROM, for example.) It can
1567** also be used if the application employs some external mechanism to
1568** prevent simultaneous access of the same database by two or more
1569** database connections. But there is a serious risk of database
1570** corruption if this locking mode is used in situations where multiple
1571** database connections are accessing the same database file at the same
1572** time and one or more of those connections are writing.
1573*/
drhbfe66312006-10-03 17:40:40 +00001574
drh734c9862008-11-28 15:37:20 +00001575static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1576 UNUSED_PARAMETER(NotUsed);
1577 *pResOut = 0;
1578 return SQLITE_OK;
1579}
drh734c9862008-11-28 15:37:20 +00001580static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1581 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1582 return SQLITE_OK;
1583}
drh734c9862008-11-28 15:37:20 +00001584static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1585 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1586 return SQLITE_OK;
1587}
1588
1589/*
drh9b35ea62008-11-29 02:20:26 +00001590** Close the file.
drh734c9862008-11-28 15:37:20 +00001591*/
1592static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001593 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001594}
1595
1596/******************* End of the no-op lock implementation *********************
1597******************************************************************************/
1598
1599/******************************************************************************
1600************************* Begin dot-file Locking ******************************
1601**
drh0c2694b2009-09-03 16:23:44 +00001602** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001603** files in order to control access to the database. This works on just
1604** about every filesystem imaginable. But there are serious downsides:
1605**
1606** (1) There is zero concurrency. A single reader blocks all other
1607** connections from reading or writing the database.
1608**
1609** (2) An application crash or power loss can leave stale lock files
1610** sitting around that need to be cleared manually.
1611**
1612** Nevertheless, a dotlock is an appropriate locking mode for use if no
1613** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001614**
1615** Dotfile locking works by creating a file in the same directory as the
1616** database and with the same name but with a ".lock" extension added.
1617** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1618** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001619*/
1620
1621/*
1622** The file suffix added to the data base filename in order to create the
1623** lock file.
1624*/
1625#define DOTLOCK_SUFFIX ".lock"
1626
drh7708e972008-11-29 00:56:52 +00001627/*
1628** This routine checks if there is a RESERVED lock held on the specified
1629** file by this or any other process. If such a lock is held, set *pResOut
1630** to a non-zero value otherwise *pResOut is set to zero. The return value
1631** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1632**
1633** In dotfile locking, either a lock exists or it does not. So in this
1634** variation of CheckReservedLock(), *pResOut is set to true if any lock
1635** is held on the file and false if the file is unlocked.
1636*/
drh734c9862008-11-28 15:37:20 +00001637static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1638 int rc = SQLITE_OK;
1639 int reserved = 0;
1640 unixFile *pFile = (unixFile*)id;
1641
1642 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1643
1644 assert( pFile );
1645
1646 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001647 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001648 /* Either this connection or some other connection in the same process
1649 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001650 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001651 }else{
1652 /* The lock is held if and only if the lockfile exists */
1653 const char *zLockFile = (const char*)pFile->lockingContext;
1654 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001655 }
drh308c2a52010-05-14 11:30:18 +00001656 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001657 *pResOut = reserved;
1658 return rc;
1659}
1660
drh7708e972008-11-29 00:56:52 +00001661/*
drh308c2a52010-05-14 11:30:18 +00001662** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001663** of the following:
1664**
1665** (1) SHARED_LOCK
1666** (2) RESERVED_LOCK
1667** (3) PENDING_LOCK
1668** (4) EXCLUSIVE_LOCK
1669**
1670** Sometimes when requesting one lock state, additional lock states
1671** are inserted in between. The locking might fail on one of the later
1672** transitions leaving the lock state different from what it started but
1673** still short of its goal. The following chart shows the allowed
1674** transitions and the inserted intermediate states:
1675**
1676** UNLOCKED -> SHARED
1677** SHARED -> RESERVED
1678** SHARED -> (PENDING) -> EXCLUSIVE
1679** RESERVED -> (PENDING) -> EXCLUSIVE
1680** PENDING -> EXCLUSIVE
1681**
1682** This routine will only increase a lock. Use the sqlite3OsUnlock()
1683** routine to lower a locking level.
1684**
1685** With dotfile locking, we really only support state (4): EXCLUSIVE.
1686** But we track the other locking levels internally.
1687*/
drh308c2a52010-05-14 11:30:18 +00001688static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001689 unixFile *pFile = (unixFile*)id;
1690 int fd;
1691 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001692 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001693
drh7708e972008-11-29 00:56:52 +00001694
1695 /* If we have any lock, then the lock file already exists. All we have
1696 ** to do is adjust our internal record of the lock level.
1697 */
drh308c2a52010-05-14 11:30:18 +00001698 if( pFile->eFileLock > NO_LOCK ){
1699 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001700#if !OS_VXWORKS
1701 /* Always update the timestamp on the old file */
1702 utimes(zLockFile, NULL);
1703#endif
drh7708e972008-11-29 00:56:52 +00001704 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001705 }
1706
1707 /* grab an exclusive lock */
1708 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1709 if( fd<0 ){
1710 /* failed to open/create the file, someone else may have stolen the lock */
1711 int tErrno = errno;
1712 if( EEXIST == tErrno ){
1713 rc = SQLITE_BUSY;
1714 } else {
1715 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1716 if( IS_LOCK_ERROR(rc) ){
1717 pFile->lastErrno = tErrno;
1718 }
1719 }
drh7708e972008-11-29 00:56:52 +00001720 return rc;
drh734c9862008-11-28 15:37:20 +00001721 }
1722 if( close(fd) ){
1723 pFile->lastErrno = errno;
1724 rc = SQLITE_IOERR_CLOSE;
1725 }
1726
1727 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001728 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001729 return rc;
1730}
1731
drh7708e972008-11-29 00:56:52 +00001732/*
drh308c2a52010-05-14 11:30:18 +00001733** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001734** must be either NO_LOCK or SHARED_LOCK.
1735**
1736** If the locking level of the file descriptor is already at or below
1737** the requested locking level, this routine is a no-op.
1738**
1739** When the locking level reaches NO_LOCK, delete the lock file.
1740*/
drh308c2a52010-05-14 11:30:18 +00001741static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001742 unixFile *pFile = (unixFile*)id;
1743 char *zLockFile = (char *)pFile->lockingContext;
1744
1745 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001746 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1747 pFile->eFileLock, getpid()));
1748 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001749
1750 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001751 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001752 return SQLITE_OK;
1753 }
drh7708e972008-11-29 00:56:52 +00001754
1755 /* To downgrade to shared, simply update our internal notion of the
1756 ** lock state. No need to mess with the file on disk.
1757 */
drh308c2a52010-05-14 11:30:18 +00001758 if( eFileLock==SHARED_LOCK ){
1759 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001760 return SQLITE_OK;
1761 }
1762
drh7708e972008-11-29 00:56:52 +00001763 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001764 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001765 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001766 int rc = 0;
1767 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001768 if( ENOENT != tErrno ){
1769 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1770 }
1771 if( IS_LOCK_ERROR(rc) ){
1772 pFile->lastErrno = tErrno;
1773 }
1774 return rc;
1775 }
drh308c2a52010-05-14 11:30:18 +00001776 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001777 return SQLITE_OK;
1778}
1779
1780/*
drh9b35ea62008-11-29 02:20:26 +00001781** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001782*/
1783static int dotlockClose(sqlite3_file *id) {
1784 int rc;
1785 if( id ){
1786 unixFile *pFile = (unixFile*)id;
1787 dotlockUnlock(id, NO_LOCK);
1788 sqlite3_free(pFile->lockingContext);
1789 }
drh734c9862008-11-28 15:37:20 +00001790 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001791 return rc;
1792}
1793/****************** End of the dot-file lock implementation *******************
1794******************************************************************************/
1795
1796/******************************************************************************
1797************************** Begin flock Locking ********************************
1798**
1799** Use the flock() system call to do file locking.
1800**
drh6b9d6dd2008-12-03 19:34:47 +00001801** flock() locking is like dot-file locking in that the various
1802** fine-grain locking levels supported by SQLite are collapsed into
1803** a single exclusive lock. In other words, SHARED, RESERVED, and
1804** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1805** still works when you do this, but concurrency is reduced since
1806** only a single process can be reading the database at a time.
1807**
drh734c9862008-11-28 15:37:20 +00001808** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1809** compiling for VXWORKS.
1810*/
1811#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001812
drh6b9d6dd2008-12-03 19:34:47 +00001813/*
drhff812312011-02-23 13:33:46 +00001814** Retry flock() calls that fail with EINTR
1815*/
1816#ifdef EINTR
1817static int robust_flock(int fd, int op){
1818 int rc;
1819 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
1820 return rc;
1821}
1822#else
drh5c819272011-02-23 14:00:12 +00001823# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00001824#endif
1825
1826
1827/*
drh6b9d6dd2008-12-03 19:34:47 +00001828** This routine checks if there is a RESERVED lock held on the specified
1829** file by this or any other process. If such a lock is held, set *pResOut
1830** to a non-zero value otherwise *pResOut is set to zero. The return value
1831** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1832*/
drh734c9862008-11-28 15:37:20 +00001833static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1834 int rc = SQLITE_OK;
1835 int reserved = 0;
1836 unixFile *pFile = (unixFile*)id;
1837
1838 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1839
1840 assert( pFile );
1841
1842 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001843 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001844 reserved = 1;
1845 }
1846
1847 /* Otherwise see if some other process holds it. */
1848 if( !reserved ){
1849 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00001850 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00001851 if( !lrc ){
1852 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00001853 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00001854 if ( lrc ) {
1855 int tErrno = errno;
1856 /* unlock failed with an error */
1857 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1858 if( IS_LOCK_ERROR(lrc) ){
1859 pFile->lastErrno = tErrno;
1860 rc = lrc;
1861 }
1862 }
1863 } else {
1864 int tErrno = errno;
1865 reserved = 1;
1866 /* someone else might have it reserved */
1867 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1868 if( IS_LOCK_ERROR(lrc) ){
1869 pFile->lastErrno = tErrno;
1870 rc = lrc;
1871 }
1872 }
1873 }
drh308c2a52010-05-14 11:30:18 +00001874 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001875
1876#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1877 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1878 rc = SQLITE_OK;
1879 reserved=1;
1880 }
1881#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1882 *pResOut = reserved;
1883 return rc;
1884}
1885
drh6b9d6dd2008-12-03 19:34:47 +00001886/*
drh308c2a52010-05-14 11:30:18 +00001887** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001888** of the following:
1889**
1890** (1) SHARED_LOCK
1891** (2) RESERVED_LOCK
1892** (3) PENDING_LOCK
1893** (4) EXCLUSIVE_LOCK
1894**
1895** Sometimes when requesting one lock state, additional lock states
1896** are inserted in between. The locking might fail on one of the later
1897** transitions leaving the lock state different from what it started but
1898** still short of its goal. The following chart shows the allowed
1899** transitions and the inserted intermediate states:
1900**
1901** UNLOCKED -> SHARED
1902** SHARED -> RESERVED
1903** SHARED -> (PENDING) -> EXCLUSIVE
1904** RESERVED -> (PENDING) -> EXCLUSIVE
1905** PENDING -> EXCLUSIVE
1906**
1907** flock() only really support EXCLUSIVE locks. We track intermediate
1908** lock states in the sqlite3_file structure, but all locks SHARED or
1909** above are really EXCLUSIVE locks and exclude all other processes from
1910** access the file.
1911**
1912** This routine will only increase a lock. Use the sqlite3OsUnlock()
1913** routine to lower a locking level.
1914*/
drh308c2a52010-05-14 11:30:18 +00001915static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001916 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001917 unixFile *pFile = (unixFile*)id;
1918
1919 assert( pFile );
1920
1921 /* if we already have a lock, it is exclusive.
1922 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001923 if (pFile->eFileLock > NO_LOCK) {
1924 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001925 return SQLITE_OK;
1926 }
1927
1928 /* grab an exclusive lock */
1929
drhff812312011-02-23 13:33:46 +00001930 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00001931 int tErrno = errno;
1932 /* didn't get, must be busy */
1933 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1934 if( IS_LOCK_ERROR(rc) ){
1935 pFile->lastErrno = tErrno;
1936 }
1937 } else {
1938 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001939 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001940 }
drh308c2a52010-05-14 11:30:18 +00001941 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1942 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001943#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1944 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1945 rc = SQLITE_BUSY;
1946 }
1947#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1948 return rc;
1949}
1950
drh6b9d6dd2008-12-03 19:34:47 +00001951
1952/*
drh308c2a52010-05-14 11:30:18 +00001953** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001954** must be either NO_LOCK or SHARED_LOCK.
1955**
1956** If the locking level of the file descriptor is already at or below
1957** the requested locking level, this routine is a no-op.
1958*/
drh308c2a52010-05-14 11:30:18 +00001959static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001960 unixFile *pFile = (unixFile*)id;
1961
1962 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001963 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1964 pFile->eFileLock, getpid()));
1965 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001966
1967 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001968 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001969 return SQLITE_OK;
1970 }
1971
1972 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001973 if (eFileLock==SHARED_LOCK) {
1974 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001975 return SQLITE_OK;
1976 }
1977
1978 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00001979 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00001980 if (rc) {
1981 int r, tErrno = errno;
1982 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1983 if( IS_LOCK_ERROR(r) ){
1984 pFile->lastErrno = tErrno;
1985 }
1986#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1987 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1988 r = SQLITE_BUSY;
1989 }
1990#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1991
1992 return r;
1993 } else {
drh308c2a52010-05-14 11:30:18 +00001994 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001995 return SQLITE_OK;
1996 }
1997}
1998
1999/*
2000** Close a file.
2001*/
2002static int flockClose(sqlite3_file *id) {
2003 if( id ){
2004 flockUnlock(id, NO_LOCK);
2005 }
2006 return closeUnixFile(id);
2007}
2008
2009#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2010
2011/******************* End of the flock lock implementation *********************
2012******************************************************************************/
2013
2014/******************************************************************************
2015************************ Begin Named Semaphore Locking ************************
2016**
2017** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002018**
2019** Semaphore locking is like dot-lock and flock in that it really only
2020** supports EXCLUSIVE locking. Only a single process can read or write
2021** the database file at a time. This reduces potential concurrency, but
2022** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002023*/
2024#if OS_VXWORKS
2025
drh6b9d6dd2008-12-03 19:34:47 +00002026/*
2027** This routine checks if there is a RESERVED lock held on the specified
2028** file by this or any other process. If such a lock is held, set *pResOut
2029** to a non-zero value otherwise *pResOut is set to zero. The return value
2030** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2031*/
drh734c9862008-11-28 15:37:20 +00002032static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2033 int rc = SQLITE_OK;
2034 int reserved = 0;
2035 unixFile *pFile = (unixFile*)id;
2036
2037 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2038
2039 assert( pFile );
2040
2041 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002042 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002043 reserved = 1;
2044 }
2045
2046 /* Otherwise see if some other process holds it. */
2047 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002048 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002049 struct stat statBuf;
2050
2051 if( sem_trywait(pSem)==-1 ){
2052 int tErrno = errno;
2053 if( EAGAIN != tErrno ){
2054 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2055 pFile->lastErrno = tErrno;
2056 } else {
2057 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002058 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002059 }
2060 }else{
2061 /* we could have it if we want it */
2062 sem_post(pSem);
2063 }
2064 }
drh308c2a52010-05-14 11:30:18 +00002065 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002066
2067 *pResOut = reserved;
2068 return rc;
2069}
2070
drh6b9d6dd2008-12-03 19:34:47 +00002071/*
drh308c2a52010-05-14 11:30:18 +00002072** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002073** of the following:
2074**
2075** (1) SHARED_LOCK
2076** (2) RESERVED_LOCK
2077** (3) PENDING_LOCK
2078** (4) EXCLUSIVE_LOCK
2079**
2080** Sometimes when requesting one lock state, additional lock states
2081** are inserted in between. The locking might fail on one of the later
2082** transitions leaving the lock state different from what it started but
2083** still short of its goal. The following chart shows the allowed
2084** transitions and the inserted intermediate states:
2085**
2086** UNLOCKED -> SHARED
2087** SHARED -> RESERVED
2088** SHARED -> (PENDING) -> EXCLUSIVE
2089** RESERVED -> (PENDING) -> EXCLUSIVE
2090** PENDING -> EXCLUSIVE
2091**
2092** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2093** lock states in the sqlite3_file structure, but all locks SHARED or
2094** above are really EXCLUSIVE locks and exclude all other processes from
2095** access the file.
2096**
2097** This routine will only increase a lock. Use the sqlite3OsUnlock()
2098** routine to lower a locking level.
2099*/
drh308c2a52010-05-14 11:30:18 +00002100static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002101 unixFile *pFile = (unixFile*)id;
2102 int fd;
drh8af6c222010-05-14 12:43:01 +00002103 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002104 int rc = SQLITE_OK;
2105
2106 /* if we already have a lock, it is exclusive.
2107 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002108 if (pFile->eFileLock > NO_LOCK) {
2109 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002110 rc = SQLITE_OK;
2111 goto sem_end_lock;
2112 }
2113
2114 /* lock semaphore now but bail out when already locked. */
2115 if( sem_trywait(pSem)==-1 ){
2116 rc = SQLITE_BUSY;
2117 goto sem_end_lock;
2118 }
2119
2120 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002121 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002122
2123 sem_end_lock:
2124 return rc;
2125}
2126
drh6b9d6dd2008-12-03 19:34:47 +00002127/*
drh308c2a52010-05-14 11:30:18 +00002128** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002129** must be either NO_LOCK or SHARED_LOCK.
2130**
2131** If the locking level of the file descriptor is already at or below
2132** the requested locking level, this routine is a no-op.
2133*/
drh308c2a52010-05-14 11:30:18 +00002134static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002135 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002136 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002137
2138 assert( pFile );
2139 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002140 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2141 pFile->eFileLock, getpid()));
2142 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002143
2144 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002145 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002146 return SQLITE_OK;
2147 }
2148
2149 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002150 if (eFileLock==SHARED_LOCK) {
2151 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002152 return SQLITE_OK;
2153 }
2154
2155 /* no, really unlock. */
2156 if ( sem_post(pSem)==-1 ) {
2157 int rc, tErrno = errno;
2158 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2159 if( IS_LOCK_ERROR(rc) ){
2160 pFile->lastErrno = tErrno;
2161 }
2162 return rc;
2163 }
drh308c2a52010-05-14 11:30:18 +00002164 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002165 return SQLITE_OK;
2166}
2167
2168/*
2169 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002170 */
drh734c9862008-11-28 15:37:20 +00002171static int semClose(sqlite3_file *id) {
2172 if( id ){
2173 unixFile *pFile = (unixFile*)id;
2174 semUnlock(id, NO_LOCK);
2175 assert( pFile );
2176 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002177 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002178 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002179 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002180 }
2181 return SQLITE_OK;
2182}
2183
2184#endif /* OS_VXWORKS */
2185/*
2186** Named semaphore locking is only available on VxWorks.
2187**
2188*************** End of the named semaphore lock implementation ****************
2189******************************************************************************/
2190
2191
2192/******************************************************************************
2193*************************** Begin AFP Locking *********************************
2194**
2195** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2196** on Apple Macintosh computers - both OS9 and OSX.
2197**
2198** Third-party implementations of AFP are available. But this code here
2199** only works on OSX.
2200*/
2201
drhd2cb50b2009-01-09 21:41:17 +00002202#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002203/*
2204** The afpLockingContext structure contains all afp lock specific state
2205*/
drhbfe66312006-10-03 17:40:40 +00002206typedef struct afpLockingContext afpLockingContext;
2207struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002208 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002209 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002210};
2211
2212struct ByteRangeLockPB2
2213{
2214 unsigned long long offset; /* offset to first byte to lock */
2215 unsigned long long length; /* nbr of bytes to lock */
2216 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2217 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2218 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2219 int fd; /* file desc to assoc this lock with */
2220};
2221
drhfd131da2007-08-07 17:13:03 +00002222#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002223
drh6b9d6dd2008-12-03 19:34:47 +00002224/*
2225** This is a utility for setting or clearing a bit-range lock on an
2226** AFP filesystem.
2227**
2228** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2229*/
2230static int afpSetLock(
2231 const char *path, /* Name of the file to be locked or unlocked */
2232 unixFile *pFile, /* Open file descriptor on path */
2233 unsigned long long offset, /* First byte to be locked */
2234 unsigned long long length, /* Number of bytes to lock */
2235 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002236){
drh6b9d6dd2008-12-03 19:34:47 +00002237 struct ByteRangeLockPB2 pb;
2238 int err;
drhbfe66312006-10-03 17:40:40 +00002239
2240 pb.unLockFlag = setLockFlag ? 0 : 1;
2241 pb.startEndFlag = 0;
2242 pb.offset = offset;
2243 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002244 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002245
drh308c2a52010-05-14 11:30:18 +00002246 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002247 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002248 offset, length));
drhbfe66312006-10-03 17:40:40 +00002249 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2250 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002251 int rc;
2252 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002253 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2254 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002255#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2256 rc = SQLITE_BUSY;
2257#else
drh734c9862008-11-28 15:37:20 +00002258 rc = sqliteErrorFromPosixError(tErrno,
2259 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002260#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002261 if( IS_LOCK_ERROR(rc) ){
2262 pFile->lastErrno = tErrno;
2263 }
2264 return rc;
drhbfe66312006-10-03 17:40:40 +00002265 } else {
aswift5b1a2562008-08-22 00:22:35 +00002266 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002267 }
2268}
2269
drh6b9d6dd2008-12-03 19:34:47 +00002270/*
2271** This routine checks if there is a RESERVED lock held on the specified
2272** file by this or any other process. If such a lock is held, set *pResOut
2273** to a non-zero value otherwise *pResOut is set to zero. The return value
2274** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2275*/
danielk1977e339d652008-06-28 11:23:00 +00002276static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002277 int rc = SQLITE_OK;
2278 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002279 unixFile *pFile = (unixFile*)id;
2280
aswift5b1a2562008-08-22 00:22:35 +00002281 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2282
2283 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002284 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002285 if( context->reserved ){
2286 *pResOut = 1;
2287 return SQLITE_OK;
2288 }
drh8af6c222010-05-14 12:43:01 +00002289 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002290
2291 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002292 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002293 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002294 }
2295
2296 /* Otherwise see if some other process holds it.
2297 */
aswift5b1a2562008-08-22 00:22:35 +00002298 if( !reserved ){
2299 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002300 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002301 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002302 /* if we succeeded in taking the reserved lock, unlock it to restore
2303 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002304 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002305 } else {
2306 /* if we failed to get the lock then someone else must have it */
2307 reserved = 1;
2308 }
2309 if( IS_LOCK_ERROR(lrc) ){
2310 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002311 }
2312 }
drhbfe66312006-10-03 17:40:40 +00002313
drh7ed97b92010-01-20 13:07:21 +00002314 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002315 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002316
2317 *pResOut = reserved;
2318 return rc;
drhbfe66312006-10-03 17:40:40 +00002319}
2320
drh6b9d6dd2008-12-03 19:34:47 +00002321/*
drh308c2a52010-05-14 11:30:18 +00002322** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002323** of the following:
2324**
2325** (1) SHARED_LOCK
2326** (2) RESERVED_LOCK
2327** (3) PENDING_LOCK
2328** (4) EXCLUSIVE_LOCK
2329**
2330** Sometimes when requesting one lock state, additional lock states
2331** are inserted in between. The locking might fail on one of the later
2332** transitions leaving the lock state different from what it started but
2333** still short of its goal. The following chart shows the allowed
2334** transitions and the inserted intermediate states:
2335**
2336** UNLOCKED -> SHARED
2337** SHARED -> RESERVED
2338** SHARED -> (PENDING) -> EXCLUSIVE
2339** RESERVED -> (PENDING) -> EXCLUSIVE
2340** PENDING -> EXCLUSIVE
2341**
2342** This routine will only increase a lock. Use the sqlite3OsUnlock()
2343** routine to lower a locking level.
2344*/
drh308c2a52010-05-14 11:30:18 +00002345static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002346 int rc = SQLITE_OK;
2347 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002348 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002349 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002350
2351 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002352 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2353 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002354 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002355
drhbfe66312006-10-03 17:40:40 +00002356 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002357 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002358 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002359 */
drh308c2a52010-05-14 11:30:18 +00002360 if( pFile->eFileLock>=eFileLock ){
2361 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2362 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002363 return SQLITE_OK;
2364 }
2365
2366 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002367 ** (1) We never move from unlocked to anything higher than shared lock.
2368 ** (2) SQLite never explicitly requests a pendig lock.
2369 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002370 */
drh308c2a52010-05-14 11:30:18 +00002371 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2372 assert( eFileLock!=PENDING_LOCK );
2373 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002374
drh8af6c222010-05-14 12:43:01 +00002375 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002376 */
drh6c7d5c52008-11-21 20:32:33 +00002377 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002378 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002379
2380 /* If some thread using this PID has a lock via a different unixFile*
2381 ** handle that precludes the requested lock, return BUSY.
2382 */
drh8af6c222010-05-14 12:43:01 +00002383 if( (pFile->eFileLock!=pInode->eFileLock &&
2384 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002385 ){
2386 rc = SQLITE_BUSY;
2387 goto afp_end_lock;
2388 }
2389
2390 /* If a SHARED lock is requested, and some thread using this PID already
2391 ** has a SHARED or RESERVED lock, then increment reference counts and
2392 ** return SQLITE_OK.
2393 */
drh308c2a52010-05-14 11:30:18 +00002394 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002395 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002396 assert( eFileLock==SHARED_LOCK );
2397 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002398 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002399 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002400 pInode->nShared++;
2401 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002402 goto afp_end_lock;
2403 }
drhbfe66312006-10-03 17:40:40 +00002404
2405 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002406 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2407 ** be released.
2408 */
drh308c2a52010-05-14 11:30:18 +00002409 if( eFileLock==SHARED_LOCK
2410 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002411 ){
2412 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002413 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002414 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002415 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002416 goto afp_end_lock;
2417 }
2418 }
2419
2420 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002421 ** operating system calls for the specified lock.
2422 */
drh308c2a52010-05-14 11:30:18 +00002423 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002424 int lrc1, lrc2, lrc1Errno;
2425 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002426
drh8af6c222010-05-14 12:43:01 +00002427 assert( pInode->nShared==0 );
2428 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002429
2430 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002431 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002432 /* note that the quality of the randomness doesn't matter that much */
2433 lk = random();
drh8af6c222010-05-14 12:43:01 +00002434 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002435 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002436 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002437 if( IS_LOCK_ERROR(lrc1) ){
2438 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002439 }
aswift5b1a2562008-08-22 00:22:35 +00002440 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002441 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002442
aswift5b1a2562008-08-22 00:22:35 +00002443 if( IS_LOCK_ERROR(lrc1) ) {
2444 pFile->lastErrno = lrc1Errno;
2445 rc = lrc1;
2446 goto afp_end_lock;
2447 } else if( IS_LOCK_ERROR(lrc2) ){
2448 rc = lrc2;
2449 goto afp_end_lock;
2450 } else if( lrc1 != SQLITE_OK ) {
2451 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002452 } else {
drh308c2a52010-05-14 11:30:18 +00002453 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002454 pInode->nLock++;
2455 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002456 }
drh8af6c222010-05-14 12:43:01 +00002457 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002458 /* We are trying for an exclusive lock but another thread in this
2459 ** same process is still holding a shared lock. */
2460 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002461 }else{
2462 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2463 ** assumed that there is a SHARED or greater lock on the file
2464 ** already.
2465 */
2466 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002467 assert( 0!=pFile->eFileLock );
2468 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002469 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002470 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002471 if( !failed ){
2472 context->reserved = 1;
2473 }
drhbfe66312006-10-03 17:40:40 +00002474 }
drh308c2a52010-05-14 11:30:18 +00002475 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002476 /* Acquire an EXCLUSIVE lock */
2477
2478 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002479 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002480 */
drh6b9d6dd2008-12-03 19:34:47 +00002481 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002482 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002483 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002484 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002485 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002486 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002487 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002488 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002489 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2490 ** a critical I/O error
2491 */
2492 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2493 SQLITE_IOERR_LOCK;
2494 goto afp_end_lock;
2495 }
2496 }else{
aswift5b1a2562008-08-22 00:22:35 +00002497 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002498 }
2499 }
aswift5b1a2562008-08-22 00:22:35 +00002500 if( failed ){
2501 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002502 }
2503 }
2504
2505 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002506 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002507 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002508 }else if( eFileLock==EXCLUSIVE_LOCK ){
2509 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002510 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002511 }
2512
2513afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002514 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002515 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2516 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002517 return rc;
2518}
2519
2520/*
drh308c2a52010-05-14 11:30:18 +00002521** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002522** must be either NO_LOCK or SHARED_LOCK.
2523**
2524** If the locking level of the file descriptor is already at or below
2525** the requested locking level, this routine is a no-op.
2526*/
drh308c2a52010-05-14 11:30:18 +00002527static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002528 int rc = SQLITE_OK;
2529 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002530 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002531 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2532 int skipShared = 0;
2533#ifdef SQLITE_TEST
2534 int h = pFile->h;
2535#endif
drhbfe66312006-10-03 17:40:40 +00002536
2537 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002538 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002539 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002540 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002541
drh308c2a52010-05-14 11:30:18 +00002542 assert( eFileLock<=SHARED_LOCK );
2543 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002544 return SQLITE_OK;
2545 }
drh6c7d5c52008-11-21 20:32:33 +00002546 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002547 pInode = pFile->pInode;
2548 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002549 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002550 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002551 SimulateIOErrorBenign(1);
2552 SimulateIOError( h=(-1) )
2553 SimulateIOErrorBenign(0);
2554
2555#ifndef NDEBUG
2556 /* When reducing a lock such that other processes can start
2557 ** reading the database file again, make sure that the
2558 ** transaction counter was updated if any part of the database
2559 ** file changed. If the transaction counter is not updated,
2560 ** other connections to the same file might not realize that
2561 ** the file has changed and hence might not know to flush their
2562 ** cache. The use of a stale cache can lead to database corruption.
2563 */
2564 assert( pFile->inNormalWrite==0
2565 || pFile->dbUpdate==0
2566 || pFile->transCntrChng==1 );
2567 pFile->inNormalWrite = 0;
2568#endif
aswiftaebf4132008-11-21 00:10:35 +00002569
drh308c2a52010-05-14 11:30:18 +00002570 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002571 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002572 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002573 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002574 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002575 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2576 } else {
2577 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002578 }
2579 }
drh308c2a52010-05-14 11:30:18 +00002580 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002581 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002582 }
drh308c2a52010-05-14 11:30:18 +00002583 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002584 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2585 if( !rc ){
2586 context->reserved = 0;
2587 }
aswiftaebf4132008-11-21 00:10:35 +00002588 }
drh8af6c222010-05-14 12:43:01 +00002589 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2590 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002591 }
aswiftaebf4132008-11-21 00:10:35 +00002592 }
drh308c2a52010-05-14 11:30:18 +00002593 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002594
drh7ed97b92010-01-20 13:07:21 +00002595 /* Decrement the shared lock counter. Release the lock using an
2596 ** OS call only when all threads in this same process have released
2597 ** the lock.
2598 */
drh8af6c222010-05-14 12:43:01 +00002599 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2600 pInode->nShared--;
2601 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002602 SimulateIOErrorBenign(1);
2603 SimulateIOError( h=(-1) )
2604 SimulateIOErrorBenign(0);
2605 if( !skipShared ){
2606 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2607 }
2608 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002609 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002610 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002611 }
2612 }
2613 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002614 pInode->nLock--;
2615 assert( pInode->nLock>=0 );
2616 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002617 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002618 }
2619 }
drhbfe66312006-10-03 17:40:40 +00002620 }
drh7ed97b92010-01-20 13:07:21 +00002621
drh6c7d5c52008-11-21 20:32:33 +00002622 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002623 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002624 return rc;
2625}
2626
2627/*
drh339eb0b2008-03-07 15:34:11 +00002628** Close a file & cleanup AFP specific locking context
2629*/
danielk1977e339d652008-06-28 11:23:00 +00002630static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002631 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002632 if( id ){
2633 unixFile *pFile = (unixFile*)id;
2634 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002635 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002636 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002637 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002638 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002639 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002640 ** the last lock is cleared.
2641 */
dan08da86a2009-08-21 17:18:03 +00002642 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002643 }
danb0ac3e32010-06-16 10:55:42 +00002644 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002645 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002646 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002647 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002648 }
drh7ed97b92010-01-20 13:07:21 +00002649 return rc;
drhbfe66312006-10-03 17:40:40 +00002650}
2651
drhd2cb50b2009-01-09 21:41:17 +00002652#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002653/*
2654** The code above is the AFP lock implementation. The code is specific
2655** to MacOSX and does not work on other unix platforms. No alternative
2656** is available. If you don't compile for a mac, then the "unix-afp"
2657** VFS is not available.
2658**
2659********************* End of the AFP lock implementation **********************
2660******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002661
drh7ed97b92010-01-20 13:07:21 +00002662/******************************************************************************
2663*************************** Begin NFS Locking ********************************/
2664
2665#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2666/*
drh308c2a52010-05-14 11:30:18 +00002667 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002668 ** must be either NO_LOCK or SHARED_LOCK.
2669 **
2670 ** If the locking level of the file descriptor is already at or below
2671 ** the requested locking level, this routine is a no-op.
2672 */
drh308c2a52010-05-14 11:30:18 +00002673static int nfsUnlock(sqlite3_file *id, int eFileLock){
2674 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002675}
2676
2677#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2678/*
2679** The code above is the NFS lock implementation. The code is specific
2680** to MacOSX and does not work on other unix platforms. No alternative
2681** is available.
2682**
2683********************* End of the NFS lock implementation **********************
2684******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002685
2686/******************************************************************************
2687**************** Non-locking sqlite3_file methods *****************************
2688**
2689** The next division contains implementations for all methods of the
2690** sqlite3_file object other than the locking methods. The locking
2691** methods were defined in divisions above (one locking method per
2692** division). Those methods that are common to all locking modes
2693** are gather together into this division.
2694*/
drhbfe66312006-10-03 17:40:40 +00002695
2696/*
drh734c9862008-11-28 15:37:20 +00002697** Seek to the offset passed as the second argument, then read cnt
2698** bytes into pBuf. Return the number of bytes actually read.
2699**
2700** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2701** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2702** one system to another. Since SQLite does not define USE_PREAD
2703** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2704** See tickets #2741 and #2681.
2705**
2706** To avoid stomping the errno value on a failed read the lastErrno value
2707** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002708*/
drh734c9862008-11-28 15:37:20 +00002709static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2710 int got;
drh7ed97b92010-01-20 13:07:21 +00002711#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002712 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002713#endif
drh734c9862008-11-28 15:37:20 +00002714 TIMER_START;
2715#if defined(USE_PREAD)
drhff812312011-02-23 13:33:46 +00002716 do{ got = pread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002717 SimulateIOError( got = -1 );
2718#elif defined(USE_PREAD64)
drhff812312011-02-23 13:33:46 +00002719 do{ got = pread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002720 SimulateIOError( got = -1 );
2721#else
2722 newOffset = lseek(id->h, offset, SEEK_SET);
2723 SimulateIOError( newOffset-- );
2724 if( newOffset!=offset ){
2725 if( newOffset == -1 ){
2726 ((unixFile*)id)->lastErrno = errno;
2727 }else{
2728 ((unixFile*)id)->lastErrno = 0;
2729 }
2730 return -1;
2731 }
drhff812312011-02-23 13:33:46 +00002732 do{ got = read(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002733#endif
2734 TIMER_END;
2735 if( got<0 ){
2736 ((unixFile*)id)->lastErrno = errno;
2737 }
drh308c2a52010-05-14 11:30:18 +00002738 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002739 return got;
drhbfe66312006-10-03 17:40:40 +00002740}
2741
2742/*
drh734c9862008-11-28 15:37:20 +00002743** Read data from a file into a buffer. Return SQLITE_OK if all
2744** bytes were read successfully and SQLITE_IOERR if anything goes
2745** wrong.
drh339eb0b2008-03-07 15:34:11 +00002746*/
drh734c9862008-11-28 15:37:20 +00002747static int unixRead(
2748 sqlite3_file *id,
2749 void *pBuf,
2750 int amt,
2751 sqlite3_int64 offset
2752){
dan08da86a2009-08-21 17:18:03 +00002753 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002754 int got;
2755 assert( id );
drh08c6d442009-02-09 17:34:07 +00002756
dan08da86a2009-08-21 17:18:03 +00002757 /* If this is a database file (not a journal, master-journal or temp
2758 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002759#if 0
dane946c392009-08-22 11:39:46 +00002760 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002761 || offset>=PENDING_BYTE+512
2762 || offset+amt<=PENDING_BYTE
2763 );
dan7c246102010-04-12 19:00:29 +00002764#endif
drh08c6d442009-02-09 17:34:07 +00002765
dan08da86a2009-08-21 17:18:03 +00002766 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002767 if( got==amt ){
2768 return SQLITE_OK;
2769 }else if( got<0 ){
2770 /* lastErrno set by seekAndRead */
2771 return SQLITE_IOERR_READ;
2772 }else{
dan08da86a2009-08-21 17:18:03 +00002773 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002774 /* Unread parts of the buffer must be zero-filled */
2775 memset(&((char*)pBuf)[got], 0, amt-got);
2776 return SQLITE_IOERR_SHORT_READ;
2777 }
2778}
2779
2780/*
2781** Seek to the offset in id->offset then read cnt bytes into pBuf.
2782** Return the number of bytes actually read. Update the offset.
2783**
2784** To avoid stomping the errno value on a failed write the lastErrno value
2785** is set before returning.
2786*/
2787static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2788 int got;
drh7ed97b92010-01-20 13:07:21 +00002789#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002790 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002791#endif
drh734c9862008-11-28 15:37:20 +00002792 TIMER_START;
2793#if defined(USE_PREAD)
drhff812312011-02-23 13:33:46 +00002794 do{ got = pwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002795#elif defined(USE_PREAD64)
drhff812312011-02-23 13:33:46 +00002796 do{ got = pwrite64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002797#else
2798 newOffset = lseek(id->h, offset, SEEK_SET);
2799 if( newOffset!=offset ){
2800 if( newOffset == -1 ){
2801 ((unixFile*)id)->lastErrno = errno;
2802 }else{
2803 ((unixFile*)id)->lastErrno = 0;
2804 }
2805 return -1;
2806 }
drhff812312011-02-23 13:33:46 +00002807 do{ got = write(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002808#endif
2809 TIMER_END;
2810 if( got<0 ){
2811 ((unixFile*)id)->lastErrno = errno;
2812 }
2813
drh308c2a52010-05-14 11:30:18 +00002814 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002815 return got;
2816}
2817
2818
2819/*
2820** Write data from a buffer into a file. Return SQLITE_OK on success
2821** or some other error code on failure.
2822*/
2823static int unixWrite(
2824 sqlite3_file *id,
2825 const void *pBuf,
2826 int amt,
2827 sqlite3_int64 offset
2828){
dan08da86a2009-08-21 17:18:03 +00002829 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002830 int wrote = 0;
2831 assert( id );
2832 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002833
dan08da86a2009-08-21 17:18:03 +00002834 /* If this is a database file (not a journal, master-journal or temp
2835 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002836#if 0
dane946c392009-08-22 11:39:46 +00002837 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002838 || offset>=PENDING_BYTE+512
2839 || offset+amt<=PENDING_BYTE
2840 );
dan7c246102010-04-12 19:00:29 +00002841#endif
drh08c6d442009-02-09 17:34:07 +00002842
drh8f941bc2009-01-14 23:03:40 +00002843#ifndef NDEBUG
2844 /* If we are doing a normal write to a database file (as opposed to
2845 ** doing a hot-journal rollback or a write to some file other than a
2846 ** normal database file) then record the fact that the database
2847 ** has changed. If the transaction counter is modified, record that
2848 ** fact too.
2849 */
dan08da86a2009-08-21 17:18:03 +00002850 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002851 pFile->dbUpdate = 1; /* The database has been modified */
2852 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002853 int rc;
drh8f941bc2009-01-14 23:03:40 +00002854 char oldCntr[4];
2855 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002856 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002857 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002858 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002859 pFile->transCntrChng = 1; /* The transaction counter has changed */
2860 }
2861 }
2862 }
2863#endif
2864
dan08da86a2009-08-21 17:18:03 +00002865 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002866 amt -= wrote;
2867 offset += wrote;
2868 pBuf = &((char*)pBuf)[wrote];
2869 }
2870 SimulateIOError(( wrote=(-1), amt=1 ));
2871 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002872
drh734c9862008-11-28 15:37:20 +00002873 if( amt>0 ){
2874 if( wrote<0 ){
2875 /* lastErrno set by seekAndWrite */
2876 return SQLITE_IOERR_WRITE;
2877 }else{
dan08da86a2009-08-21 17:18:03 +00002878 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002879 return SQLITE_FULL;
2880 }
2881 }
dan6e09d692010-07-27 18:34:15 +00002882
drh734c9862008-11-28 15:37:20 +00002883 return SQLITE_OK;
2884}
2885
2886#ifdef SQLITE_TEST
2887/*
2888** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002889** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002890*/
2891int sqlite3_sync_count = 0;
2892int sqlite3_fullsync_count = 0;
2893#endif
2894
2895/*
drh89240432009-03-25 01:06:01 +00002896** We do not trust systems to provide a working fdatasync(). Some do.
2897** Others do no. To be safe, we will stick with the (slower) fsync().
2898** If you know that your system does support fdatasync() correctly,
2899** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002900*/
drh89240432009-03-25 01:06:01 +00002901#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002902# define fdatasync fsync
2903#endif
2904
2905/*
2906** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2907** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2908** only available on Mac OS X. But that could change.
2909*/
2910#ifdef F_FULLFSYNC
2911# define HAVE_FULLFSYNC 1
2912#else
2913# define HAVE_FULLFSYNC 0
2914#endif
2915
2916
2917/*
2918** The fsync() system call does not work as advertised on many
2919** unix systems. The following procedure is an attempt to make
2920** it work better.
2921**
2922** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2923** for testing when we want to run through the test suite quickly.
2924** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2925** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2926** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002927**
2928** SQLite sets the dataOnly flag if the size of the file is unchanged.
2929** The idea behind dataOnly is that it should only write the file content
2930** to disk, not the inode. We only set dataOnly if the file size is
2931** unchanged since the file size is part of the inode. However,
2932** Ted Ts'o tells us that fdatasync() will also write the inode if the
2933** file size has changed. The only real difference between fdatasync()
2934** and fsync(), Ted tells us, is that fdatasync() will not flush the
2935** inode if the mtime or owner or other inode attributes have changed.
2936** We only care about the file size, not the other file attributes, so
2937** as far as SQLite is concerned, an fdatasync() is always adequate.
2938** So, we always use fdatasync() if it is available, regardless of
2939** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002940*/
2941static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002942 int rc;
drh734c9862008-11-28 15:37:20 +00002943
2944 /* The following "ifdef/elif/else/" block has the same structure as
2945 ** the one below. It is replicated here solely to avoid cluttering
2946 ** up the real code with the UNUSED_PARAMETER() macros.
2947 */
2948#ifdef SQLITE_NO_SYNC
2949 UNUSED_PARAMETER(fd);
2950 UNUSED_PARAMETER(fullSync);
2951 UNUSED_PARAMETER(dataOnly);
2952#elif HAVE_FULLFSYNC
2953 UNUSED_PARAMETER(dataOnly);
2954#else
2955 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002956 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002957#endif
2958
2959 /* Record the number of times that we do a normal fsync() and
2960 ** FULLSYNC. This is used during testing to verify that this procedure
2961 ** gets called with the correct arguments.
2962 */
2963#ifdef SQLITE_TEST
2964 if( fullSync ) sqlite3_fullsync_count++;
2965 sqlite3_sync_count++;
2966#endif
2967
2968 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2969 ** no-op
2970 */
2971#ifdef SQLITE_NO_SYNC
2972 rc = SQLITE_OK;
2973#elif HAVE_FULLFSYNC
2974 if( fullSync ){
2975 rc = fcntl(fd, F_FULLFSYNC, 0);
2976 }else{
2977 rc = 1;
2978 }
2979 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002980 ** It shouldn't be possible for fullfsync to fail on the local
2981 ** file system (on OSX), so failure indicates that FULLFSYNC
2982 ** isn't supported for this file system. So, attempt an fsync
2983 ** and (for now) ignore the overhead of a superfluous fcntl call.
2984 ** It'd be better to detect fullfsync support once and avoid
2985 ** the fcntl call every time sync is called.
2986 */
drh734c9862008-11-28 15:37:20 +00002987 if( rc ) rc = fsync(fd);
2988
drh7ed97b92010-01-20 13:07:21 +00002989#elif defined(__APPLE__)
2990 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2991 ** so currently we default to the macro that redefines fdatasync to fsync
2992 */
2993 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002994#else
drh0b647ff2009-03-21 14:41:04 +00002995 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002996#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002997 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002998 rc = fsync(fd);
2999 }
drh0b647ff2009-03-21 14:41:04 +00003000#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003001#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3002
3003 if( OS_VXWORKS && rc!= -1 ){
3004 rc = 0;
3005 }
chw97185482008-11-17 08:05:31 +00003006 return rc;
drhbfe66312006-10-03 17:40:40 +00003007}
3008
drh734c9862008-11-28 15:37:20 +00003009/*
3010** Make sure all writes to a particular file are committed to disk.
3011**
3012** If dataOnly==0 then both the file itself and its metadata (file
3013** size, access time, etc) are synced. If dataOnly!=0 then only the
3014** file data is synced.
3015**
3016** Under Unix, also make sure that the directory entry for the file
3017** has been created by fsync-ing the directory that contains the file.
3018** If we do not do this and we encounter a power failure, the directory
3019** entry for the journal might not exist after we reboot. The next
3020** SQLite to access the file will not know that the journal exists (because
3021** the directory entry for the journal was never created) and the transaction
3022** will not roll back - possibly leading to database corruption.
3023*/
3024static int unixSync(sqlite3_file *id, int flags){
3025 int rc;
3026 unixFile *pFile = (unixFile*)id;
3027
3028 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3029 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3030
3031 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3032 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3033 || (flags&0x0F)==SQLITE_SYNC_FULL
3034 );
3035
3036 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3037 ** line is to test that doing so does not cause any problems.
3038 */
3039 SimulateDiskfullError( return SQLITE_FULL );
3040
3041 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003042 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003043 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3044 SimulateIOError( rc=1 );
3045 if( rc ){
3046 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003047 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003048 }
3049 if( pFile->dirfd>=0 ){
3050 int err;
drh308c2a52010-05-14 11:30:18 +00003051 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3052 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003053#ifndef SQLITE_DISABLE_DIRSYNC
3054 /* The directory sync is only attempted if full_fsync is
3055 ** turned off or unavailable. If a full_fsync occurred above,
3056 ** then the directory sync is superfluous.
3057 */
3058 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3059 /*
3060 ** We have received multiple reports of fsync() returning
3061 ** errors when applied to directories on certain file systems.
3062 ** A failed directory sync is not a big deal. So it seems
3063 ** better to ignore the error. Ticket #1657
3064 */
3065 /* pFile->lastErrno = errno; */
3066 /* return SQLITE_IOERR; */
3067 }
3068#endif
3069 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3070 if( err==0 ){ /* directory when we are done */
3071 pFile->dirfd = -1;
3072 }else{
3073 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003074 rc = unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003075 }
3076 }
3077 return rc;
3078}
3079
3080/*
3081** Truncate an open file to a specified size
3082*/
3083static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003084 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003085 int rc;
dan6e09d692010-07-27 18:34:15 +00003086 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003087 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003088
3089 /* If the user has configured a chunk-size for this file, truncate the
3090 ** file so that it consists of an integer number of chunks (i.e. the
3091 ** actual file size after the operation may be larger than the requested
3092 ** size).
3093 */
3094 if( pFile->szChunk ){
3095 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3096 }
3097
drhff812312011-02-23 13:33:46 +00003098 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003099 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003100 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003101 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003102 }else{
drh3313b142009-11-06 04:13:18 +00003103#ifndef NDEBUG
3104 /* If we are doing a normal write to a database file (as opposed to
3105 ** doing a hot-journal rollback or a write to some file other than a
3106 ** normal database file) and we truncate the file to zero length,
3107 ** that effectively updates the change counter. This might happen
3108 ** when restoring a database using the backup API from a zero-length
3109 ** source.
3110 */
dan6e09d692010-07-27 18:34:15 +00003111 if( pFile->inNormalWrite && nByte==0 ){
3112 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003113 }
3114#endif
3115
drh734c9862008-11-28 15:37:20 +00003116 return SQLITE_OK;
3117 }
3118}
3119
3120/*
3121** Determine the current size of a file in bytes
3122*/
3123static int unixFileSize(sqlite3_file *id, i64 *pSize){
3124 int rc;
3125 struct stat buf;
3126 assert( id );
3127 rc = fstat(((unixFile*)id)->h, &buf);
3128 SimulateIOError( rc=1 );
3129 if( rc!=0 ){
3130 ((unixFile*)id)->lastErrno = errno;
3131 return SQLITE_IOERR_FSTAT;
3132 }
3133 *pSize = buf.st_size;
3134
drh8af6c222010-05-14 12:43:01 +00003135 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003136 ** writes a single byte into that file in order to work around a bug
3137 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3138 ** layers, we need to report this file size as zero even though it is
3139 ** really 1. Ticket #3260.
3140 */
3141 if( *pSize==1 ) *pSize = 0;
3142
3143
3144 return SQLITE_OK;
3145}
3146
drhd2cb50b2009-01-09 21:41:17 +00003147#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003148/*
3149** Handler for proxy-locking file-control verbs. Defined below in the
3150** proxying locking division.
3151*/
3152static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003153#endif
drh715ff302008-12-03 22:32:44 +00003154
dan502019c2010-07-28 14:26:17 +00003155/*
3156** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3157** file-control operation.
3158**
3159** If the user has configured a chunk-size for this file, it could be
3160** that the file needs to be extended at this point. Otherwise, the
3161** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3162*/
3163static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3164 if( pFile->szChunk ){
3165 i64 nSize; /* Required file size */
3166 struct stat buf; /* Used to hold return values of fstat() */
3167
3168 if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
3169
3170 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3171 if( nSize>(i64)buf.st_size ){
3172#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003173 int rc;
3174 do{
3175 rc = posix_fallocate(pFile-.h, buf.st_size, nSize-buf.st_size;
3176 }while( rc<0 && errno=EINTR );
3177 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003178#else
3179 /* If the OS does not have posix_fallocate(), fake it. First use
3180 ** ftruncate() to set the file size, then write a single byte to
3181 ** the last byte in each block within the extended region. This
3182 ** is the same technique used by glibc to implement posix_fallocate()
3183 ** on systems that do not have a real fallocate() system call.
3184 */
3185 int nBlk = buf.st_blksize; /* File-system block size */
3186 i64 iWrite; /* Next offset to write to */
3187 int nWrite; /* Return value from seekAndWrite() */
3188
drhff812312011-02-23 13:33:46 +00003189 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003190 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003191 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003192 }
3193 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3194 do {
3195 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3196 iWrite += nBlk;
3197 } while( nWrite==1 && iWrite<nSize );
3198 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3199#endif
3200 }
3201 }
3202
3203 return SQLITE_OK;
3204}
danielk1977ad94b582007-08-20 06:44:22 +00003205
danielk1977e3026632004-06-22 11:29:02 +00003206/*
drh9e33c2c2007-08-31 18:34:59 +00003207** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003208*/
drhcc6bb3e2007-08-31 16:11:35 +00003209static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003210 switch( op ){
3211 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003212 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003213 return SQLITE_OK;
3214 }
drh7708e972008-11-29 00:56:52 +00003215 case SQLITE_LAST_ERRNO: {
3216 *(int*)pArg = ((unixFile*)id)->lastErrno;
3217 return SQLITE_OK;
3218 }
dan6e09d692010-07-27 18:34:15 +00003219 case SQLITE_FCNTL_CHUNK_SIZE: {
3220 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003221 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003222 }
drh9ff27ec2010-05-19 19:26:05 +00003223 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003224 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003225 }
drh8f941bc2009-01-14 23:03:40 +00003226#ifndef NDEBUG
3227 /* The pager calls this method to signal that it has done
3228 ** a rollback and that the database is therefore unchanged and
3229 ** it hence it is OK for the transaction change counter to be
3230 ** unchanged.
3231 */
3232 case SQLITE_FCNTL_DB_UNCHANGED: {
3233 ((unixFile*)id)->dbUpdate = 0;
3234 return SQLITE_OK;
3235 }
3236#endif
drhd2cb50b2009-01-09 21:41:17 +00003237#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003238 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003239 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003240 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003241 }
drhd2cb50b2009-01-09 21:41:17 +00003242#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003243 case SQLITE_FCNTL_SYNC_OMITTED: {
3244 return SQLITE_OK; /* A no-op */
3245 }
drh9e33c2c2007-08-31 18:34:59 +00003246 }
drh0b52b7d2011-01-26 19:46:22 +00003247 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003248}
3249
3250/*
danielk1977a3d4c882007-03-23 10:08:38 +00003251** Return the sector size in bytes of the underlying block device for
3252** the specified file. This is almost always 512 bytes, but may be
3253** larger for some devices.
3254**
3255** SQLite code assumes this function cannot fail. It also assumes that
3256** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003257** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003258** same for both.
3259*/
danielk1977397d65f2008-11-19 11:35:39 +00003260static int unixSectorSize(sqlite3_file *NotUsed){
3261 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003262 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003263}
3264
danielk197790949c22007-08-17 16:50:38 +00003265/*
danielk1977397d65f2008-11-19 11:35:39 +00003266** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003267*/
danielk1977397d65f2008-11-19 11:35:39 +00003268static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3269 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003270 return 0;
3271}
3272
drhd9e5c4f2010-05-12 18:01:39 +00003273#ifndef SQLITE_OMIT_WAL
3274
3275
3276/*
drhd91c68f2010-05-14 14:52:25 +00003277** Object used to represent an shared memory buffer.
3278**
3279** When multiple threads all reference the same wal-index, each thread
3280** has its own unixShm object, but they all point to a single instance
3281** of this unixShmNode object. In other words, each wal-index is opened
3282** only once per process.
3283**
3284** Each unixShmNode object is connected to a single unixInodeInfo object.
3285** We could coalesce this object into unixInodeInfo, but that would mean
3286** every open file that does not use shared memory (in other words, most
3287** open files) would have to carry around this extra information. So
3288** the unixInodeInfo object contains a pointer to this unixShmNode object
3289** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003290**
3291** unixMutexHeld() must be true when creating or destroying
3292** this object or while reading or writing the following fields:
3293**
3294** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003295**
3296** The following fields are read-only after the object is created:
3297**
3298** fid
3299** zFilename
3300**
drhd91c68f2010-05-14 14:52:25 +00003301** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003302** unixMutexHeld() is true when reading or writing any other field
3303** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003304*/
drhd91c68f2010-05-14 14:52:25 +00003305struct unixShmNode {
3306 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003307 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003308 char *zFilename; /* Name of the mmapped file */
3309 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003310 int szRegion; /* Size of shared-memory regions */
3311 int nRegion; /* Size of array apRegion */
3312 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003313 int nRef; /* Number of unixShm objects pointing to this */
3314 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003315#ifdef SQLITE_DEBUG
3316 u8 exclMask; /* Mask of exclusive locks held */
3317 u8 sharedMask; /* Mask of shared locks held */
3318 u8 nextShmId; /* Next available unixShm.id value */
3319#endif
3320};
3321
3322/*
drhd9e5c4f2010-05-12 18:01:39 +00003323** Structure used internally by this VFS to record the state of an
3324** open shared memory connection.
3325**
drhd91c68f2010-05-14 14:52:25 +00003326** The following fields are initialized when this object is created and
3327** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003328**
drhd91c68f2010-05-14 14:52:25 +00003329** unixShm.pFile
3330** unixShm.id
3331**
3332** All other fields are read/write. The unixShm.pFile->mutex must be held
3333** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003334*/
3335struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003336 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3337 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003338 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003339 u16 sharedMask; /* Mask of shared locks held */
3340 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003341#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003342 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003343#endif
3344};
3345
3346/*
drhd9e5c4f2010-05-12 18:01:39 +00003347** Constants used for locking
3348*/
drhbd9676c2010-06-23 17:58:38 +00003349#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003350#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003351
drhd9e5c4f2010-05-12 18:01:39 +00003352/*
drh73b64e42010-05-30 19:55:15 +00003353** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003354**
3355** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3356** otherwise.
3357*/
3358static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003359 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3360 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003361 int ofst, /* First byte of the locking range */
3362 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003363){
3364 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003365 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003366
drhd91c68f2010-05-14 14:52:25 +00003367 /* Access to the unixShmNode object is serialized by the caller */
3368 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003369
drh73b64e42010-05-30 19:55:15 +00003370 /* Shared locks never span more than one byte */
3371 assert( n==1 || lockType!=F_RDLCK );
3372
3373 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003374 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003375
drhd9e5c4f2010-05-12 18:01:39 +00003376 /* Initialize the locking parameters */
3377 memset(&f, 0, sizeof(f));
3378 f.l_type = lockType;
3379 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003380 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003381 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003382
drh73b64e42010-05-30 19:55:15 +00003383 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003384 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3385
3386 /* Update the global lock state and do debug tracing */
3387#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003388 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003389 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003390 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003391 if( rc==SQLITE_OK ){
3392 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003393 OSTRACE(("unlock %d ok", ofst));
3394 pShmNode->exclMask &= ~mask;
3395 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003396 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003397 OSTRACE(("read-lock %d ok", ofst));
3398 pShmNode->exclMask &= ~mask;
3399 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003400 }else{
3401 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003402 OSTRACE(("write-lock %d ok", ofst));
3403 pShmNode->exclMask |= mask;
3404 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003405 }
3406 }else{
3407 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003408 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003409 }else if( lockType==F_RDLCK ){
3410 OSTRACE(("read-lock failed"));
3411 }else{
3412 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003413 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003414 }
3415 }
drh20e1f082010-05-31 16:10:12 +00003416 OSTRACE((" - afterwards %03x,%03x\n",
3417 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003418 }
drhd9e5c4f2010-05-12 18:01:39 +00003419#endif
3420
3421 return rc;
3422}
3423
drhd9e5c4f2010-05-12 18:01:39 +00003424
3425/*
drhd91c68f2010-05-14 14:52:25 +00003426** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003427**
3428** This is not a VFS shared-memory method; it is a utility function called
3429** by VFS shared-memory methods.
3430*/
drhd91c68f2010-05-14 14:52:25 +00003431static void unixShmPurge(unixFile *pFd){
3432 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003433 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003434 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003435 int i;
drhd91c68f2010-05-14 14:52:25 +00003436 assert( p->pInode==pFd->pInode );
3437 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003438 for(i=0; i<p->nRegion; i++){
3439 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003440 }
dan18801912010-06-14 14:07:50 +00003441 sqlite3_free(p->apRegion);
drhd91c68f2010-05-14 14:52:25 +00003442 if( p->h>=0 ) close(p->h);
3443 p->pInode->pShmNode = 0;
3444 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003445 }
3446}
3447
3448/*
danda9fe0c2010-07-13 18:44:03 +00003449** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003450** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003451**
drh7234c6d2010-06-19 15:10:09 +00003452** The file used to implement shared-memory is in the same directory
3453** as the open database file and has the same name as the open database
3454** file with the "-shm" suffix added. For example, if the database file
3455** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003456** for shared memory will be called "/home/user1/config.db-shm".
3457**
3458** Another approach to is to use files in /dev/shm or /dev/tmp or an
3459** some other tmpfs mount. But if a file in a different directory
3460** from the database file is used, then differing access permissions
3461** or a chroot() might cause two different processes on the same
3462** database to end up using different files for shared memory -
3463** meaning that their memory would not really be shared - resulting
3464** in database corruption. Nevertheless, this tmpfs file usage
3465** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3466** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3467** option results in an incompatible build of SQLite; builds of SQLite
3468** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3469** same database file at the same time, database corruption will likely
3470** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3471** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003472**
3473** When opening a new shared-memory file, if no other instances of that
3474** file are currently open, in this process or in other processes, then
3475** the file must be truncated to zero length or have its header cleared.
3476*/
danda9fe0c2010-07-13 18:44:03 +00003477static int unixOpenSharedMemory(unixFile *pDbFd){
3478 struct unixShm *p = 0; /* The connection to be opened */
3479 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3480 int rc; /* Result code */
3481 unixInodeInfo *pInode; /* The inode of fd */
3482 char *zShmFilename; /* Name of the file used for SHM */
3483 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003484
danda9fe0c2010-07-13 18:44:03 +00003485 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003486 p = sqlite3_malloc( sizeof(*p) );
3487 if( p==0 ) return SQLITE_NOMEM;
3488 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003489 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003490
danda9fe0c2010-07-13 18:44:03 +00003491 /* Check to see if a unixShmNode object already exists. Reuse an existing
3492 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003493 */
3494 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003495 pInode = pDbFd->pInode;
3496 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003497 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003498 struct stat sStat; /* fstat() info for database file */
3499
3500 /* Call fstat() to figure out the permissions on the database file. If
3501 ** a new *-shm file is created, an attempt will be made to create it
3502 ** with the same permissions. The actual permissions the file is created
3503 ** with are subject to the current umask setting.
3504 */
3505 if( fstat(pDbFd->h, &sStat) ){
3506 rc = SQLITE_IOERR_FSTAT;
3507 goto shm_open_err;
3508 }
3509
drha4ced192010-07-15 18:32:40 +00003510#ifdef SQLITE_SHM_DIRECTORY
3511 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3512#else
drh7234c6d2010-06-19 15:10:09 +00003513 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003514#endif
drh7234c6d2010-06-19 15:10:09 +00003515 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003516 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003517 rc = SQLITE_NOMEM;
3518 goto shm_open_err;
3519 }
drhd91c68f2010-05-14 14:52:25 +00003520 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003521 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003522#ifdef SQLITE_SHM_DIRECTORY
3523 sqlite3_snprintf(nShmFilename, zShmFilename,
3524 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3525 (u32)sStat.st_ino, (u32)sStat.st_dev);
3526#else
drh7234c6d2010-06-19 15:10:09 +00003527 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003528#endif
drhd91c68f2010-05-14 14:52:25 +00003529 pShmNode->h = -1;
3530 pDbFd->pInode->pShmNode = pShmNode;
3531 pShmNode->pInode = pDbFd->pInode;
3532 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3533 if( pShmNode->mutex==0 ){
3534 rc = SQLITE_NOMEM;
3535 goto shm_open_err;
3536 }
drhd9e5c4f2010-05-12 18:01:39 +00003537
danddb0ac42010-07-14 14:48:58 +00003538 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003539 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003540 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003541 goto shm_open_err;
3542 }
3543
drhd9e5c4f2010-05-12 18:01:39 +00003544 /* Check to see if another process is holding the dead-man switch.
3545 ** If not, truncate the file to zero length.
3546 */
drhd91c68f2010-05-14 14:52:25 +00003547 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003548 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhff812312011-02-23 13:33:46 +00003549 if( robust_ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003550 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003551 }
3552 }
3553 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003554 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003555 }
3556 if( rc ) goto shm_open_err;
3557 }
3558
drhd91c68f2010-05-14 14:52:25 +00003559 /* Make the new connection a child of the unixShmNode */
3560 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003561#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003562 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003563#endif
drhd91c68f2010-05-14 14:52:25 +00003564 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003565 pDbFd->pShm = p;
3566 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003567
3568 /* The reference count on pShmNode has already been incremented under
3569 ** the cover of the unixEnterMutex() mutex and the pointer from the
3570 ** new (struct unixShm) object to the pShmNode has been set. All that is
3571 ** left to do is to link the new object into the linked list starting
3572 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3573 ** mutex.
3574 */
3575 sqlite3_mutex_enter(pShmNode->mutex);
3576 p->pNext = pShmNode->pFirst;
3577 pShmNode->pFirst = p;
3578 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003579 return SQLITE_OK;
3580
3581 /* Jump here on any error */
3582shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003583 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003584 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003585 unixLeaveMutex();
3586 return rc;
3587}
3588
3589/*
danda9fe0c2010-07-13 18:44:03 +00003590** This function is called to obtain a pointer to region iRegion of the
3591** shared-memory associated with the database file fd. Shared-memory regions
3592** are numbered starting from zero. Each shared-memory region is szRegion
3593** bytes in size.
3594**
3595** If an error occurs, an error code is returned and *pp is set to NULL.
3596**
3597** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3598** region has not been allocated (by any client, including one running in a
3599** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3600** bExtend is non-zero and the requested shared-memory region has not yet
3601** been allocated, it is allocated by this function.
3602**
3603** If the shared-memory region has already been allocated or is allocated by
3604** this call as described above, then it is mapped into this processes
3605** address space (if it is not already), *pp is set to point to the mapped
3606** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003607*/
danda9fe0c2010-07-13 18:44:03 +00003608static int unixShmMap(
3609 sqlite3_file *fd, /* Handle open on database file */
3610 int iRegion, /* Region to retrieve */
3611 int szRegion, /* Size of regions */
3612 int bExtend, /* True to extend file if necessary */
3613 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003614){
danda9fe0c2010-07-13 18:44:03 +00003615 unixFile *pDbFd = (unixFile*)fd;
3616 unixShm *p;
3617 unixShmNode *pShmNode;
3618 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003619
danda9fe0c2010-07-13 18:44:03 +00003620 /* If the shared-memory file has not yet been opened, open it now. */
3621 if( pDbFd->pShm==0 ){
3622 rc = unixOpenSharedMemory(pDbFd);
3623 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003624 }
drhd9e5c4f2010-05-12 18:01:39 +00003625
danda9fe0c2010-07-13 18:44:03 +00003626 p = pDbFd->pShm;
3627 pShmNode = p->pShmNode;
3628 sqlite3_mutex_enter(pShmNode->mutex);
3629 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3630
3631 if( pShmNode->nRegion<=iRegion ){
3632 char **apNew; /* New apRegion[] array */
3633 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3634 struct stat sStat; /* Used by fstat() */
3635
3636 pShmNode->szRegion = szRegion;
3637
3638 /* The requested region is not mapped into this processes address space.
3639 ** Check to see if it has been allocated (i.e. if the wal-index file is
3640 ** large enough to contain the requested region).
3641 */
3642 if( fstat(pShmNode->h, &sStat) ){
3643 rc = SQLITE_IOERR_SHMSIZE;
3644 goto shmpage_out;
3645 }
3646
3647 if( sStat.st_size<nByte ){
3648 /* The requested memory region does not exist. If bExtend is set to
3649 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3650 **
3651 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3652 ** the requested memory region.
3653 */
3654 if( !bExtend ) goto shmpage_out;
drhff812312011-02-23 13:33:46 +00003655 if( robust_ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003656 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003657 goto shmpage_out;
3658 }
3659 }
3660
3661 /* Map the requested memory region into this processes address space. */
3662 apNew = (char **)sqlite3_realloc(
3663 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3664 );
3665 if( !apNew ){
3666 rc = SQLITE_IOERR_NOMEM;
3667 goto shmpage_out;
3668 }
3669 pShmNode->apRegion = apNew;
3670 while(pShmNode->nRegion<=iRegion){
3671 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003672 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003673 );
3674 if( pMem==MAP_FAILED ){
3675 rc = SQLITE_IOERR;
3676 goto shmpage_out;
3677 }
3678 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3679 pShmNode->nRegion++;
3680 }
3681 }
3682
3683shmpage_out:
3684 if( pShmNode->nRegion>iRegion ){
3685 *pp = pShmNode->apRegion[iRegion];
3686 }else{
3687 *pp = 0;
3688 }
3689 sqlite3_mutex_leave(pShmNode->mutex);
3690 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003691}
3692
3693/*
drhd9e5c4f2010-05-12 18:01:39 +00003694** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003695**
3696** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3697** different here than in posix. In xShmLock(), one can go from unlocked
3698** to shared and back or from unlocked to exclusive and back. But one may
3699** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003700*/
3701static int unixShmLock(
3702 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003703 int ofst, /* First lock to acquire or release */
3704 int n, /* Number of locks to acquire or release */
3705 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003706){
drh73b64e42010-05-30 19:55:15 +00003707 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3708 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3709 unixShm *pX; /* For looping over all siblings */
3710 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3711 int rc = SQLITE_OK; /* Result code */
3712 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003713
drhd91c68f2010-05-14 14:52:25 +00003714 assert( pShmNode==pDbFd->pInode->pShmNode );
3715 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003716 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003717 assert( n>=1 );
3718 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3719 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3720 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3721 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3722 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003723
drhc99597c2010-05-31 01:41:15 +00003724 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003725 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003726 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003727 if( flags & SQLITE_SHM_UNLOCK ){
3728 u16 allMask = 0; /* Mask of locks held by siblings */
3729
3730 /* See if any siblings hold this same lock */
3731 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3732 if( pX==p ) continue;
3733 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3734 allMask |= pX->sharedMask;
3735 }
3736
3737 /* Unlock the system-level locks */
3738 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003739 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003740 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003741 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003742 }
drh73b64e42010-05-30 19:55:15 +00003743
3744 /* Undo the local locks */
3745 if( rc==SQLITE_OK ){
3746 p->exclMask &= ~mask;
3747 p->sharedMask &= ~mask;
3748 }
3749 }else if( flags & SQLITE_SHM_SHARED ){
3750 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3751
3752 /* Find out which shared locks are already held by sibling connections.
3753 ** If any sibling already holds an exclusive lock, go ahead and return
3754 ** SQLITE_BUSY.
3755 */
3756 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003757 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003758 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003759 break;
3760 }
3761 allShared |= pX->sharedMask;
3762 }
3763
3764 /* Get shared locks at the system level, if necessary */
3765 if( rc==SQLITE_OK ){
3766 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003767 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003768 }else{
drh73b64e42010-05-30 19:55:15 +00003769 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003770 }
drhd9e5c4f2010-05-12 18:01:39 +00003771 }
drh73b64e42010-05-30 19:55:15 +00003772
3773 /* Get the local shared locks */
3774 if( rc==SQLITE_OK ){
3775 p->sharedMask |= mask;
3776 }
3777 }else{
3778 /* Make sure no sibling connections hold locks that will block this
3779 ** lock. If any do, return SQLITE_BUSY right away.
3780 */
3781 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003782 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3783 rc = SQLITE_BUSY;
3784 break;
3785 }
3786 }
3787
3788 /* Get the exclusive locks at the system level. Then if successful
3789 ** also mark the local connection as being locked.
3790 */
3791 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003792 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003793 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003794 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003795 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003796 }
drhd9e5c4f2010-05-12 18:01:39 +00003797 }
3798 }
drhd91c68f2010-05-14 14:52:25 +00003799 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003800 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3801 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003802 return rc;
3803}
3804
drh286a2882010-05-20 23:51:06 +00003805/*
3806** Implement a memory barrier or memory fence on shared memory.
3807**
3808** All loads and stores begun before the barrier must complete before
3809** any load or store begun after the barrier.
3810*/
3811static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003812 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003813){
drhff828942010-06-26 21:34:06 +00003814 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003815 unixEnterMutex();
3816 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003817}
3818
dan18801912010-06-14 14:07:50 +00003819/*
danda9fe0c2010-07-13 18:44:03 +00003820** Close a connection to shared-memory. Delete the underlying
3821** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003822**
3823** If there is no shared memory associated with the connection then this
3824** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003825*/
danda9fe0c2010-07-13 18:44:03 +00003826static int unixShmUnmap(
3827 sqlite3_file *fd, /* The underlying database file */
3828 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003829){
danda9fe0c2010-07-13 18:44:03 +00003830 unixShm *p; /* The connection to be closed */
3831 unixShmNode *pShmNode; /* The underlying shared-memory file */
3832 unixShm **pp; /* For looping over sibling connections */
3833 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003834
danda9fe0c2010-07-13 18:44:03 +00003835 pDbFd = (unixFile*)fd;
3836 p = pDbFd->pShm;
3837 if( p==0 ) return SQLITE_OK;
3838 pShmNode = p->pShmNode;
3839
3840 assert( pShmNode==pDbFd->pInode->pShmNode );
3841 assert( pShmNode->pInode==pDbFd->pInode );
3842
3843 /* Remove connection p from the set of connections associated
3844 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003845 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003846 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3847 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003848
danda9fe0c2010-07-13 18:44:03 +00003849 /* Free the connection p */
3850 sqlite3_free(p);
3851 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003852 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003853
3854 /* If pShmNode->nRef has reached 0, then close the underlying
3855 ** shared-memory file, too */
3856 unixEnterMutex();
3857 assert( pShmNode->nRef>0 );
3858 pShmNode->nRef--;
3859 if( pShmNode->nRef==0 ){
3860 if( deleteFlag ) unlink(pShmNode->zFilename);
3861 unixShmPurge(pDbFd);
3862 }
3863 unixLeaveMutex();
3864
3865 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003866}
drh286a2882010-05-20 23:51:06 +00003867
danda9fe0c2010-07-13 18:44:03 +00003868
drhd9e5c4f2010-05-12 18:01:39 +00003869#else
drh6b017cc2010-06-14 18:01:46 +00003870# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003871# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003872# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003873# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003874#endif /* #ifndef SQLITE_OMIT_WAL */
3875
drh734c9862008-11-28 15:37:20 +00003876/*
3877** Here ends the implementation of all sqlite3_file methods.
3878**
3879********************** End sqlite3_file Methods *******************************
3880******************************************************************************/
3881
3882/*
drh6b9d6dd2008-12-03 19:34:47 +00003883** This division contains definitions of sqlite3_io_methods objects that
3884** implement various file locking strategies. It also contains definitions
3885** of "finder" functions. A finder-function is used to locate the appropriate
3886** sqlite3_io_methods object for a particular database file. The pAppData
3887** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3888** the correct finder-function for that VFS.
3889**
3890** Most finder functions return a pointer to a fixed sqlite3_io_methods
3891** object. The only interesting finder-function is autolockIoFinder, which
3892** looks at the filesystem type and tries to guess the best locking
3893** strategy from that.
3894**
drh1875f7a2008-12-08 18:19:17 +00003895** For finder-funtion F, two objects are created:
3896**
3897** (1) The real finder-function named "FImpt()".
3898**
dane946c392009-08-22 11:39:46 +00003899** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003900**
3901**
3902** A pointer to the F pointer is used as the pAppData value for VFS
3903** objects. We have to do this instead of letting pAppData point
3904** directly at the finder-function since C90 rules prevent a void*
3905** from be cast into a function pointer.
3906**
drh6b9d6dd2008-12-03 19:34:47 +00003907**
drh7708e972008-11-29 00:56:52 +00003908** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003909**
drh7708e972008-11-29 00:56:52 +00003910** * A constant sqlite3_io_methods object call METHOD that has locking
3911** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3912**
3913** * An I/O method finder function called FINDER that returns a pointer
3914** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003915*/
drhd9e5c4f2010-05-12 18:01:39 +00003916#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003917static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003918 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003919 CLOSE, /* xClose */ \
3920 unixRead, /* xRead */ \
3921 unixWrite, /* xWrite */ \
3922 unixTruncate, /* xTruncate */ \
3923 unixSync, /* xSync */ \
3924 unixFileSize, /* xFileSize */ \
3925 LOCK, /* xLock */ \
3926 UNLOCK, /* xUnlock */ \
3927 CKLOCK, /* xCheckReservedLock */ \
3928 unixFileControl, /* xFileControl */ \
3929 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003930 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003931 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00003932 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003933 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00003934 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00003935}; \
drh0c2694b2009-09-03 16:23:44 +00003936static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3937 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003938 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003939} \
drh0c2694b2009-09-03 16:23:44 +00003940static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003941 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003942
3943/*
3944** Here are all of the sqlite3_io_methods objects for each of the
3945** locking strategies. Functions that return pointers to these methods
3946** are also created.
3947*/
3948IOMETHODS(
3949 posixIoFinder, /* Finder function name */
3950 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003951 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00003952 unixClose, /* xClose method */
3953 unixLock, /* xLock method */
3954 unixUnlock, /* xUnlock method */
3955 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003956)
drh7708e972008-11-29 00:56:52 +00003957IOMETHODS(
3958 nolockIoFinder, /* Finder function name */
3959 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003960 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003961 nolockClose, /* xClose method */
3962 nolockLock, /* xLock method */
3963 nolockUnlock, /* xUnlock method */
3964 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003965)
drh7708e972008-11-29 00:56:52 +00003966IOMETHODS(
3967 dotlockIoFinder, /* Finder function name */
3968 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003969 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003970 dotlockClose, /* xClose method */
3971 dotlockLock, /* xLock method */
3972 dotlockUnlock, /* xUnlock method */
3973 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003974)
drh7708e972008-11-29 00:56:52 +00003975
chw78a13182009-04-07 05:35:03 +00003976#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003977IOMETHODS(
3978 flockIoFinder, /* Finder function name */
3979 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003980 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003981 flockClose, /* xClose method */
3982 flockLock, /* xLock method */
3983 flockUnlock, /* xUnlock method */
3984 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003985)
drh7708e972008-11-29 00:56:52 +00003986#endif
3987
drh6c7d5c52008-11-21 20:32:33 +00003988#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003989IOMETHODS(
3990 semIoFinder, /* Finder function name */
3991 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003992 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003993 semClose, /* xClose method */
3994 semLock, /* xLock method */
3995 semUnlock, /* xUnlock method */
3996 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003997)
aswiftaebf4132008-11-21 00:10:35 +00003998#endif
drh7708e972008-11-29 00:56:52 +00003999
drhd2cb50b2009-01-09 21:41:17 +00004000#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004001IOMETHODS(
4002 afpIoFinder, /* Finder function name */
4003 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004004 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004005 afpClose, /* xClose method */
4006 afpLock, /* xLock method */
4007 afpUnlock, /* xUnlock method */
4008 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004009)
drh715ff302008-12-03 22:32:44 +00004010#endif
4011
4012/*
4013** The proxy locking method is a "super-method" in the sense that it
4014** opens secondary file descriptors for the conch and lock files and
4015** it uses proxy, dot-file, AFP, and flock() locking methods on those
4016** secondary files. For this reason, the division that implements
4017** proxy locking is located much further down in the file. But we need
4018** to go ahead and define the sqlite3_io_methods and finder function
4019** for proxy locking here. So we forward declare the I/O methods.
4020*/
drhd2cb50b2009-01-09 21:41:17 +00004021#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004022static int proxyClose(sqlite3_file*);
4023static int proxyLock(sqlite3_file*, int);
4024static int proxyUnlock(sqlite3_file*, int);
4025static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004026IOMETHODS(
4027 proxyIoFinder, /* Finder function name */
4028 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004029 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004030 proxyClose, /* xClose method */
4031 proxyLock, /* xLock method */
4032 proxyUnlock, /* xUnlock method */
4033 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004034)
aswiftaebf4132008-11-21 00:10:35 +00004035#endif
drh7708e972008-11-29 00:56:52 +00004036
drh7ed97b92010-01-20 13:07:21 +00004037/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4038#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4039IOMETHODS(
4040 nfsIoFinder, /* Finder function name */
4041 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004042 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004043 unixClose, /* xClose method */
4044 unixLock, /* xLock method */
4045 nfsUnlock, /* xUnlock method */
4046 unixCheckReservedLock /* xCheckReservedLock method */
4047)
4048#endif
drh7708e972008-11-29 00:56:52 +00004049
drhd2cb50b2009-01-09 21:41:17 +00004050#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004051/*
drh6b9d6dd2008-12-03 19:34:47 +00004052** This "finder" function attempts to determine the best locking strategy
4053** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004054** object that implements that strategy.
4055**
4056** This is for MacOSX only.
4057*/
drh1875f7a2008-12-08 18:19:17 +00004058static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004059 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004060 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004061){
4062 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004063 const char *zFilesystem; /* Filesystem type name */
4064 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004065 } aMap[] = {
4066 { "hfs", &posixIoMethods },
4067 { "ufs", &posixIoMethods },
4068 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004069 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004070 { "webdav", &nolockIoMethods },
4071 { 0, 0 }
4072 };
4073 int i;
4074 struct statfs fsInfo;
4075 struct flock lockInfo;
4076
4077 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004078 /* If filePath==NULL that means we are dealing with a transient file
4079 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004080 return &nolockIoMethods;
4081 }
4082 if( statfs(filePath, &fsInfo) != -1 ){
4083 if( fsInfo.f_flags & MNT_RDONLY ){
4084 return &nolockIoMethods;
4085 }
4086 for(i=0; aMap[i].zFilesystem; i++){
4087 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4088 return aMap[i].pMethods;
4089 }
4090 }
4091 }
4092
4093 /* Default case. Handles, amongst others, "nfs".
4094 ** Test byte-range lock using fcntl(). If the call succeeds,
4095 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004096 */
drh7708e972008-11-29 00:56:52 +00004097 lockInfo.l_len = 1;
4098 lockInfo.l_start = 0;
4099 lockInfo.l_whence = SEEK_SET;
4100 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004101 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004102 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4103 return &nfsIoMethods;
4104 } else {
4105 return &posixIoMethods;
4106 }
drh7708e972008-11-29 00:56:52 +00004107 }else{
4108 return &dotlockIoMethods;
4109 }
4110}
drh0c2694b2009-09-03 16:23:44 +00004111static const sqlite3_io_methods
4112 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004113
drhd2cb50b2009-01-09 21:41:17 +00004114#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004115
chw78a13182009-04-07 05:35:03 +00004116#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4117/*
4118** This "finder" function attempts to determine the best locking strategy
4119** for the database file "filePath". It then returns the sqlite3_io_methods
4120** object that implements that strategy.
4121**
4122** This is for VXWorks only.
4123*/
4124static const sqlite3_io_methods *autolockIoFinderImpl(
4125 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004126 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004127){
4128 struct flock lockInfo;
4129
4130 if( !filePath ){
4131 /* If filePath==NULL that means we are dealing with a transient file
4132 ** that does not need to be locked. */
4133 return &nolockIoMethods;
4134 }
4135
4136 /* Test if fcntl() is supported and use POSIX style locks.
4137 ** Otherwise fall back to the named semaphore method.
4138 */
4139 lockInfo.l_len = 1;
4140 lockInfo.l_start = 0;
4141 lockInfo.l_whence = SEEK_SET;
4142 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004143 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004144 return &posixIoMethods;
4145 }else{
4146 return &semIoMethods;
4147 }
4148}
drh0c2694b2009-09-03 16:23:44 +00004149static const sqlite3_io_methods
4150 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004151
4152#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4153
drh7708e972008-11-29 00:56:52 +00004154/*
4155** An abstract type for a pointer to a IO method finder function:
4156*/
drh0c2694b2009-09-03 16:23:44 +00004157typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004158
aswiftaebf4132008-11-21 00:10:35 +00004159
drh734c9862008-11-28 15:37:20 +00004160/****************************************************************************
4161**************************** sqlite3_vfs methods ****************************
4162**
4163** This division contains the implementation of methods on the
4164** sqlite3_vfs object.
4165*/
4166
danielk1977a3d4c882007-03-23 10:08:38 +00004167/*
danielk1977e339d652008-06-28 11:23:00 +00004168** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004169*/
4170static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004171 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004172 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004173 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004174 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004175 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004176 int noLock, /* Omit locking if true */
4177 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004178){
drh7708e972008-11-29 00:56:52 +00004179 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004180 unixFile *pNew = (unixFile *)pId;
4181 int rc = SQLITE_OK;
4182
drh8af6c222010-05-14 12:43:01 +00004183 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004184
dane946c392009-08-22 11:39:46 +00004185 /* Parameter isDelete is only used on vxworks. Express this explicitly
4186 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004187 */
drh7708e972008-11-29 00:56:52 +00004188 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004189
dan00157392010-10-05 11:33:15 +00004190 /* Usually the path zFilename should not be a relative pathname. The
4191 ** exception is when opening the proxy "conch" file in builds that
4192 ** include the special Apple locking styles.
4193 */
dan00157392010-10-05 11:33:15 +00004194#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004195 assert( zFilename==0 || zFilename[0]=='/'
4196 || pVfs->pAppData==(void*)&autolockIoFinder );
4197#else
4198 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004199#endif
dan00157392010-10-05 11:33:15 +00004200
drh308c2a52010-05-14 11:30:18 +00004201 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004202 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004203 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004204 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004205 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004206
drh6c7d5c52008-11-21 20:32:33 +00004207#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004208 pNew->pId = vxworksFindFileId(zFilename);
4209 if( pNew->pId==0 ){
4210 noLock = 1;
4211 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004212 }
4213#endif
4214
drhda0e7682008-07-30 15:27:54 +00004215 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004216 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004217 }else{
drh0c2694b2009-09-03 16:23:44 +00004218 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004219#if SQLITE_ENABLE_LOCKING_STYLE
4220 /* Cache zFilename in the locking context (AFP and dotlock override) for
4221 ** proxyLock activation is possible (remote proxy is based on db name)
4222 ** zFilename remains valid until file is closed, to support */
4223 pNew->lockingContext = (void*)zFilename;
4224#endif
drhda0e7682008-07-30 15:27:54 +00004225 }
danielk1977e339d652008-06-28 11:23:00 +00004226
drh7ed97b92010-01-20 13:07:21 +00004227 if( pLockingStyle == &posixIoMethods
4228#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4229 || pLockingStyle == &nfsIoMethods
4230#endif
4231 ){
drh7708e972008-11-29 00:56:52 +00004232 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004233 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004234 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004235 /* If an error occured in findInodeInfo(), close the file descriptor
4236 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004237 ** in two scenarios:
4238 **
4239 ** (a) A call to fstat() failed.
4240 ** (b) A malloc failed.
4241 **
4242 ** Scenario (b) may only occur if the process is holding no other
4243 ** file descriptors open on the same file. If there were other file
4244 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004245 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004246 ** handle h - as it is guaranteed that no posix locks will be released
4247 ** by doing so.
4248 **
4249 ** If scenario (a) caused the error then things are not so safe. The
4250 ** implicit assumption here is that if fstat() fails, things are in
4251 ** such bad shape that dropping a lock or two doesn't matter much.
4252 */
4253 close(h);
4254 h = -1;
4255 }
drh7708e972008-11-29 00:56:52 +00004256 unixLeaveMutex();
4257 }
danielk1977e339d652008-06-28 11:23:00 +00004258
drhd2cb50b2009-01-09 21:41:17 +00004259#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004260 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004261 /* AFP locking uses the file path so it needs to be included in
4262 ** the afpLockingContext.
4263 */
4264 afpLockingContext *pCtx;
4265 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4266 if( pCtx==0 ){
4267 rc = SQLITE_NOMEM;
4268 }else{
4269 /* NB: zFilename exists and remains valid until the file is closed
4270 ** according to requirement F11141. So we do not need to make a
4271 ** copy of the filename. */
4272 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004273 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004274 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004275 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004276 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004277 if( rc!=SQLITE_OK ){
4278 sqlite3_free(pNew->lockingContext);
4279 close(h);
4280 h = -1;
4281 }
drh7708e972008-11-29 00:56:52 +00004282 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004283 }
drh7708e972008-11-29 00:56:52 +00004284 }
4285#endif
danielk1977e339d652008-06-28 11:23:00 +00004286
drh7708e972008-11-29 00:56:52 +00004287 else if( pLockingStyle == &dotlockIoMethods ){
4288 /* Dotfile locking uses the file path so it needs to be included in
4289 ** the dotlockLockingContext
4290 */
4291 char *zLockFile;
4292 int nFilename;
drhea678832008-12-10 19:26:22 +00004293 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004294 zLockFile = (char *)sqlite3_malloc(nFilename);
4295 if( zLockFile==0 ){
4296 rc = SQLITE_NOMEM;
4297 }else{
4298 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004299 }
drh7708e972008-11-29 00:56:52 +00004300 pNew->lockingContext = zLockFile;
4301 }
danielk1977e339d652008-06-28 11:23:00 +00004302
drh6c7d5c52008-11-21 20:32:33 +00004303#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004304 else if( pLockingStyle == &semIoMethods ){
4305 /* Named semaphore locking uses the file path so it needs to be
4306 ** included in the semLockingContext
4307 */
4308 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004309 rc = findInodeInfo(pNew, &pNew->pInode);
4310 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4311 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004312 int n;
drh2238dcc2009-08-27 17:56:20 +00004313 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004314 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004315 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004316 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004317 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4318 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004319 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004320 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004321 }
chw97185482008-11-17 08:05:31 +00004322 }
drh7708e972008-11-29 00:56:52 +00004323 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004324 }
drh7708e972008-11-29 00:56:52 +00004325#endif
aswift5b1a2562008-08-22 00:22:35 +00004326
4327 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004328#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004329 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004330 if( h>=0 ) close(h);
4331 h = -1;
chw97185482008-11-17 08:05:31 +00004332 unlink(zFilename);
4333 isDelete = 0;
4334 }
4335 pNew->isDelete = isDelete;
4336#endif
danielk1977e339d652008-06-28 11:23:00 +00004337 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004338 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004339 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004340 }else{
drh7708e972008-11-29 00:56:52 +00004341 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004342 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004343 }
danielk1977e339d652008-06-28 11:23:00 +00004344 return rc;
drh054889e2005-11-30 03:20:31 +00004345}
drh9c06c952005-11-26 00:25:00 +00004346
danielk1977ad94b582007-08-20 06:44:22 +00004347/*
4348** Open a file descriptor to the directory containing file zFilename.
4349** If successful, *pFd is set to the opened file descriptor and
4350** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4351** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4352** value.
4353**
4354** If SQLITE_OK is returned, the caller is responsible for closing
4355** the file descriptor *pFd using close().
4356*/
danielk1977fee2d252007-08-18 10:59:19 +00004357static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004358 int ii;
drh777b17a2007-09-20 10:02:54 +00004359 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004360 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004361
drh153c62c2007-08-24 03:51:33 +00004362 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004363 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004364 if( ii>0 ){
4365 zDirname[ii] = '\0';
4366 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004367 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004368#ifdef FD_CLOEXEC
4369 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4370#endif
drh308c2a52010-05-14 11:30:18 +00004371 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004372 }
4373 }
danielk1977fee2d252007-08-18 10:59:19 +00004374 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004375 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004376}
4377
danielk1977b4b47412007-08-17 15:53:36 +00004378/*
drh8b3cf822010-06-01 21:02:51 +00004379** Return the name of a directory in which to put temporary files.
4380** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004381*/
drh7234c6d2010-06-19 15:10:09 +00004382static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004383 static const char *azDirs[] = {
4384 0,
aswiftaebf4132008-11-21 00:10:35 +00004385 0,
danielk197717b90b52008-06-06 11:11:25 +00004386 "/var/tmp",
4387 "/usr/tmp",
4388 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004389 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004390 };
drh8b3cf822010-06-01 21:02:51 +00004391 unsigned int i;
4392 struct stat buf;
4393 const char *zDir = 0;
4394
4395 azDirs[0] = sqlite3_temp_directory;
4396 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004397 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004398 if( zDir==0 ) continue;
4399 if( stat(zDir, &buf) ) continue;
4400 if( !S_ISDIR(buf.st_mode) ) continue;
drh7234c6d2010-06-19 15:10:09 +00004401 if( access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004402 break;
4403 }
4404 return zDir;
4405}
4406
4407/*
4408** Create a temporary file name in zBuf. zBuf must be allocated
4409** by the calling process and must be big enough to hold at least
4410** pVfs->mxPathname bytes.
4411*/
4412static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004413 static const unsigned char zChars[] =
4414 "abcdefghijklmnopqrstuvwxyz"
4415 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4416 "0123456789";
drh41022642008-11-21 00:24:42 +00004417 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004418 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004419
4420 /* It's odd to simulate an io-error here, but really this is just
4421 ** using the io-error infrastructure to test that SQLite handles this
4422 ** function failing.
4423 */
4424 SimulateIOError( return SQLITE_IOERR );
4425
drh7234c6d2010-06-19 15:10:09 +00004426 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004427 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004428
4429 /* Check that the output buffer is large enough for the temporary file
4430 ** name. If it is not, return SQLITE_ERROR.
4431 */
danielk197700e13612008-11-17 19:18:54 +00004432 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004433 return SQLITE_ERROR;
4434 }
4435
4436 do{
4437 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004438 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004439 sqlite3_randomness(15, &zBuf[j]);
4440 for(i=0; i<15; i++, j++){
4441 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4442 }
4443 zBuf[j] = 0;
4444 }while( access(zBuf,0)==0 );
4445 return SQLITE_OK;
4446}
4447
drhd2cb50b2009-01-09 21:41:17 +00004448#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004449/*
4450** Routine to transform a unixFile into a proxy-locking unixFile.
4451** Implementation in the proxy-lock division, but used by unixOpen()
4452** if SQLITE_PREFER_PROXY_LOCKING is defined.
4453*/
4454static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004455#endif
drhc66d5b62008-12-03 22:48:32 +00004456
dan08da86a2009-08-21 17:18:03 +00004457/*
4458** Search for an unused file descriptor that was opened on the database
4459** file (not a journal or master-journal file) identified by pathname
4460** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4461** argument to this function.
4462**
4463** Such a file descriptor may exist if a database connection was closed
4464** but the associated file descriptor could not be closed because some
4465** other file descriptor open on the same file is holding a file-lock.
4466** Refer to comments in the unixClose() function and the lengthy comment
4467** describing "Posix Advisory Locking" at the start of this file for
4468** further details. Also, ticket #4018.
4469**
4470** If a suitable file descriptor is found, then it is returned. If no
4471** such file descriptor is located, -1 is returned.
4472*/
dane946c392009-08-22 11:39:46 +00004473static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4474 UnixUnusedFd *pUnused = 0;
4475
4476 /* Do not search for an unused file descriptor on vxworks. Not because
4477 ** vxworks would not benefit from the change (it might, we're not sure),
4478 ** but because no way to test it is currently available. It is better
4479 ** not to risk breaking vxworks support for the sake of such an obscure
4480 ** feature. */
4481#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004482 struct stat sStat; /* Results of stat() call */
4483
4484 /* A stat() call may fail for various reasons. If this happens, it is
4485 ** almost certain that an open() call on the same path will also fail.
4486 ** For this reason, if an error occurs in the stat() call here, it is
4487 ** ignored and -1 is returned. The caller will try to open a new file
4488 ** descriptor on the same path, fail, and return an error to SQLite.
4489 **
4490 ** Even if a subsequent open() call does succeed, the consequences of
4491 ** not searching for a resusable file descriptor are not dire. */
4492 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004493 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004494
4495 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004496 pInode = inodeList;
4497 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4498 || pInode->fileId.ino!=sStat.st_ino) ){
4499 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004500 }
drh8af6c222010-05-14 12:43:01 +00004501 if( pInode ){
dane946c392009-08-22 11:39:46 +00004502 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004503 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004504 pUnused = *pp;
4505 if( pUnused ){
4506 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004507 }
4508 }
4509 unixLeaveMutex();
4510 }
dane946c392009-08-22 11:39:46 +00004511#endif /* if !OS_VXWORKS */
4512 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004513}
danielk197717b90b52008-06-06 11:11:25 +00004514
4515/*
danddb0ac42010-07-14 14:48:58 +00004516** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004517** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004518** and a value suitable for passing as the third argument to open(2) is
4519** written to *pMode. If an IO error occurs, an SQLite error code is
4520** returned and the value of *pMode is not modified.
4521**
4522** If the file being opened is a temporary file, it is always created with
4523** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004524** is a database or master journal file, it is created with the permissions
4525** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004526**
drh8ab58662010-07-15 18:38:39 +00004527** Finally, if the file being opened is a WAL or regular journal file, then
4528** this function queries the file-system for the permissions on the
4529** corresponding database file and sets *pMode to this value. Whenever
4530** possible, WAL and journal files are created using the same permissions
4531** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004532*/
4533static int findCreateFileMode(
4534 const char *zPath, /* Path of file (possibly) being created */
4535 int flags, /* Flags passed as 4th argument to xOpen() */
4536 mode_t *pMode /* OUT: Permissions to open file with */
4537){
4538 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004539 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004540 char zDb[MAX_PATHNAME+1]; /* Database file path */
4541 int nDb; /* Number of valid bytes in zDb */
4542 struct stat sStat; /* Output of stat() on database file */
4543
dana0c989d2010-11-05 18:07:37 +00004544 /* zPath is a path to a WAL or journal file. The following block derives
4545 ** the path to the associated database file from zPath. This block handles
4546 ** the following naming conventions:
4547 **
4548 ** "<path to db>-journal"
4549 ** "<path to db>-wal"
4550 ** "<path to db>-journal-NNNN"
4551 ** "<path to db>-wal-NNNN"
4552 **
4553 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4554 ** used by the test_multiplex.c module.
4555 */
4556 nDb = sqlite3Strlen30(zPath) - 1;
4557 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4558 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004559 memcpy(zDb, zPath, nDb);
4560 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004561
danddb0ac42010-07-14 14:48:58 +00004562 if( 0==stat(zDb, &sStat) ){
4563 *pMode = sStat.st_mode & 0777;
4564 }else{
4565 rc = SQLITE_IOERR_FSTAT;
4566 }
4567 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4568 *pMode = 0600;
4569 }else{
4570 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4571 }
4572 return rc;
4573}
4574
4575/*
danielk1977ad94b582007-08-20 06:44:22 +00004576** Open the file zPath.
4577**
danielk1977b4b47412007-08-17 15:53:36 +00004578** Previously, the SQLite OS layer used three functions in place of this
4579** one:
4580**
4581** sqlite3OsOpenReadWrite();
4582** sqlite3OsOpenReadOnly();
4583** sqlite3OsOpenExclusive();
4584**
4585** These calls correspond to the following combinations of flags:
4586**
4587** ReadWrite() -> (READWRITE | CREATE)
4588** ReadOnly() -> (READONLY)
4589** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4590**
4591** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4592** true, the file was configured to be automatically deleted when the
4593** file handle closed. To achieve the same effect using this new
4594** interface, add the DELETEONCLOSE flag to those specified above for
4595** OpenExclusive().
4596*/
4597static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004598 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4599 const char *zPath, /* Pathname of file to be opened */
4600 sqlite3_file *pFile, /* The file descriptor to be filled in */
4601 int flags, /* Input flags to control the opening */
4602 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004603){
dan08da86a2009-08-21 17:18:03 +00004604 unixFile *p = (unixFile *)pFile;
4605 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004606 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004607 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004608 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004609 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004610 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004611
4612 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4613 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4614 int isCreate = (flags & SQLITE_OPEN_CREATE);
4615 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4616 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004617#if SQLITE_ENABLE_LOCKING_STYLE
4618 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4619#endif
danielk1977b4b47412007-08-17 15:53:36 +00004620
danielk1977fee2d252007-08-18 10:59:19 +00004621 /* If creating a master or main-file journal, this function will open
4622 ** a file-descriptor on the directory too. The first time unixSync()
4623 ** is called the directory file descriptor will be fsync()ed and close()d.
4624 */
danddb0ac42010-07-14 14:48:58 +00004625 int isOpenDirectory = (isCreate && (
4626 eType==SQLITE_OPEN_MASTER_JOURNAL
4627 || eType==SQLITE_OPEN_MAIN_JOURNAL
4628 || eType==SQLITE_OPEN_WAL
4629 ));
danielk1977fee2d252007-08-18 10:59:19 +00004630
danielk197717b90b52008-06-06 11:11:25 +00004631 /* If argument zPath is a NULL pointer, this function is required to open
4632 ** a temporary file. Use this buffer to store the file name in.
4633 */
4634 char zTmpname[MAX_PATHNAME+1];
4635 const char *zName = zPath;
4636
danielk1977fee2d252007-08-18 10:59:19 +00004637 /* Check the following statements are true:
4638 **
4639 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4640 ** (b) if CREATE is set, then READWRITE must also be set, and
4641 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004642 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004643 */
danielk1977b4b47412007-08-17 15:53:36 +00004644 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004645 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004646 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004647 assert(isDelete==0 || isCreate);
4648
danddb0ac42010-07-14 14:48:58 +00004649 /* The main DB, main journal, WAL file and master journal are never
4650 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004651 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4652 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4653 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004654 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004655
danielk1977fee2d252007-08-18 10:59:19 +00004656 /* Assert that the upper layer has set one of the "file-type" flags. */
4657 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4658 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4659 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004660 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004661 );
4662
dan08da86a2009-08-21 17:18:03 +00004663 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004664
dan08da86a2009-08-21 17:18:03 +00004665 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004666 UnixUnusedFd *pUnused;
4667 pUnused = findReusableFd(zName, flags);
4668 if( pUnused ){
4669 fd = pUnused->fd;
4670 }else{
dan6aa657f2009-08-24 18:57:58 +00004671 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004672 if( !pUnused ){
4673 return SQLITE_NOMEM;
4674 }
4675 }
4676 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004677 }else if( !zName ){
4678 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004679 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004680 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004681 if( rc!=SQLITE_OK ){
4682 return rc;
4683 }
4684 zName = zTmpname;
4685 }
4686
dan08da86a2009-08-21 17:18:03 +00004687 /* Determine the value of the flags parameter passed to POSIX function
4688 ** open(). These must be calculated even if open() is not called, as
4689 ** they may be stored as part of the file handle and used by the
4690 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004691 if( isReadonly ) openFlags |= O_RDONLY;
4692 if( isReadWrite ) openFlags |= O_RDWR;
4693 if( isCreate ) openFlags |= O_CREAT;
4694 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4695 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004696
danielk1977b4b47412007-08-17 15:53:36 +00004697 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004698 mode_t openMode; /* Permissions to create file with */
4699 rc = findCreateFileMode(zName, flags, &openMode);
4700 if( rc!=SQLITE_OK ){
4701 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004702 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004703 return rc;
4704 }
dane946c392009-08-22 11:39:46 +00004705 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004706 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004707 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4708 /* Failed to open the file for read/write access. Try read-only. */
4709 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004710 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004711 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004712 openFlags |= O_RDONLY;
4713 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004714 }
4715 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004716 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004717 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004718 }
danielk1977b4b47412007-08-17 15:53:36 +00004719 }
dan08da86a2009-08-21 17:18:03 +00004720 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004721 if( pOutFlags ){
4722 *pOutFlags = flags;
4723 }
4724
dane946c392009-08-22 11:39:46 +00004725 if( p->pUnused ){
4726 p->pUnused->fd = fd;
4727 p->pUnused->flags = flags;
4728 }
4729
danielk1977b4b47412007-08-17 15:53:36 +00004730 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004731#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004732 zPath = zName;
4733#else
danielk197717b90b52008-06-06 11:11:25 +00004734 unlink(zName);
chw97185482008-11-17 08:05:31 +00004735#endif
danielk1977b4b47412007-08-17 15:53:36 +00004736 }
drh41022642008-11-21 00:24:42 +00004737#if SQLITE_ENABLE_LOCKING_STYLE
4738 else{
dan08da86a2009-08-21 17:18:03 +00004739 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004740 }
4741#endif
4742
danielk1977fee2d252007-08-18 10:59:19 +00004743 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004744 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004745 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004746 /* It is safe to close fd at this point, because it is guaranteed not
4747 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004748 ** it would not be safe to close as this would release any locks held
4749 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004750 assert( eType!=SQLITE_OPEN_MAIN_DB );
4751 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004752 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004753 }
4754 }
danielk1977e339d652008-06-28 11:23:00 +00004755
4756#ifdef FD_CLOEXEC
4757 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4758#endif
4759
drhda0e7682008-07-30 15:27:54 +00004760 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004761
drh7ed97b92010-01-20 13:07:21 +00004762
4763#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4764 struct statfs fsInfo;
4765 if( fstatfs(fd, &fsInfo) == -1 ){
4766 ((unixFile*)pFile)->lastErrno = errno;
4767 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4768 close(fd); /* silently leak if fail, in error */
4769 return SQLITE_IOERR_ACCESS;
4770 }
4771 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4772 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4773 }
4774#endif
4775
4776#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004777#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004778 isAutoProxy = 1;
4779#endif
4780 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004781 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4782 int useProxy = 0;
4783
dan08da86a2009-08-21 17:18:03 +00004784 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4785 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004786 if( envforce!=NULL ){
4787 useProxy = atoi(envforce)>0;
4788 }else{
4789 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004790 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004791 /* In theory, the close(fd) call is sub-optimal. If the file opened
4792 ** with fd is a database file, and there are other connections open
4793 ** on that file that are currently holding advisory locks on it,
4794 ** then the call to close() will cancel those locks. In practice,
4795 ** we're assuming that statfs() doesn't fail very often. At least
4796 ** not while other file descriptors opened by the same process on
4797 ** the same file are working. */
4798 p->lastErrno = errno;
4799 if( dirfd>=0 ){
4800 close(dirfd); /* silently leak if fail, in error */
4801 }
aswiftaebf4132008-11-21 00:10:35 +00004802 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004803 rc = SQLITE_IOERR_ACCESS;
4804 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004805 }
4806 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4807 }
4808 if( useProxy ){
4809 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4810 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004811 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004812 if( rc!=SQLITE_OK ){
4813 /* Use unixClose to clean up the resources added in fillInUnixFile
4814 ** and clear all the structure's references. Specifically,
4815 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4816 */
4817 unixClose(pFile);
4818 return rc;
4819 }
aswiftaebf4132008-11-21 00:10:35 +00004820 }
dane946c392009-08-22 11:39:46 +00004821 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004822 }
4823 }
4824#endif
4825
dane946c392009-08-22 11:39:46 +00004826 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4827open_finished:
4828 if( rc!=SQLITE_OK ){
4829 sqlite3_free(p->pUnused);
4830 }
4831 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004832}
4833
dane946c392009-08-22 11:39:46 +00004834
danielk1977b4b47412007-08-17 15:53:36 +00004835/*
danielk1977fee2d252007-08-18 10:59:19 +00004836** Delete the file at zPath. If the dirSync argument is true, fsync()
4837** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004838*/
drh6b9d6dd2008-12-03 19:34:47 +00004839static int unixDelete(
4840 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4841 const char *zPath, /* Name of file to be deleted */
4842 int dirSync /* If true, fsync() directory after deleting file */
4843){
danielk1977fee2d252007-08-18 10:59:19 +00004844 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004845 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004846 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004847 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00004848 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00004849 }
danielk1977d39fa702008-10-16 13:27:40 +00004850#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004851 if( dirSync ){
4852 int fd;
4853 rc = openDirectory(zPath, &fd);
4854 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004855#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004856 if( fsync(fd)==-1 )
4857#else
4858 if( fsync(fd) )
4859#endif
4860 {
dane18d4952011-02-21 11:46:24 +00004861 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00004862 }
aswiftaebf4132008-11-21 00:10:35 +00004863 if( close(fd)&&!rc ){
dane18d4952011-02-21 11:46:24 +00004864 rc = unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", zPath);
aswiftaebf4132008-11-21 00:10:35 +00004865 }
danielk1977fee2d252007-08-18 10:59:19 +00004866 }
4867 }
danielk1977d138dd82008-10-15 16:02:48 +00004868#endif
danielk1977fee2d252007-08-18 10:59:19 +00004869 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004870}
4871
danielk197790949c22007-08-17 16:50:38 +00004872/*
4873** Test the existance of or access permissions of file zPath. The
4874** test performed depends on the value of flags:
4875**
4876** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4877** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4878** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4879**
4880** Otherwise return 0.
4881*/
danielk1977861f7452008-06-05 11:39:11 +00004882static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004883 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4884 const char *zPath, /* Path of the file to examine */
4885 int flags, /* What do we want to learn about the zPath file? */
4886 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004887){
rse25c0d1a2007-09-20 08:38:14 +00004888 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004889 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004890 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004891 switch( flags ){
4892 case SQLITE_ACCESS_EXISTS:
4893 amode = F_OK;
4894 break;
4895 case SQLITE_ACCESS_READWRITE:
4896 amode = W_OK|R_OK;
4897 break;
drh50d3f902007-08-27 21:10:36 +00004898 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004899 amode = R_OK;
4900 break;
4901
4902 default:
4903 assert(!"Invalid flags argument");
4904 }
danielk1977861f7452008-06-05 11:39:11 +00004905 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004906 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4907 struct stat buf;
4908 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4909 *pResOut = 0;
4910 }
4911 }
danielk1977861f7452008-06-05 11:39:11 +00004912 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004913}
4914
danielk1977b4b47412007-08-17 15:53:36 +00004915
4916/*
4917** Turn a relative pathname into a full pathname. The relative path
4918** is stored as a nul-terminated string in the buffer pointed to by
4919** zPath.
4920**
4921** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4922** (in this case, MAX_PATHNAME bytes). The full-path is written to
4923** this buffer before returning.
4924*/
danielk1977adfb9b02007-09-17 07:02:56 +00004925static int unixFullPathname(
4926 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4927 const char *zPath, /* Possibly relative input path */
4928 int nOut, /* Size of output buffer in bytes */
4929 char *zOut /* Output buffer */
4930){
danielk1977843e65f2007-09-01 16:16:15 +00004931
4932 /* It's odd to simulate an io-error here, but really this is just
4933 ** using the io-error infrastructure to test that SQLite handles this
4934 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004935 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004936 */
4937 SimulateIOError( return SQLITE_ERROR );
4938
drh153c62c2007-08-24 03:51:33 +00004939 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004940 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004941
drh3c7f2dc2007-12-06 13:26:20 +00004942 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004943 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004944 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004945 }else{
4946 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004947 if( getcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00004948 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004949 }
drhea678832008-12-10 19:26:22 +00004950 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004951 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004952 }
4953 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004954}
4955
drh0ccebe72005-06-07 22:22:50 +00004956
drh761df872006-12-21 01:29:22 +00004957#ifndef SQLITE_OMIT_LOAD_EXTENSION
4958/*
4959** Interfaces for opening a shared library, finding entry points
4960** within the shared library, and closing the shared library.
4961*/
4962#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004963static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4964 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004965 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4966}
danielk197795c8a542007-09-01 06:51:27 +00004967
4968/*
4969** SQLite calls this function immediately after a call to unixDlSym() or
4970** unixDlOpen() fails (returns a null pointer). If a more detailed error
4971** message is available, it is written to zBufOut. If no error message
4972** is available, zBufOut is left unmodified and SQLite uses a default
4973** error message.
4974*/
danielk1977397d65f2008-11-19 11:35:39 +00004975static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00004976 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004977 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004978 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004979 zErr = dlerror();
4980 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004981 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004982 }
drh6c7d5c52008-11-21 20:32:33 +00004983 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004984}
drh1875f7a2008-12-08 18:19:17 +00004985static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4986 /*
4987 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4988 ** cast into a pointer to a function. And yet the library dlsym() routine
4989 ** returns a void* which is really a pointer to a function. So how do we
4990 ** use dlsym() with -pedantic-errors?
4991 **
4992 ** Variable x below is defined to be a pointer to a function taking
4993 ** parameters void* and const char* and returning a pointer to a function.
4994 ** We initialize x by assigning it a pointer to the dlsym() function.
4995 ** (That assignment requires a cast.) Then we call the function that
4996 ** x points to.
4997 **
4998 ** This work-around is unlikely to work correctly on any system where
4999 ** you really cannot cast a function pointer into void*. But then, on the
5000 ** other hand, dlsym() will not work on such a system either, so we have
5001 ** not really lost anything.
5002 */
5003 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005004 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005005 x = (void(*(*)(void*,const char*))(void))dlsym;
5006 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005007}
danielk1977397d65f2008-11-19 11:35:39 +00005008static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5009 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005010 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005011}
danielk1977b4b47412007-08-17 15:53:36 +00005012#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5013 #define unixDlOpen 0
5014 #define unixDlError 0
5015 #define unixDlSym 0
5016 #define unixDlClose 0
5017#endif
5018
5019/*
danielk197790949c22007-08-17 16:50:38 +00005020** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005021*/
danielk1977397d65f2008-11-19 11:35:39 +00005022static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5023 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005024 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005025
drhbbd42a62004-05-22 17:41:58 +00005026 /* We have to initialize zBuf to prevent valgrind from reporting
5027 ** errors. The reports issued by valgrind are incorrect - we would
5028 ** prefer that the randomness be increased by making use of the
5029 ** uninitialized space in zBuf - but valgrind errors tend to worry
5030 ** some users. Rather than argue, it seems easier just to initialize
5031 ** the whole array and silence valgrind, even if that means less randomness
5032 ** in the random seed.
5033 **
5034 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005035 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005036 ** tests repeatable.
5037 */
danielk1977b4b47412007-08-17 15:53:36 +00005038 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005039#if !defined(SQLITE_TEST)
5040 {
drh842b8642005-01-21 17:53:17 +00005041 int pid, fd;
5042 fd = open("/dev/urandom", O_RDONLY);
5043 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005044 time_t t;
5045 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005046 memcpy(zBuf, &t, sizeof(t));
5047 pid = getpid();
5048 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005049 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005050 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005051 }else{
drhff812312011-02-23 13:33:46 +00005052 do{ nBuf = read(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh842b8642005-01-21 17:53:17 +00005053 close(fd);
5054 }
drhbbd42a62004-05-22 17:41:58 +00005055 }
5056#endif
drh72cbd072008-10-14 17:58:38 +00005057 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005058}
5059
danielk1977b4b47412007-08-17 15:53:36 +00005060
drhbbd42a62004-05-22 17:41:58 +00005061/*
5062** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005063** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005064** The return value is the number of microseconds of sleep actually
5065** requested from the underlying operating system, a number which
5066** might be greater than or equal to the argument, but not less
5067** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005068*/
danielk1977397d65f2008-11-19 11:35:39 +00005069static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005070#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005071 struct timespec sp;
5072
5073 sp.tv_sec = microseconds / 1000000;
5074 sp.tv_nsec = (microseconds % 1000000) * 1000;
5075 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005076 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005077 return microseconds;
5078#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005079 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005080 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005081 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005082#else
danielk1977b4b47412007-08-17 15:53:36 +00005083 int seconds = (microseconds+999999)/1000000;
5084 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005085 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005086 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005087#endif
drh88f474a2006-01-02 20:00:12 +00005088}
5089
5090/*
drh6b9d6dd2008-12-03 19:34:47 +00005091** The following variable, if set to a non-zero value, is interpreted as
5092** the number of seconds since 1970 and is used to set the result of
5093** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005094*/
5095#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005096int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005097#endif
5098
5099/*
drhb7e8ea22010-05-03 14:32:30 +00005100** Find the current time (in Universal Coordinated Time). Write into *piNow
5101** the current time and date as a Julian Day number times 86_400_000. In
5102** other words, write into *piNow the number of milliseconds since the Julian
5103** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5104** proleptic Gregorian calendar.
5105**
5106** On success, return 0. Return 1 if the time and date cannot be found.
5107*/
5108static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5109 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5110#if defined(NO_GETTOD)
5111 time_t t;
5112 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005113 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005114#elif OS_VXWORKS
5115 struct timespec sNow;
5116 clock_gettime(CLOCK_REALTIME, &sNow);
5117 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5118#else
5119 struct timeval sNow;
5120 gettimeofday(&sNow, 0);
5121 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5122#endif
5123
5124#ifdef SQLITE_TEST
5125 if( sqlite3_current_time ){
5126 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5127 }
5128#endif
5129 UNUSED_PARAMETER(NotUsed);
5130 return 0;
5131}
5132
5133/*
drhbbd42a62004-05-22 17:41:58 +00005134** Find the current time (in Universal Coordinated Time). Write the
5135** current time and date as a Julian Day number into *prNow and
5136** return 0. Return 1 if the time and date cannot be found.
5137*/
danielk1977397d65f2008-11-19 11:35:39 +00005138static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005139 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005140 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005141 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005142 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005143 return 0;
5144}
danielk1977b4b47412007-08-17 15:53:36 +00005145
drh6b9d6dd2008-12-03 19:34:47 +00005146/*
5147** We added the xGetLastError() method with the intention of providing
5148** better low-level error messages when operating-system problems come up
5149** during SQLite operation. But so far, none of that has been implemented
5150** in the core. So this routine is never called. For now, it is merely
5151** a place-holder.
5152*/
danielk1977397d65f2008-11-19 11:35:39 +00005153static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5154 UNUSED_PARAMETER(NotUsed);
5155 UNUSED_PARAMETER(NotUsed2);
5156 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005157 return 0;
5158}
5159
drhf2424c52010-04-26 00:04:55 +00005160
5161/*
drh734c9862008-11-28 15:37:20 +00005162************************ End of sqlite3_vfs methods ***************************
5163******************************************************************************/
5164
drh715ff302008-12-03 22:32:44 +00005165/******************************************************************************
5166************************** Begin Proxy Locking ********************************
5167**
5168** Proxy locking is a "uber-locking-method" in this sense: It uses the
5169** other locking methods on secondary lock files. Proxy locking is a
5170** meta-layer over top of the primitive locking implemented above. For
5171** this reason, the division that implements of proxy locking is deferred
5172** until late in the file (here) after all of the other I/O methods have
5173** been defined - so that the primitive locking methods are available
5174** as services to help with the implementation of proxy locking.
5175**
5176****
5177**
5178** The default locking schemes in SQLite use byte-range locks on the
5179** database file to coordinate safe, concurrent access by multiple readers
5180** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5181** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5182** as POSIX read & write locks over fixed set of locations (via fsctl),
5183** on AFP and SMB only exclusive byte-range locks are available via fsctl
5184** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5185** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5186** address in the shared range is taken for a SHARED lock, the entire
5187** shared range is taken for an EXCLUSIVE lock):
5188**
5189** PENDING_BYTE 0x40000000
5190** RESERVED_BYTE 0x40000001
5191** SHARED_RANGE 0x40000002 -> 0x40000200
5192**
5193** This works well on the local file system, but shows a nearly 100x
5194** slowdown in read performance on AFP because the AFP client disables
5195** the read cache when byte-range locks are present. Enabling the read
5196** cache exposes a cache coherency problem that is present on all OS X
5197** supported network file systems. NFS and AFP both observe the
5198** close-to-open semantics for ensuring cache coherency
5199** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5200** address the requirements for concurrent database access by multiple
5201** readers and writers
5202** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5203**
5204** To address the performance and cache coherency issues, proxy file locking
5205** changes the way database access is controlled by limiting access to a
5206** single host at a time and moving file locks off of the database file
5207** and onto a proxy file on the local file system.
5208**
5209**
5210** Using proxy locks
5211** -----------------
5212**
5213** C APIs
5214**
5215** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5216** <proxy_path> | ":auto:");
5217** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5218**
5219**
5220** SQL pragmas
5221**
5222** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5223** PRAGMA [database.]lock_proxy_file
5224**
5225** Specifying ":auto:" means that if there is a conch file with a matching
5226** host ID in it, the proxy path in the conch file will be used, otherwise
5227** a proxy path based on the user's temp dir
5228** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5229** actual proxy file name is generated from the name and path of the
5230** database file. For example:
5231**
5232** For database path "/Users/me/foo.db"
5233** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5234**
5235** Once a lock proxy is configured for a database connection, it can not
5236** be removed, however it may be switched to a different proxy path via
5237** the above APIs (assuming the conch file is not being held by another
5238** connection or process).
5239**
5240**
5241** How proxy locking works
5242** -----------------------
5243**
5244** Proxy file locking relies primarily on two new supporting files:
5245**
5246** * conch file to limit access to the database file to a single host
5247** at a time
5248**
5249** * proxy file to act as a proxy for the advisory locks normally
5250** taken on the database
5251**
5252** The conch file - to use a proxy file, sqlite must first "hold the conch"
5253** by taking an sqlite-style shared lock on the conch file, reading the
5254** contents and comparing the host's unique host ID (see below) and lock
5255** proxy path against the values stored in the conch. The conch file is
5256** stored in the same directory as the database file and the file name
5257** is patterned after the database file name as ".<databasename>-conch".
5258** If the conch file does not exist, or it's contents do not match the
5259** host ID and/or proxy path, then the lock is escalated to an exclusive
5260** lock and the conch file contents is updated with the host ID and proxy
5261** path and the lock is downgraded to a shared lock again. If the conch
5262** is held by another process (with a shared lock), the exclusive lock
5263** will fail and SQLITE_BUSY is returned.
5264**
5265** The proxy file - a single-byte file used for all advisory file locks
5266** normally taken on the database file. This allows for safe sharing
5267** of the database file for multiple readers and writers on the same
5268** host (the conch ensures that they all use the same local lock file).
5269**
drh715ff302008-12-03 22:32:44 +00005270** Requesting the lock proxy does not immediately take the conch, it is
5271** only taken when the first request to lock database file is made.
5272** This matches the semantics of the traditional locking behavior, where
5273** opening a connection to a database file does not take a lock on it.
5274** The shared lock and an open file descriptor are maintained until
5275** the connection to the database is closed.
5276**
5277** The proxy file and the lock file are never deleted so they only need
5278** to be created the first time they are used.
5279**
5280** Configuration options
5281** ---------------------
5282**
5283** SQLITE_PREFER_PROXY_LOCKING
5284**
5285** Database files accessed on non-local file systems are
5286** automatically configured for proxy locking, lock files are
5287** named automatically using the same logic as
5288** PRAGMA lock_proxy_file=":auto:"
5289**
5290** SQLITE_PROXY_DEBUG
5291**
5292** Enables the logging of error messages during host id file
5293** retrieval and creation
5294**
drh715ff302008-12-03 22:32:44 +00005295** LOCKPROXYDIR
5296**
5297** Overrides the default directory used for lock proxy files that
5298** are named automatically via the ":auto:" setting
5299**
5300** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5301**
5302** Permissions to use when creating a directory for storing the
5303** lock proxy files, only used when LOCKPROXYDIR is not set.
5304**
5305**
5306** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5307** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5308** force proxy locking to be used for every database file opened, and 0
5309** will force automatic proxy locking to be disabled for all database
5310** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5311** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5312*/
5313
5314/*
5315** Proxy locking is only available on MacOSX
5316*/
drhd2cb50b2009-01-09 21:41:17 +00005317#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005318
drh715ff302008-12-03 22:32:44 +00005319/*
5320** The proxyLockingContext has the path and file structures for the remote
5321** and local proxy files in it
5322*/
5323typedef struct proxyLockingContext proxyLockingContext;
5324struct proxyLockingContext {
5325 unixFile *conchFile; /* Open conch file */
5326 char *conchFilePath; /* Name of the conch file */
5327 unixFile *lockProxy; /* Open proxy lock file */
5328 char *lockProxyPath; /* Name of the proxy lock file */
5329 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005330 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005331 void *oldLockingContext; /* Original lockingcontext to restore on close */
5332 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5333};
5334
drh7ed97b92010-01-20 13:07:21 +00005335/*
5336** The proxy lock file path for the database at dbPath is written into lPath,
5337** which must point to valid, writable memory large enough for a maxLen length
5338** file path.
drh715ff302008-12-03 22:32:44 +00005339*/
drh715ff302008-12-03 22:32:44 +00005340static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5341 int len;
5342 int dbLen;
5343 int i;
5344
5345#ifdef LOCKPROXYDIR
5346 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5347#else
5348# ifdef _CS_DARWIN_USER_TEMP_DIR
5349 {
drh7ed97b92010-01-20 13:07:21 +00005350 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005351 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5352 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005353 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005354 }
drh7ed97b92010-01-20 13:07:21 +00005355 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005356 }
5357# else
5358 len = strlcpy(lPath, "/tmp/", maxLen);
5359# endif
5360#endif
5361
5362 if( lPath[len-1]!='/' ){
5363 len = strlcat(lPath, "/", maxLen);
5364 }
5365
5366 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005367 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005368 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005369 char c = dbPath[i];
5370 lPath[i+len] = (c=='/')?'_':c;
5371 }
5372 lPath[i+len]='\0';
5373 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005374 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005375 return SQLITE_OK;
5376}
5377
drh7ed97b92010-01-20 13:07:21 +00005378/*
5379 ** Creates the lock file and any missing directories in lockPath
5380 */
5381static int proxyCreateLockPath(const char *lockPath){
5382 int i, len;
5383 char buf[MAXPATHLEN];
5384 int start = 0;
5385
5386 assert(lockPath!=NULL);
5387 /* try to create all the intermediate directories */
5388 len = (int)strlen(lockPath);
5389 buf[0] = lockPath[0];
5390 for( i=1; i<len; i++ ){
5391 if( lockPath[i] == '/' && (i - start > 0) ){
5392 /* only mkdir if leaf dir != "." or "/" or ".." */
5393 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5394 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5395 buf[i]='\0';
5396 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5397 int err=errno;
5398 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005399 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005400 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005401 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005402 return err;
5403 }
5404 }
5405 }
5406 start=i+1;
5407 }
5408 buf[i] = lockPath[i];
5409 }
drh308c2a52010-05-14 11:30:18 +00005410 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005411 return 0;
5412}
5413
drh715ff302008-12-03 22:32:44 +00005414/*
5415** Create a new VFS file descriptor (stored in memory obtained from
5416** sqlite3_malloc) and open the file named "path" in the file descriptor.
5417**
5418** The caller is responsible not only for closing the file descriptor
5419** but also for freeing the memory associated with the file descriptor.
5420*/
drh7ed97b92010-01-20 13:07:21 +00005421static int proxyCreateUnixFile(
5422 const char *path, /* path for the new unixFile */
5423 unixFile **ppFile, /* unixFile created and returned by ref */
5424 int islockfile /* if non zero missing dirs will be created */
5425) {
5426 int fd = -1;
5427 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005428 unixFile *pNew;
5429 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005430 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005431 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005432 int terrno = 0;
5433 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005434
drh7ed97b92010-01-20 13:07:21 +00005435 /* 1. first try to open/create the file
5436 ** 2. if that fails, and this is a lock file (not-conch), try creating
5437 ** the parent directories and then try again.
5438 ** 3. if that fails, try to open the file read-only
5439 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5440 */
5441 pUnused = findReusableFd(path, openFlags);
5442 if( pUnused ){
5443 fd = pUnused->fd;
5444 }else{
5445 pUnused = sqlite3_malloc(sizeof(*pUnused));
5446 if( !pUnused ){
5447 return SQLITE_NOMEM;
5448 }
5449 }
5450 if( fd<0 ){
5451 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5452 terrno = errno;
5453 if( fd<0 && errno==ENOENT && islockfile ){
5454 if( proxyCreateLockPath(path) == SQLITE_OK ){
5455 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5456 }
5457 }
5458 }
5459 if( fd<0 ){
5460 openFlags = O_RDONLY;
5461 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5462 terrno = errno;
5463 }
5464 if( fd<0 ){
5465 if( islockfile ){
5466 return SQLITE_BUSY;
5467 }
5468 switch (terrno) {
5469 case EACCES:
5470 return SQLITE_PERM;
5471 case EIO:
5472 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5473 default:
drh9978c972010-02-23 17:36:32 +00005474 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005475 }
5476 }
5477
5478 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5479 if( pNew==NULL ){
5480 rc = SQLITE_NOMEM;
5481 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005482 }
5483 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005484 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005485 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005486 pUnused->fd = fd;
5487 pUnused->flags = openFlags;
5488 pNew->pUnused = pUnused;
5489
5490 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5491 if( rc==SQLITE_OK ){
5492 *ppFile = pNew;
5493 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005494 }
drh7ed97b92010-01-20 13:07:21 +00005495end_create_proxy:
5496 close(fd); /* silently leak fd if error, we're already in error */
5497 sqlite3_free(pNew);
5498 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005499 return rc;
5500}
5501
drh7ed97b92010-01-20 13:07:21 +00005502#ifdef SQLITE_TEST
5503/* simulate multiple hosts by creating unique hostid file paths */
5504int sqlite3_hostid_num = 0;
5505#endif
5506
5507#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5508
drh0ab216a2010-07-02 17:10:40 +00005509/* Not always defined in the headers as it ought to be */
5510extern int gethostuuid(uuid_t id, const struct timespec *wait);
5511
drh7ed97b92010-01-20 13:07:21 +00005512/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5513** bytes of writable memory.
5514*/
5515static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005516 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5517 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005518#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5519 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005520 {
5521 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5522 if( gethostuuid(pHostID, &timeout) ){
5523 int err = errno;
5524 if( pError ){
5525 *pError = err;
5526 }
5527 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005528 }
drh7ed97b92010-01-20 13:07:21 +00005529 }
drhe8b0c9b2010-09-25 14:13:17 +00005530#endif
drh7ed97b92010-01-20 13:07:21 +00005531#ifdef SQLITE_TEST
5532 /* simulate multiple hosts by creating unique hostid file paths */
5533 if( sqlite3_hostid_num != 0){
5534 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5535 }
5536#endif
5537
5538 return SQLITE_OK;
5539}
5540
5541/* The conch file contains the header, host id and lock file path
5542 */
5543#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5544#define PROXY_HEADERLEN 1 /* conch file header length */
5545#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5546#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5547
5548/*
5549** Takes an open conch file, copies the contents to a new path and then moves
5550** it back. The newly created file's file descriptor is assigned to the
5551** conch file structure and finally the original conch file descriptor is
5552** closed. Returns zero if successful.
5553*/
5554static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5555 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5556 unixFile *conchFile = pCtx->conchFile;
5557 char tPath[MAXPATHLEN];
5558 char buf[PROXY_MAXCONCHLEN];
5559 char *cPath = pCtx->conchFilePath;
5560 size_t readLen = 0;
5561 size_t pathLen = 0;
5562 char errmsg[64] = "";
5563 int fd = -1;
5564 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005565 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005566
5567 /* create a new path by replace the trailing '-conch' with '-break' */
5568 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5569 if( pathLen>MAXPATHLEN || pathLen<6 ||
5570 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005571 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005572 goto end_breaklock;
5573 }
5574 /* read the conch content */
5575 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5576 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005577 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005578 goto end_breaklock;
5579 }
5580 /* write it out to the temporary break file */
5581 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5582 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005583 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005584 goto end_breaklock;
5585 }
drh0ab216a2010-07-02 17:10:40 +00005586 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005587 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005588 goto end_breaklock;
5589 }
5590 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005591 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005592 goto end_breaklock;
5593 }
5594 rc = 0;
5595 fprintf(stderr, "broke stale lock on %s\n", cPath);
5596 close(conchFile->h);
5597 conchFile->h = fd;
5598 conchFile->openFlags = O_RDWR | O_CREAT;
5599
5600end_breaklock:
5601 if( rc ){
5602 if( fd>=0 ){
5603 unlink(tPath);
5604 close(fd);
5605 }
5606 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5607 }
5608 return rc;
5609}
5610
5611/* Take the requested lock on the conch file and break a stale lock if the
5612** host id matches.
5613*/
5614static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5615 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5616 unixFile *conchFile = pCtx->conchFile;
5617 int rc = SQLITE_OK;
5618 int nTries = 0;
5619 struct timespec conchModTime;
5620
5621 do {
5622 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5623 nTries ++;
5624 if( rc==SQLITE_BUSY ){
5625 /* If the lock failed (busy):
5626 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5627 * 2nd try: fail if the mod time changed or host id is different, wait
5628 * 10 sec and try again
5629 * 3rd try: break the lock unless the mod time has changed.
5630 */
5631 struct stat buf;
5632 if( fstat(conchFile->h, &buf) ){
5633 pFile->lastErrno = errno;
5634 return SQLITE_IOERR_LOCK;
5635 }
5636
5637 if( nTries==1 ){
5638 conchModTime = buf.st_mtimespec;
5639 usleep(500000); /* wait 0.5 sec and try the lock again*/
5640 continue;
5641 }
5642
5643 assert( nTries>1 );
5644 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5645 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5646 return SQLITE_BUSY;
5647 }
5648
5649 if( nTries==2 ){
5650 char tBuf[PROXY_MAXCONCHLEN];
5651 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5652 if( len<0 ){
5653 pFile->lastErrno = errno;
5654 return SQLITE_IOERR_LOCK;
5655 }
5656 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5657 /* don't break the lock if the host id doesn't match */
5658 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5659 return SQLITE_BUSY;
5660 }
5661 }else{
5662 /* don't break the lock on short read or a version mismatch */
5663 return SQLITE_BUSY;
5664 }
5665 usleep(10000000); /* wait 10 sec and try the lock again */
5666 continue;
5667 }
5668
5669 assert( nTries==3 );
5670 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5671 rc = SQLITE_OK;
5672 if( lockType==EXCLUSIVE_LOCK ){
5673 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5674 }
5675 if( !rc ){
5676 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5677 }
5678 }
5679 }
5680 } while( rc==SQLITE_BUSY && nTries<3 );
5681
5682 return rc;
5683}
5684
5685/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005686** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5687** lockPath means that the lockPath in the conch file will be used if the
5688** host IDs match, or a new lock path will be generated automatically
5689** and written to the conch file.
5690*/
5691static int proxyTakeConch(unixFile *pFile){
5692 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5693
drh7ed97b92010-01-20 13:07:21 +00005694 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005695 return SQLITE_OK;
5696 }else{
5697 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005698 uuid_t myHostID;
5699 int pError = 0;
5700 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005701 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005702 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005703 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005704 int createConch = 0;
5705 int hostIdMatch = 0;
5706 int readLen = 0;
5707 int tryOldLockPath = 0;
5708 int forceNewLockPath = 0;
5709
drh308c2a52010-05-14 11:30:18 +00005710 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5711 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005712
drh7ed97b92010-01-20 13:07:21 +00005713 rc = proxyGetHostID(myHostID, &pError);
5714 if( (rc&0xff)==SQLITE_IOERR ){
5715 pFile->lastErrno = pError;
5716 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005717 }
drh7ed97b92010-01-20 13:07:21 +00005718 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005719 if( rc!=SQLITE_OK ){
5720 goto end_takeconch;
5721 }
drh7ed97b92010-01-20 13:07:21 +00005722 /* read the existing conch file */
5723 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5724 if( readLen<0 ){
5725 /* I/O error: lastErrno set by seekAndRead */
5726 pFile->lastErrno = conchFile->lastErrno;
5727 rc = SQLITE_IOERR_READ;
5728 goto end_takeconch;
5729 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5730 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5731 /* a short read or version format mismatch means we need to create a new
5732 ** conch file.
5733 */
5734 createConch = 1;
5735 }
5736 /* if the host id matches and the lock path already exists in the conch
5737 ** we'll try to use the path there, if we can't open that path, we'll
5738 ** retry with a new auto-generated path
5739 */
5740 do { /* in case we need to try again for an :auto: named lock file */
5741
5742 if( !createConch && !forceNewLockPath ){
5743 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5744 PROXY_HOSTIDLEN);
5745 /* if the conch has data compare the contents */
5746 if( !pCtx->lockProxyPath ){
5747 /* for auto-named local lock file, just check the host ID and we'll
5748 ** use the local lock file path that's already in there
5749 */
5750 if( hostIdMatch ){
5751 size_t pathLen = (readLen - PROXY_PATHINDEX);
5752
5753 if( pathLen>=MAXPATHLEN ){
5754 pathLen=MAXPATHLEN-1;
5755 }
5756 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5757 lockPath[pathLen] = 0;
5758 tempLockPath = lockPath;
5759 tryOldLockPath = 1;
5760 /* create a copy of the lock path if the conch is taken */
5761 goto end_takeconch;
5762 }
5763 }else if( hostIdMatch
5764 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5765 readLen-PROXY_PATHINDEX)
5766 ){
5767 /* conch host and lock path match */
5768 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005769 }
drh7ed97b92010-01-20 13:07:21 +00005770 }
5771
5772 /* if the conch isn't writable and doesn't match, we can't take it */
5773 if( (conchFile->openFlags&O_RDWR) == 0 ){
5774 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005775 goto end_takeconch;
5776 }
drh7ed97b92010-01-20 13:07:21 +00005777
5778 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005779 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005780 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5781 tempLockPath = lockPath;
5782 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005783 }
drh7ed97b92010-01-20 13:07:21 +00005784
5785 /* update conch with host and path (this will fail if other process
5786 ** has a shared lock already), if the host id matches, use the big
5787 ** stick.
drh715ff302008-12-03 22:32:44 +00005788 */
drh7ed97b92010-01-20 13:07:21 +00005789 futimes(conchFile->h, NULL);
5790 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005791 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005792 /* We are trying for an exclusive lock but another thread in this
5793 ** same process is still holding a shared lock. */
5794 rc = SQLITE_BUSY;
5795 } else {
5796 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005797 }
drh715ff302008-12-03 22:32:44 +00005798 }else{
drh7ed97b92010-01-20 13:07:21 +00005799 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005800 }
drh7ed97b92010-01-20 13:07:21 +00005801 if( rc==SQLITE_OK ){
5802 char writeBuffer[PROXY_MAXCONCHLEN];
5803 int writeSize = 0;
5804
5805 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5806 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5807 if( pCtx->lockProxyPath!=NULL ){
5808 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5809 }else{
5810 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5811 }
5812 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00005813 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00005814 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5815 fsync(conchFile->h);
5816 /* If we created a new conch file (not just updated the contents of a
5817 ** valid conch file), try to match the permissions of the database
5818 */
5819 if( rc==SQLITE_OK && createConch ){
5820 struct stat buf;
drhff812312011-02-23 13:33:46 +00005821 int rc;
drh7ed97b92010-01-20 13:07:21 +00005822 int err = fstat(pFile->h, &buf);
5823 if( err==0 ){
5824 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5825 S_IROTH|S_IWOTH);
5826 /* try to match the database file R/W permissions, ignore failure */
5827#ifndef SQLITE_PROXY_DEBUG
5828 fchmod(conchFile->h, cmode);
5829#else
drhff812312011-02-23 13:33:46 +00005830 do{
5831 rc = fchmod(conchFile->h, cmode);
5832 }while( rc==(-1) && errno==EINTR );
5833 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00005834 int code = errno;
5835 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5836 cmode, code, strerror(code));
5837 } else {
5838 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5839 }
5840 }else{
5841 int code = errno;
5842 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5843 err, code, strerror(code));
5844#endif
5845 }
drh715ff302008-12-03 22:32:44 +00005846 }
5847 }
drh7ed97b92010-01-20 13:07:21 +00005848 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5849
5850 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005851 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005852 if( rc==SQLITE_OK && pFile->openFlags ){
5853 if( pFile->h>=0 ){
5854#ifdef STRICT_CLOSE_ERROR
5855 if( close(pFile->h) ){
5856 pFile->lastErrno = errno;
5857 return SQLITE_IOERR_CLOSE;
5858 }
5859#else
5860 close(pFile->h); /* silently leak fd if fail */
5861#endif
5862 }
5863 pFile->h = -1;
5864 int fd = open(pCtx->dbPath, pFile->openFlags,
5865 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005866 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005867 if( fd>=0 ){
5868 pFile->h = fd;
5869 }else{
drh9978c972010-02-23 17:36:32 +00005870 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005871 during locking */
5872 }
5873 }
5874 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5875 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5876 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5877 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5878 /* we couldn't create the proxy lock file with the old lock file path
5879 ** so try again via auto-naming
5880 */
5881 forceNewLockPath = 1;
5882 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005883 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005884 }
5885 }
5886 if( rc==SQLITE_OK ){
5887 /* Need to make a copy of path if we extracted the value
5888 ** from the conch file or the path was allocated on the stack
5889 */
5890 if( tempLockPath ){
5891 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5892 if( !pCtx->lockProxyPath ){
5893 rc = SQLITE_NOMEM;
5894 }
5895 }
5896 }
5897 if( rc==SQLITE_OK ){
5898 pCtx->conchHeld = 1;
5899
5900 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5901 afpLockingContext *afpCtx;
5902 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5903 afpCtx->dbPath = pCtx->lockProxyPath;
5904 }
5905 } else {
5906 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5907 }
drh308c2a52010-05-14 11:30:18 +00005908 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5909 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005910 return rc;
drh308c2a52010-05-14 11:30:18 +00005911 } while (1); /* in case we need to retry the :auto: lock file -
5912 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005913 }
5914}
5915
5916/*
5917** If pFile holds a lock on a conch file, then release that lock.
5918*/
5919static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005920 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005921 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5922 unixFile *conchFile; /* Name of the conch file */
5923
5924 pCtx = (proxyLockingContext *)pFile->lockingContext;
5925 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005926 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005927 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005928 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005929 if( pCtx->conchHeld>0 ){
5930 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5931 }
drh715ff302008-12-03 22:32:44 +00005932 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005933 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5934 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005935 return rc;
5936}
5937
5938/*
5939** Given the name of a database file, compute the name of its conch file.
5940** Store the conch filename in memory obtained from sqlite3_malloc().
5941** Make *pConchPath point to the new name. Return SQLITE_OK on success
5942** or SQLITE_NOMEM if unable to obtain memory.
5943**
5944** The caller is responsible for ensuring that the allocated memory
5945** space is eventually freed.
5946**
5947** *pConchPath is set to NULL if a memory allocation error occurs.
5948*/
5949static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5950 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005951 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005952 char *conchPath; /* buffer in which to construct conch name */
5953
5954 /* Allocate space for the conch filename and initialize the name to
5955 ** the name of the original database file. */
5956 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5957 if( conchPath==0 ){
5958 return SQLITE_NOMEM;
5959 }
5960 memcpy(conchPath, dbPath, len+1);
5961
5962 /* now insert a "." before the last / character */
5963 for( i=(len-1); i>=0; i-- ){
5964 if( conchPath[i]=='/' ){
5965 i++;
5966 break;
5967 }
5968 }
5969 conchPath[i]='.';
5970 while ( i<len ){
5971 conchPath[i+1]=dbPath[i];
5972 i++;
5973 }
5974
5975 /* append the "-conch" suffix to the file */
5976 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005977 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005978
5979 return SQLITE_OK;
5980}
5981
5982
5983/* Takes a fully configured proxy locking-style unix file and switches
5984** the local lock file path
5985*/
5986static int switchLockProxyPath(unixFile *pFile, const char *path) {
5987 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5988 char *oldPath = pCtx->lockProxyPath;
5989 int rc = SQLITE_OK;
5990
drh308c2a52010-05-14 11:30:18 +00005991 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005992 return SQLITE_BUSY;
5993 }
5994
5995 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5996 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5997 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5998 return SQLITE_OK;
5999 }else{
6000 unixFile *lockProxy = pCtx->lockProxy;
6001 pCtx->lockProxy=NULL;
6002 pCtx->conchHeld = 0;
6003 if( lockProxy!=NULL ){
6004 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6005 if( rc ) return rc;
6006 sqlite3_free(lockProxy);
6007 }
6008 sqlite3_free(oldPath);
6009 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6010 }
6011
6012 return rc;
6013}
6014
6015/*
6016** pFile is a file that has been opened by a prior xOpen call. dbPath
6017** is a string buffer at least MAXPATHLEN+1 characters in size.
6018**
6019** This routine find the filename associated with pFile and writes it
6020** int dbPath.
6021*/
6022static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006023#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006024 if( pFile->pMethod == &afpIoMethods ){
6025 /* afp style keeps a reference to the db path in the filePath field
6026 ** of the struct */
drhea678832008-12-10 19:26:22 +00006027 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006028 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6029 } else
drh715ff302008-12-03 22:32:44 +00006030#endif
6031 if( pFile->pMethod == &dotlockIoMethods ){
6032 /* dot lock style uses the locking context to store the dot lock
6033 ** file path */
6034 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6035 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6036 }else{
6037 /* all other styles use the locking context to store the db file path */
6038 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006039 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006040 }
6041 return SQLITE_OK;
6042}
6043
6044/*
6045** Takes an already filled in unix file and alters it so all file locking
6046** will be performed on the local proxy lock file. The following fields
6047** are preserved in the locking context so that they can be restored and
6048** the unix structure properly cleaned up at close time:
6049** ->lockingContext
6050** ->pMethod
6051*/
6052static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6053 proxyLockingContext *pCtx;
6054 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6055 char *lockPath=NULL;
6056 int rc = SQLITE_OK;
6057
drh308c2a52010-05-14 11:30:18 +00006058 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006059 return SQLITE_BUSY;
6060 }
6061 proxyGetDbPathForUnixFile(pFile, dbPath);
6062 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6063 lockPath=NULL;
6064 }else{
6065 lockPath=(char *)path;
6066 }
6067
drh308c2a52010-05-14 11:30:18 +00006068 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6069 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006070
6071 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6072 if( pCtx==0 ){
6073 return SQLITE_NOMEM;
6074 }
6075 memset(pCtx, 0, sizeof(*pCtx));
6076
6077 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6078 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006079 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6080 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6081 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6082 ** (c) the file system is read-only, then enable no-locking access.
6083 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6084 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6085 */
6086 struct statfs fsInfo;
6087 struct stat conchInfo;
6088 int goLockless = 0;
6089
6090 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6091 int err = errno;
6092 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6093 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6094 }
6095 }
6096 if( goLockless ){
6097 pCtx->conchHeld = -1; /* read only FS/ lockless */
6098 rc = SQLITE_OK;
6099 }
6100 }
drh715ff302008-12-03 22:32:44 +00006101 }
6102 if( rc==SQLITE_OK && lockPath ){
6103 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6104 }
6105
6106 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006107 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6108 if( pCtx->dbPath==NULL ){
6109 rc = SQLITE_NOMEM;
6110 }
6111 }
6112 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006113 /* all memory is allocated, proxys are created and assigned,
6114 ** switch the locking context and pMethod then return.
6115 */
drh715ff302008-12-03 22:32:44 +00006116 pCtx->oldLockingContext = pFile->lockingContext;
6117 pFile->lockingContext = pCtx;
6118 pCtx->pOldMethod = pFile->pMethod;
6119 pFile->pMethod = &proxyIoMethods;
6120 }else{
6121 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006122 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006123 sqlite3_free(pCtx->conchFile);
6124 }
drhd56b1212010-08-11 06:14:15 +00006125 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006126 sqlite3_free(pCtx->conchFilePath);
6127 sqlite3_free(pCtx);
6128 }
drh308c2a52010-05-14 11:30:18 +00006129 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6130 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006131 return rc;
6132}
6133
6134
6135/*
6136** This routine handles sqlite3_file_control() calls that are specific
6137** to proxy locking.
6138*/
6139static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6140 switch( op ){
6141 case SQLITE_GET_LOCKPROXYFILE: {
6142 unixFile *pFile = (unixFile*)id;
6143 if( pFile->pMethod == &proxyIoMethods ){
6144 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6145 proxyTakeConch(pFile);
6146 if( pCtx->lockProxyPath ){
6147 *(const char **)pArg = pCtx->lockProxyPath;
6148 }else{
6149 *(const char **)pArg = ":auto: (not held)";
6150 }
6151 } else {
6152 *(const char **)pArg = NULL;
6153 }
6154 return SQLITE_OK;
6155 }
6156 case SQLITE_SET_LOCKPROXYFILE: {
6157 unixFile *pFile = (unixFile*)id;
6158 int rc = SQLITE_OK;
6159 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6160 if( pArg==NULL || (const char *)pArg==0 ){
6161 if( isProxyStyle ){
6162 /* turn off proxy locking - not supported */
6163 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6164 }else{
6165 /* turn off proxy locking - already off - NOOP */
6166 rc = SQLITE_OK;
6167 }
6168 }else{
6169 const char *proxyPath = (const char *)pArg;
6170 if( isProxyStyle ){
6171 proxyLockingContext *pCtx =
6172 (proxyLockingContext*)pFile->lockingContext;
6173 if( !strcmp(pArg, ":auto:")
6174 || (pCtx->lockProxyPath &&
6175 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6176 ){
6177 rc = SQLITE_OK;
6178 }else{
6179 rc = switchLockProxyPath(pFile, proxyPath);
6180 }
6181 }else{
6182 /* turn on proxy file locking */
6183 rc = proxyTransformUnixFile(pFile, proxyPath);
6184 }
6185 }
6186 return rc;
6187 }
6188 default: {
6189 assert( 0 ); /* The call assures that only valid opcodes are sent */
6190 }
6191 }
6192 /*NOTREACHED*/
6193 return SQLITE_ERROR;
6194}
6195
6196/*
6197** Within this division (the proxying locking implementation) the procedures
6198** above this point are all utilities. The lock-related methods of the
6199** proxy-locking sqlite3_io_method object follow.
6200*/
6201
6202
6203/*
6204** This routine checks if there is a RESERVED lock held on the specified
6205** file by this or any other process. If such a lock is held, set *pResOut
6206** to a non-zero value otherwise *pResOut is set to zero. The return value
6207** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6208*/
6209static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6210 unixFile *pFile = (unixFile*)id;
6211 int rc = proxyTakeConch(pFile);
6212 if( rc==SQLITE_OK ){
6213 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006214 if( pCtx->conchHeld>0 ){
6215 unixFile *proxy = pCtx->lockProxy;
6216 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6217 }else{ /* conchHeld < 0 is lockless */
6218 pResOut=0;
6219 }
drh715ff302008-12-03 22:32:44 +00006220 }
6221 return rc;
6222}
6223
6224/*
drh308c2a52010-05-14 11:30:18 +00006225** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006226** of the following:
6227**
6228** (1) SHARED_LOCK
6229** (2) RESERVED_LOCK
6230** (3) PENDING_LOCK
6231** (4) EXCLUSIVE_LOCK
6232**
6233** Sometimes when requesting one lock state, additional lock states
6234** are inserted in between. The locking might fail on one of the later
6235** transitions leaving the lock state different from what it started but
6236** still short of its goal. The following chart shows the allowed
6237** transitions and the inserted intermediate states:
6238**
6239** UNLOCKED -> SHARED
6240** SHARED -> RESERVED
6241** SHARED -> (PENDING) -> EXCLUSIVE
6242** RESERVED -> (PENDING) -> EXCLUSIVE
6243** PENDING -> EXCLUSIVE
6244**
6245** This routine will only increase a lock. Use the sqlite3OsUnlock()
6246** routine to lower a locking level.
6247*/
drh308c2a52010-05-14 11:30:18 +00006248static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006249 unixFile *pFile = (unixFile*)id;
6250 int rc = proxyTakeConch(pFile);
6251 if( rc==SQLITE_OK ){
6252 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006253 if( pCtx->conchHeld>0 ){
6254 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006255 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6256 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006257 }else{
6258 /* conchHeld < 0 is lockless */
6259 }
drh715ff302008-12-03 22:32:44 +00006260 }
6261 return rc;
6262}
6263
6264
6265/*
drh308c2a52010-05-14 11:30:18 +00006266** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006267** must be either NO_LOCK or SHARED_LOCK.
6268**
6269** If the locking level of the file descriptor is already at or below
6270** the requested locking level, this routine is a no-op.
6271*/
drh308c2a52010-05-14 11:30:18 +00006272static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006273 unixFile *pFile = (unixFile*)id;
6274 int rc = proxyTakeConch(pFile);
6275 if( rc==SQLITE_OK ){
6276 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006277 if( pCtx->conchHeld>0 ){
6278 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006279 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6280 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006281 }else{
6282 /* conchHeld < 0 is lockless */
6283 }
drh715ff302008-12-03 22:32:44 +00006284 }
6285 return rc;
6286}
6287
6288/*
6289** Close a file that uses proxy locks.
6290*/
6291static int proxyClose(sqlite3_file *id) {
6292 if( id ){
6293 unixFile *pFile = (unixFile*)id;
6294 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6295 unixFile *lockProxy = pCtx->lockProxy;
6296 unixFile *conchFile = pCtx->conchFile;
6297 int rc = SQLITE_OK;
6298
6299 if( lockProxy ){
6300 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6301 if( rc ) return rc;
6302 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6303 if( rc ) return rc;
6304 sqlite3_free(lockProxy);
6305 pCtx->lockProxy = 0;
6306 }
6307 if( conchFile ){
6308 if( pCtx->conchHeld ){
6309 rc = proxyReleaseConch(pFile);
6310 if( rc ) return rc;
6311 }
6312 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6313 if( rc ) return rc;
6314 sqlite3_free(conchFile);
6315 }
drhd56b1212010-08-11 06:14:15 +00006316 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006317 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006318 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006319 /* restore the original locking context and pMethod then close it */
6320 pFile->lockingContext = pCtx->oldLockingContext;
6321 pFile->pMethod = pCtx->pOldMethod;
6322 sqlite3_free(pCtx);
6323 return pFile->pMethod->xClose(id);
6324 }
6325 return SQLITE_OK;
6326}
6327
6328
6329
drhd2cb50b2009-01-09 21:41:17 +00006330#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006331/*
6332** The proxy locking style is intended for use with AFP filesystems.
6333** And since AFP is only supported on MacOSX, the proxy locking is also
6334** restricted to MacOSX.
6335**
6336**
6337******************* End of the proxy lock implementation **********************
6338******************************************************************************/
6339
drh734c9862008-11-28 15:37:20 +00006340/*
danielk1977e339d652008-06-28 11:23:00 +00006341** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006342**
6343** This routine registers all VFS implementations for unix-like operating
6344** systems. This routine, and the sqlite3_os_end() routine that follows,
6345** should be the only routines in this file that are visible from other
6346** files.
drh6b9d6dd2008-12-03 19:34:47 +00006347**
6348** This routine is called once during SQLite initialization and by a
6349** single thread. The memory allocation and mutex subsystems have not
6350** necessarily been initialized when this routine is called, and so they
6351** should not be used.
drh153c62c2007-08-24 03:51:33 +00006352*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006353int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006354 /*
6355 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006356 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6357 ** to the "finder" function. (pAppData is a pointer to a pointer because
6358 ** silly C90 rules prohibit a void* from being cast to a function pointer
6359 ** and so we have to go through the intermediate pointer to avoid problems
6360 ** when compiling with -pedantic-errors on GCC.)
6361 **
6362 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006363 ** finder-function. The finder-function returns a pointer to the
6364 ** sqlite_io_methods object that implements the desired locking
6365 ** behaviors. See the division above that contains the IOMETHODS
6366 ** macro for addition information on finder-functions.
6367 **
6368 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6369 ** object. But the "autolockIoFinder" available on MacOSX does a little
6370 ** more than that; it looks at the filesystem type that hosts the
6371 ** database file and tries to choose an locking method appropriate for
6372 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006373 */
drh7708e972008-11-29 00:56:52 +00006374 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006375 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006376 sizeof(unixFile), /* szOsFile */ \
6377 MAX_PATHNAME, /* mxPathname */ \
6378 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006379 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006380 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006381 unixOpen, /* xOpen */ \
6382 unixDelete, /* xDelete */ \
6383 unixAccess, /* xAccess */ \
6384 unixFullPathname, /* xFullPathname */ \
6385 unixDlOpen, /* xDlOpen */ \
6386 unixDlError, /* xDlError */ \
6387 unixDlSym, /* xDlSym */ \
6388 unixDlClose, /* xDlClose */ \
6389 unixRandomness, /* xRandomness */ \
6390 unixSleep, /* xSleep */ \
6391 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006392 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006393 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006394 }
6395
drh6b9d6dd2008-12-03 19:34:47 +00006396 /*
6397 ** All default VFSes for unix are contained in the following array.
6398 **
6399 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6400 ** by the SQLite core when the VFS is registered. So the following
6401 ** array cannot be const.
6402 */
danielk1977e339d652008-06-28 11:23:00 +00006403 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006404#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006405 UNIXVFS("unix", autolockIoFinder ),
6406#else
6407 UNIXVFS("unix", posixIoFinder ),
6408#endif
6409 UNIXVFS("unix-none", nolockIoFinder ),
6410 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006411#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006412 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006413#endif
6414#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006415 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006416#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006417 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006418#endif
chw78a13182009-04-07 05:35:03 +00006419#endif
drhd2cb50b2009-01-09 21:41:17 +00006420#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006421 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006422 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006423 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006424#endif
drh153c62c2007-08-24 03:51:33 +00006425 };
drh6b9d6dd2008-12-03 19:34:47 +00006426 unsigned int i; /* Loop counter */
6427
6428 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006429 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006430 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006431 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006432 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006433}
danielk1977e339d652008-06-28 11:23:00 +00006434
6435/*
drh6b9d6dd2008-12-03 19:34:47 +00006436** Shutdown the operating system interface.
6437**
6438** Some operating systems might need to do some cleanup in this routine,
6439** to release dynamically allocated objects. But not on unix.
6440** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006441*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006442int sqlite3_os_end(void){
6443 return SQLITE_OK;
6444}
drhdce8bdb2007-08-16 13:01:44 +00006445
danielk197729bafea2008-06-26 10:41:19 +00006446#endif /* SQLITE_OS_UNIX */