blob: b2374beec320abcc33245d74967449357a770c0e [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*/
drh0e9365c2011-03-02 02:08:13 +0000770#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
771static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000772 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 */
drh0e9365c2011-03-02 02:08:13 +0000778 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000779
780 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
781 ** the strerror() function to obtain the human-readable error message
782 ** equivalent to errno. Otherwise, use strerror_r().
783 */
784#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
785 char aErr[80];
786 memset(aErr, 0, sizeof(aErr));
787 zErr = aErr;
788
789 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
790 ** assume that the system provides the the GNU version of strerror_r() that
791 ** returns a pointer to a buffer containing the error message. That pointer
792 ** may point to aErr[], or it may point to some static storage somewhere.
793 ** Otherwise, assume that the system provides the POSIX version of
794 ** strerror_r(), which always writes an error message into aErr[].
795 **
796 ** If the code incorrectly assumes that it is the POSIX version that is
797 ** available, the error message will often be an empty string. Not a
798 ** huge problem. Incorrectly concluding that the GNU version is available
799 ** could lead to a segfault though.
800 */
801#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
802 zErr =
803# endif
drh0e9365c2011-03-02 02:08:13 +0000804 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000805
806#elif SQLITE_THREADSAFE
807 /* This is a threadsafe build, but strerror_r() is not available. */
808 zErr = "";
809#else
810 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000811 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000812#endif
813
814 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000815 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000816 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000817 "os_unix.c:%d: (%d) %s(%s) - %s",
818 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000819 );
820
821 return errcode;
822}
823
drh0e9365c2011-03-02 02:08:13 +0000824/*
825** Close a file descriptor.
826**
827** We assume that close() almost always works, since it is only in a
828** very sick application or on a very sick platform that it might fail.
829** If it does fail, simply leak the file descriptor, but do log the
830** error.
831**
832** Note that it is not safe to retry close() after EINTR since the
833** file descriptor might have already been reused by another thread.
834** So we don't even try to recover from an EINTR. Just log the error
835** and move on.
836*/
837static void robust_close(unixFile *pFile, int h, int lineno){
838 if( close(h) ){
839 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
840 pFile ? pFile->zPath : 0, lineno);
841 }
842}
dane18d4952011-02-21 11:46:24 +0000843
844/*
danb0ac3e32010-06-16 10:55:42 +0000845** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +0000846*/
drh0e9365c2011-03-02 02:08:13 +0000847static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +0000848 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +0000849 UnixUnusedFd *p;
850 UnixUnusedFd *pNext;
851 for(p=pInode->pUnused; p; p=pNext){
852 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +0000853 robust_close(pFile, p->fd, __LINE__);
854 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +0000855 }
drh0e9365c2011-03-02 02:08:13 +0000856 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +0000857}
858
859/*
drh8af6c222010-05-14 12:43:01 +0000860** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000861**
862** The mutex entered using the unixEnterMutex() function must be held
863** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000864*/
danb0ac3e32010-06-16 10:55:42 +0000865static void releaseInodeInfo(unixFile *pFile){
866 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000867 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000868 if( pInode ){
869 pInode->nRef--;
870 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000871 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000872 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000873 if( pInode->pPrev ){
874 assert( pInode->pPrev->pNext==pInode );
875 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000876 }else{
drh8af6c222010-05-14 12:43:01 +0000877 assert( inodeList==pInode );
878 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000879 }
drh8af6c222010-05-14 12:43:01 +0000880 if( pInode->pNext ){
881 assert( pInode->pNext->pPrev==pInode );
882 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000883 }
drh8af6c222010-05-14 12:43:01 +0000884 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000885 }
drhbbd42a62004-05-22 17:41:58 +0000886 }
887}
888
889/*
drh8af6c222010-05-14 12:43:01 +0000890** Given a file descriptor, locate the unixInodeInfo object that
891** describes that file descriptor. Create a new one if necessary. The
892** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000893**
dan9359c7b2009-08-21 08:29:10 +0000894** The mutex entered using the unixEnterMutex() function must be held
895** when this function is called.
896**
drh6c7d5c52008-11-21 20:32:33 +0000897** Return an appropriate error code.
898*/
drh8af6c222010-05-14 12:43:01 +0000899static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000900 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000901 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000902){
903 int rc; /* System call return code */
904 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000905 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
906 struct stat statbuf; /* Low-level file information */
907 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000908
dan9359c7b2009-08-21 08:29:10 +0000909 assert( unixMutexHeld() );
910
drh6c7d5c52008-11-21 20:32:33 +0000911 /* Get low-level information about the file that we can used to
912 ** create a unique name for the file.
913 */
914 fd = pFile->h;
915 rc = fstat(fd, &statbuf);
916 if( rc!=0 ){
917 pFile->lastErrno = errno;
918#ifdef EOVERFLOW
919 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
920#endif
921 return SQLITE_IOERR;
922 }
923
drheb0d74f2009-02-03 15:27:02 +0000924#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000925 /* On OS X on an msdos filesystem, the inode number is reported
926 ** incorrectly for zero-size files. See ticket #3260. To work
927 ** around this problem (we consider it a bug in OS X, not SQLite)
928 ** we always increase the file size to 1 by writing a single byte
929 ** prior to accessing the inode number. The one byte written is
930 ** an ASCII 'S' character which also happens to be the first byte
931 ** in the header of every SQLite database. In this way, if there
932 ** is a race condition such that another thread has already populated
933 ** the first page of the database, no damage is done.
934 */
drh7ed97b92010-01-20 13:07:21 +0000935 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhff812312011-02-23 13:33:46 +0000936 do{ rc = write(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +0000937 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000938 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000939 return SQLITE_IOERR;
940 }
drh6c7d5c52008-11-21 20:32:33 +0000941 rc = fstat(fd, &statbuf);
942 if( rc!=0 ){
943 pFile->lastErrno = errno;
944 return SQLITE_IOERR;
945 }
946 }
drheb0d74f2009-02-03 15:27:02 +0000947#endif
drh6c7d5c52008-11-21 20:32:33 +0000948
drh8af6c222010-05-14 12:43:01 +0000949 memset(&fileId, 0, sizeof(fileId));
950 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000951#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000952 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000953#else
drh8af6c222010-05-14 12:43:01 +0000954 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000955#endif
drh8af6c222010-05-14 12:43:01 +0000956 pInode = inodeList;
957 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
958 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000959 }
drh8af6c222010-05-14 12:43:01 +0000960 if( pInode==0 ){
961 pInode = sqlite3_malloc( sizeof(*pInode) );
962 if( pInode==0 ){
963 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000964 }
drh8af6c222010-05-14 12:43:01 +0000965 memset(pInode, 0, sizeof(*pInode));
966 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
967 pInode->nRef = 1;
968 pInode->pNext = inodeList;
969 pInode->pPrev = 0;
970 if( inodeList ) inodeList->pPrev = pInode;
971 inodeList = pInode;
972 }else{
973 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000974 }
drh8af6c222010-05-14 12:43:01 +0000975 *ppInode = pInode;
976 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000977}
drh6c7d5c52008-11-21 20:32:33 +0000978
aswift5b1a2562008-08-22 00:22:35 +0000979
980/*
danielk197713adf8a2004-06-03 16:08:41 +0000981** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000982** file by this or any other process. If such a lock is held, set *pResOut
983** to a non-zero value otherwise *pResOut is set to zero. The return value
984** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000985*/
danielk1977861f7452008-06-05 11:39:11 +0000986static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000987 int rc = SQLITE_OK;
988 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000989 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000990
danielk1977861f7452008-06-05 11:39:11 +0000991 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
992
drh054889e2005-11-30 03:20:31 +0000993 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000994 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000995
996 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000997 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000998 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000999 }
1000
drh2ac3ee92004-06-07 16:27:46 +00001001 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001002 */
danielk197709480a92009-02-09 05:32:32 +00001003#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001004 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001005 struct flock lock;
1006 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001007 lock.l_start = RESERVED_BYTE;
1008 lock.l_len = 1;
1009 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001010 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1011 int tErrno = errno;
1012 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1013 pFile->lastErrno = tErrno;
1014 } else if( lock.l_type!=F_UNLCK ){
1015 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001016 }
1017 }
danielk197709480a92009-02-09 05:32:32 +00001018#endif
danielk197713adf8a2004-06-03 16:08:41 +00001019
drh6c7d5c52008-11-21 20:32:33 +00001020 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001021 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001022
aswift5b1a2562008-08-22 00:22:35 +00001023 *pResOut = reserved;
1024 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001025}
1026
1027/*
drh308c2a52010-05-14 11:30:18 +00001028** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001029** of the following:
1030**
drh2ac3ee92004-06-07 16:27:46 +00001031** (1) SHARED_LOCK
1032** (2) RESERVED_LOCK
1033** (3) PENDING_LOCK
1034** (4) EXCLUSIVE_LOCK
1035**
drhb3e04342004-06-08 00:47:47 +00001036** Sometimes when requesting one lock state, additional lock states
1037** are inserted in between. The locking might fail on one of the later
1038** transitions leaving the lock state different from what it started but
1039** still short of its goal. The following chart shows the allowed
1040** transitions and the inserted intermediate states:
1041**
1042** UNLOCKED -> SHARED
1043** SHARED -> RESERVED
1044** SHARED -> (PENDING) -> EXCLUSIVE
1045** RESERVED -> (PENDING) -> EXCLUSIVE
1046** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001047**
drha6abd042004-06-09 17:37:22 +00001048** This routine will only increase a lock. Use the sqlite3OsUnlock()
1049** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001050*/
drh308c2a52010-05-14 11:30:18 +00001051static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001052 /* The following describes the implementation of the various locks and
1053 ** lock transitions in terms of the POSIX advisory shared and exclusive
1054 ** lock primitives (called read-locks and write-locks below, to avoid
1055 ** confusion with SQLite lock names). The algorithms are complicated
1056 ** slightly in order to be compatible with windows systems simultaneously
1057 ** accessing the same database file, in case that is ever required.
1058 **
1059 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1060 ** byte', each single bytes at well known offsets, and the 'shared byte
1061 ** range', a range of 510 bytes at a well known offset.
1062 **
1063 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1064 ** byte'. If this is successful, a random byte from the 'shared byte
1065 ** range' is read-locked and the lock on the 'pending byte' released.
1066 **
danielk197790ba3bd2004-06-25 08:32:25 +00001067 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1068 ** A RESERVED lock is implemented by grabbing a write-lock on the
1069 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001070 **
1071 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001072 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1073 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1074 ** obtained, but existing SHARED locks are allowed to persist. A process
1075 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1076 ** This property is used by the algorithm for rolling back a journal file
1077 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001078 **
danielk197790ba3bd2004-06-25 08:32:25 +00001079 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1080 ** implemented by obtaining a write-lock on the entire 'shared byte
1081 ** range'. Since all other locks require a read-lock on one of the bytes
1082 ** within this range, this ensures that no other locks are held on the
1083 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001084 **
1085 ** The reason a single byte cannot be used instead of the 'shared byte
1086 ** range' is that some versions of windows do not support read-locks. By
1087 ** locking a random byte from a range, concurrent SHARED locks may exist
1088 ** even if the locking primitive used is always a write-lock.
1089 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001090 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001091 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001092 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001093 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001094 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001095 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001096
drh054889e2005-11-30 03:20:31 +00001097 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001098 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1099 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001100 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001101
1102 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001103 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001104 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001105 */
drh308c2a52010-05-14 11:30:18 +00001106 if( pFile->eFileLock>=eFileLock ){
1107 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1108 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001109 return SQLITE_OK;
1110 }
1111
drh0c2694b2009-09-03 16:23:44 +00001112 /* Make sure the locking sequence is correct.
1113 ** (1) We never move from unlocked to anything higher than shared lock.
1114 ** (2) SQLite never explicitly requests a pendig lock.
1115 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001116 */
drh308c2a52010-05-14 11:30:18 +00001117 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1118 assert( eFileLock!=PENDING_LOCK );
1119 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001120
drh8af6c222010-05-14 12:43:01 +00001121 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001122 */
drh6c7d5c52008-11-21 20:32:33 +00001123 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001124 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001125
danielk1977ad94b582007-08-20 06:44:22 +00001126 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001127 ** handle that precludes the requested lock, return BUSY.
1128 */
drh8af6c222010-05-14 12:43:01 +00001129 if( (pFile->eFileLock!=pInode->eFileLock &&
1130 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001131 ){
1132 rc = SQLITE_BUSY;
1133 goto end_lock;
1134 }
1135
1136 /* If a SHARED lock is requested, and some thread using this PID already
1137 ** has a SHARED or RESERVED lock, then increment reference counts and
1138 ** return SQLITE_OK.
1139 */
drh308c2a52010-05-14 11:30:18 +00001140 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001141 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001142 assert( eFileLock==SHARED_LOCK );
1143 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001144 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001145 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001146 pInode->nShared++;
1147 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001148 goto end_lock;
1149 }
1150
danielk19779a1d0ab2004-06-01 14:09:28 +00001151
drh3cde3bb2004-06-12 02:17:14 +00001152 /* A PENDING lock is needed before acquiring a SHARED lock and before
1153 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1154 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001155 */
drh0c2694b2009-09-03 16:23:44 +00001156 lock.l_len = 1L;
1157 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001158 if( eFileLock==SHARED_LOCK
1159 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001160 ){
drh308c2a52010-05-14 11:30:18 +00001161 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001162 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001163 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001164 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001165 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001166 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1167 if( IS_LOCK_ERROR(rc) ){
1168 pFile->lastErrno = tErrno;
1169 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001170 goto end_lock;
1171 }
drh3cde3bb2004-06-12 02:17:14 +00001172 }
1173
1174
1175 /* If control gets to this point, then actually go ahead and make
1176 ** operating system calls for the specified lock.
1177 */
drh308c2a52010-05-14 11:30:18 +00001178 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001179 assert( pInode->nShared==0 );
1180 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001181
drh2ac3ee92004-06-07 16:27:46 +00001182 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001183 lock.l_start = SHARED_FIRST;
1184 lock.l_len = SHARED_SIZE;
1185 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1186 tErrno = errno;
1187 }
drh2ac3ee92004-06-07 16:27:46 +00001188 /* Drop the temporary PENDING lock */
1189 lock.l_start = PENDING_BYTE;
1190 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001191 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001192 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001193 if( s != -1 ){
1194 /* This could happen with a network mount */
1195 tErrno = errno;
1196 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1197 if( IS_LOCK_ERROR(rc) ){
1198 pFile->lastErrno = tErrno;
1199 }
1200 goto end_lock;
1201 }
drh2b4b5962005-06-15 17:47:55 +00001202 }
drhe2396a12007-03-29 20:19:58 +00001203 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001204 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1205 if( IS_LOCK_ERROR(rc) ){
1206 pFile->lastErrno = tErrno;
1207 }
drhbbd42a62004-05-22 17:41:58 +00001208 }else{
drh308c2a52010-05-14 11:30:18 +00001209 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001210 pInode->nLock++;
1211 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001212 }
drh8af6c222010-05-14 12:43:01 +00001213 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001214 /* We are trying for an exclusive lock but another thread in this
1215 ** same process is still holding a shared lock. */
1216 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001217 }else{
drh3cde3bb2004-06-12 02:17:14 +00001218 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001219 ** assumed that there is a SHARED or greater lock on the file
1220 ** already.
1221 */
drh308c2a52010-05-14 11:30:18 +00001222 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001224 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001225 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001226 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001227 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001229 lock.l_start = SHARED_FIRST;
1230 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001231 break;
1232 default:
1233 assert(0);
1234 }
drh7ed97b92010-01-20 13:07:21 +00001235 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001236 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001237 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001238 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1239 if( IS_LOCK_ERROR(rc) ){
1240 pFile->lastErrno = tErrno;
1241 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001242 }
drhbbd42a62004-05-22 17:41:58 +00001243 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001244
drh8f941bc2009-01-14 23:03:40 +00001245
1246#ifndef NDEBUG
1247 /* Set up the transaction-counter change checking flags when
1248 ** transitioning from a SHARED to a RESERVED lock. The change
1249 ** from SHARED to RESERVED marks the beginning of a normal
1250 ** write operation (not a hot journal rollback).
1251 */
1252 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001253 && pFile->eFileLock<=SHARED_LOCK
1254 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001255 ){
1256 pFile->transCntrChng = 0;
1257 pFile->dbUpdate = 0;
1258 pFile->inNormalWrite = 1;
1259 }
1260#endif
1261
1262
danielk1977ecb2a962004-06-02 06:30:16 +00001263 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001264 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001265 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001266 }else if( eFileLock==EXCLUSIVE_LOCK ){
1267 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001268 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001269 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001270
1271end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001272 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001273 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1274 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001275 return rc;
1276}
1277
1278/*
dan08da86a2009-08-21 17:18:03 +00001279** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001280** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001281*/
1282static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001283 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001284 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001285 p->pNext = pInode->pUnused;
1286 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001287 pFile->h = -1;
1288 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001289}
1290
1291/*
drh308c2a52010-05-14 11:30:18 +00001292** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001293** must be either NO_LOCK or SHARED_LOCK.
1294**
1295** If the locking level of the file descriptor is already at or below
1296** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001297**
1298** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1299** the byte range is divided into 2 parts and the first part is unlocked then
1300** set to a read lock, then the other part is simply unlocked. This works
1301** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1302** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001303*/
drh308c2a52010-05-14 11:30:18 +00001304static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001305 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001306 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001307 struct flock lock;
1308 int rc = SQLITE_OK;
1309 int h;
drh0c2694b2009-09-03 16:23:44 +00001310 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001311
drh054889e2005-11-30 03:20:31 +00001312 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001313 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001314 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001315 getpid()));
drha6abd042004-06-09 17:37:22 +00001316
drh308c2a52010-05-14 11:30:18 +00001317 assert( eFileLock<=SHARED_LOCK );
1318 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001319 return SQLITE_OK;
1320 }
drh6c7d5c52008-11-21 20:32:33 +00001321 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001322 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001323 pInode = pFile->pInode;
1324 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001325 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001326 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001327 SimulateIOErrorBenign(1);
1328 SimulateIOError( h=(-1) )
1329 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001330
1331#ifndef NDEBUG
1332 /* When reducing a lock such that other processes can start
1333 ** reading the database file again, make sure that the
1334 ** transaction counter was updated if any part of the database
1335 ** file changed. If the transaction counter is not updated,
1336 ** other connections to the same file might not realize that
1337 ** the file has changed and hence might not know to flush their
1338 ** cache. The use of a stale cache can lead to database corruption.
1339 */
dan7c246102010-04-12 19:00:29 +00001340#if 0
drh8f941bc2009-01-14 23:03:40 +00001341 assert( pFile->inNormalWrite==0
1342 || pFile->dbUpdate==0
1343 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001344#endif
drh8f941bc2009-01-14 23:03:40 +00001345 pFile->inNormalWrite = 0;
1346#endif
1347
drh7ed97b92010-01-20 13:07:21 +00001348 /* downgrading to a shared lock on NFS involves clearing the write lock
1349 ** before establishing the readlock - to avoid a race condition we downgrade
1350 ** the lock in 2 blocks, so that part of the range will be covered by a
1351 ** write lock until the rest is covered by a read lock:
1352 ** 1: [WWWWW]
1353 ** 2: [....W]
1354 ** 3: [RRRRW]
1355 ** 4: [RRRR.]
1356 */
drh308c2a52010-05-14 11:30:18 +00001357 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001358
1359#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001360 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001361 assert( handleNFSUnlock==0 );
1362#endif
1363#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001364 if( handleNFSUnlock ){
1365 off_t divSize = SHARED_SIZE - 1;
1366
1367 lock.l_type = F_UNLCK;
1368 lock.l_whence = SEEK_SET;
1369 lock.l_start = SHARED_FIRST;
1370 lock.l_len = divSize;
1371 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001372 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001373 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1374 if( IS_LOCK_ERROR(rc) ){
1375 pFile->lastErrno = tErrno;
1376 }
1377 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001378 }
drh7ed97b92010-01-20 13:07:21 +00001379 lock.l_type = F_RDLCK;
1380 lock.l_whence = SEEK_SET;
1381 lock.l_start = SHARED_FIRST;
1382 lock.l_len = divSize;
1383 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001384 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001385 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1386 if( IS_LOCK_ERROR(rc) ){
1387 pFile->lastErrno = tErrno;
1388 }
1389 goto end_unlock;
1390 }
1391 lock.l_type = F_UNLCK;
1392 lock.l_whence = SEEK_SET;
1393 lock.l_start = SHARED_FIRST+divSize;
1394 lock.l_len = SHARED_SIZE-divSize;
1395 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001396 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001397 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1398 if( IS_LOCK_ERROR(rc) ){
1399 pFile->lastErrno = tErrno;
1400 }
1401 goto end_unlock;
1402 }
drh30f776f2011-02-25 03:25:07 +00001403 }else
1404#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1405 {
drh7ed97b92010-01-20 13:07:21 +00001406 lock.l_type = F_RDLCK;
1407 lock.l_whence = SEEK_SET;
1408 lock.l_start = SHARED_FIRST;
1409 lock.l_len = SHARED_SIZE;
1410 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001411 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001412 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1413 if( IS_LOCK_ERROR(rc) ){
1414 pFile->lastErrno = tErrno;
1415 }
1416 goto end_unlock;
1417 }
drh9c105bb2004-10-02 20:38:28 +00001418 }
1419 }
drhbbd42a62004-05-22 17:41:58 +00001420 lock.l_type = F_UNLCK;
1421 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001422 lock.l_start = PENDING_BYTE;
1423 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001424 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001425 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001426 }else{
drh0c2694b2009-09-03 16:23:44 +00001427 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001428 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1429 if( IS_LOCK_ERROR(rc) ){
1430 pFile->lastErrno = tErrno;
1431 }
drhcd731cf2009-03-28 23:23:02 +00001432 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001433 }
drhbbd42a62004-05-22 17:41:58 +00001434 }
drh308c2a52010-05-14 11:30:18 +00001435 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001436 /* Decrement the shared lock counter. Release the lock using an
1437 ** OS call only when all threads in this same process have released
1438 ** the lock.
1439 */
drh8af6c222010-05-14 12:43:01 +00001440 pInode->nShared--;
1441 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001442 lock.l_type = F_UNLCK;
1443 lock.l_whence = SEEK_SET;
1444 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001445 SimulateIOErrorBenign(1);
1446 SimulateIOError( h=(-1) )
1447 SimulateIOErrorBenign(0);
1448 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001449 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001450 }else{
drh0c2694b2009-09-03 16:23:44 +00001451 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001452 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001453 if( IS_LOCK_ERROR(rc) ){
1454 pFile->lastErrno = tErrno;
1455 }
drh8af6c222010-05-14 12:43:01 +00001456 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001457 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001458 }
drha6abd042004-06-09 17:37:22 +00001459 }
1460
drhbbd42a62004-05-22 17:41:58 +00001461 /* Decrement the count of locks against this same file. When the
1462 ** count reaches zero, close any other file descriptors whose close
1463 ** was deferred because of outstanding locks.
1464 */
drh8af6c222010-05-14 12:43:01 +00001465 pInode->nLock--;
1466 assert( pInode->nLock>=0 );
1467 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001468 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001469 }
1470 }
aswift5b1a2562008-08-22 00:22:35 +00001471
1472end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001473 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001474 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001475 return rc;
drhbbd42a62004-05-22 17:41:58 +00001476}
1477
1478/*
drh308c2a52010-05-14 11:30:18 +00001479** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001480** must be either NO_LOCK or SHARED_LOCK.
1481**
1482** If the locking level of the file descriptor is already at or below
1483** the requested locking level, this routine is a no-op.
1484*/
drh308c2a52010-05-14 11:30:18 +00001485static int unixUnlock(sqlite3_file *id, int eFileLock){
1486 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001487}
1488
1489/*
danielk1977e339d652008-06-28 11:23:00 +00001490** This function performs the parts of the "close file" operation
1491** common to all locking schemes. It closes the directory and file
1492** handles, if they are valid, and sets all fields of the unixFile
1493** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001494**
1495** It is *not* necessary to hold the mutex when this routine is called,
1496** even on VxWorks. A mutex will be acquired on VxWorks by the
1497** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001498*/
1499static int closeUnixFile(sqlite3_file *id){
1500 unixFile *pFile = (unixFile*)id;
1501 if( pFile ){
1502 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001503 robust_close(pFile, pFile->dirfd, __LINE__);
1504 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001505 }
1506 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001507 robust_close(pFile, pFile->h, __LINE__);
1508 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001509 }
drh6c7d5c52008-11-21 20:32:33 +00001510#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001511 if( pFile->pId ){
1512 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001513 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001514 }
drh107886a2008-11-21 22:21:50 +00001515 vxworksReleaseFileId(pFile->pId);
1516 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001517 }
1518#endif
drhff59a112010-05-14 20:15:51 +00001519 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001520 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001521 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001522 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001523 }
1524 return SQLITE_OK;
1525}
1526
1527/*
danielk1977e3026632004-06-22 11:29:02 +00001528** Close a file.
1529*/
danielk197762079062007-08-15 17:08:46 +00001530static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001531 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001532 if( id ){
1533 unixFile *pFile = (unixFile *)id;
1534 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001535 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001536 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001537 /* If there are outstanding locks, do not actually close the file just
1538 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001539 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001540 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001541 */
dan08da86a2009-08-21 17:18:03 +00001542 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001543 }
danb0ac3e32010-06-16 10:55:42 +00001544 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001545 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001546 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001547 }
aswiftaebf4132008-11-21 00:10:35 +00001548 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001549}
1550
drh734c9862008-11-28 15:37:20 +00001551/************** End of the posix advisory lock implementation *****************
1552******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001553
drh734c9862008-11-28 15:37:20 +00001554/******************************************************************************
1555****************************** No-op Locking **********************************
1556**
1557** Of the various locking implementations available, this is by far the
1558** simplest: locking is ignored. No attempt is made to lock the database
1559** file for reading or writing.
1560**
1561** This locking mode is appropriate for use on read-only databases
1562** (ex: databases that are burned into CD-ROM, for example.) It can
1563** also be used if the application employs some external mechanism to
1564** prevent simultaneous access of the same database by two or more
1565** database connections. But there is a serious risk of database
1566** corruption if this locking mode is used in situations where multiple
1567** database connections are accessing the same database file at the same
1568** time and one or more of those connections are writing.
1569*/
drhbfe66312006-10-03 17:40:40 +00001570
drh734c9862008-11-28 15:37:20 +00001571static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1572 UNUSED_PARAMETER(NotUsed);
1573 *pResOut = 0;
1574 return SQLITE_OK;
1575}
drh734c9862008-11-28 15:37:20 +00001576static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1577 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1578 return SQLITE_OK;
1579}
drh734c9862008-11-28 15:37:20 +00001580static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1581 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1582 return SQLITE_OK;
1583}
1584
1585/*
drh9b35ea62008-11-29 02:20:26 +00001586** Close the file.
drh734c9862008-11-28 15:37:20 +00001587*/
1588static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001589 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001590}
1591
1592/******************* End of the no-op lock implementation *********************
1593******************************************************************************/
1594
1595/******************************************************************************
1596************************* Begin dot-file Locking ******************************
1597**
drh0c2694b2009-09-03 16:23:44 +00001598** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001599** files in order to control access to the database. This works on just
1600** about every filesystem imaginable. But there are serious downsides:
1601**
1602** (1) There is zero concurrency. A single reader blocks all other
1603** connections from reading or writing the database.
1604**
1605** (2) An application crash or power loss can leave stale lock files
1606** sitting around that need to be cleared manually.
1607**
1608** Nevertheless, a dotlock is an appropriate locking mode for use if no
1609** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001610**
1611** Dotfile locking works by creating a file in the same directory as the
1612** database and with the same name but with a ".lock" extension added.
1613** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1614** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001615*/
1616
1617/*
1618** The file suffix added to the data base filename in order to create the
1619** lock file.
1620*/
1621#define DOTLOCK_SUFFIX ".lock"
1622
drh7708e972008-11-29 00:56:52 +00001623/*
1624** This routine checks if there is a RESERVED lock held on the specified
1625** file by this or any other process. If such a lock is held, set *pResOut
1626** to a non-zero value otherwise *pResOut is set to zero. The return value
1627** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1628**
1629** In dotfile locking, either a lock exists or it does not. So in this
1630** variation of CheckReservedLock(), *pResOut is set to true if any lock
1631** is held on the file and false if the file is unlocked.
1632*/
drh734c9862008-11-28 15:37:20 +00001633static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1634 int rc = SQLITE_OK;
1635 int reserved = 0;
1636 unixFile *pFile = (unixFile*)id;
1637
1638 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1639
1640 assert( pFile );
1641
1642 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001643 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001644 /* Either this connection or some other connection in the same process
1645 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001646 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001647 }else{
1648 /* The lock is held if and only if the lockfile exists */
1649 const char *zLockFile = (const char*)pFile->lockingContext;
1650 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001651 }
drh308c2a52010-05-14 11:30:18 +00001652 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001653 *pResOut = reserved;
1654 return rc;
1655}
1656
drh7708e972008-11-29 00:56:52 +00001657/*
drh308c2a52010-05-14 11:30:18 +00001658** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001659** of the following:
1660**
1661** (1) SHARED_LOCK
1662** (2) RESERVED_LOCK
1663** (3) PENDING_LOCK
1664** (4) EXCLUSIVE_LOCK
1665**
1666** Sometimes when requesting one lock state, additional lock states
1667** are inserted in between. The locking might fail on one of the later
1668** transitions leaving the lock state different from what it started but
1669** still short of its goal. The following chart shows the allowed
1670** transitions and the inserted intermediate states:
1671**
1672** UNLOCKED -> SHARED
1673** SHARED -> RESERVED
1674** SHARED -> (PENDING) -> EXCLUSIVE
1675** RESERVED -> (PENDING) -> EXCLUSIVE
1676** PENDING -> EXCLUSIVE
1677**
1678** This routine will only increase a lock. Use the sqlite3OsUnlock()
1679** routine to lower a locking level.
1680**
1681** With dotfile locking, we really only support state (4): EXCLUSIVE.
1682** But we track the other locking levels internally.
1683*/
drh308c2a52010-05-14 11:30:18 +00001684static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001685 unixFile *pFile = (unixFile*)id;
1686 int fd;
1687 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001688 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001689
drh7708e972008-11-29 00:56:52 +00001690
1691 /* If we have any lock, then the lock file already exists. All we have
1692 ** to do is adjust our internal record of the lock level.
1693 */
drh308c2a52010-05-14 11:30:18 +00001694 if( pFile->eFileLock > NO_LOCK ){
1695 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001696#if !OS_VXWORKS
1697 /* Always update the timestamp on the old file */
1698 utimes(zLockFile, NULL);
1699#endif
drh7708e972008-11-29 00:56:52 +00001700 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001701 }
1702
1703 /* grab an exclusive lock */
1704 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1705 if( fd<0 ){
1706 /* failed to open/create the file, someone else may have stolen the lock */
1707 int tErrno = errno;
1708 if( EEXIST == tErrno ){
1709 rc = SQLITE_BUSY;
1710 } else {
1711 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1712 if( IS_LOCK_ERROR(rc) ){
1713 pFile->lastErrno = tErrno;
1714 }
1715 }
drh7708e972008-11-29 00:56:52 +00001716 return rc;
drh734c9862008-11-28 15:37:20 +00001717 }
drh0e9365c2011-03-02 02:08:13 +00001718 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001719
1720 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001721 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001722 return rc;
1723}
1724
drh7708e972008-11-29 00:56:52 +00001725/*
drh308c2a52010-05-14 11:30:18 +00001726** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001727** must be either NO_LOCK or SHARED_LOCK.
1728**
1729** If the locking level of the file descriptor is already at or below
1730** the requested locking level, this routine is a no-op.
1731**
1732** When the locking level reaches NO_LOCK, delete the lock file.
1733*/
drh308c2a52010-05-14 11:30:18 +00001734static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001735 unixFile *pFile = (unixFile*)id;
1736 char *zLockFile = (char *)pFile->lockingContext;
1737
1738 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001739 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1740 pFile->eFileLock, getpid()));
1741 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001742
1743 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001744 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001745 return SQLITE_OK;
1746 }
drh7708e972008-11-29 00:56:52 +00001747
1748 /* To downgrade to shared, simply update our internal notion of the
1749 ** lock state. No need to mess with the file on disk.
1750 */
drh308c2a52010-05-14 11:30:18 +00001751 if( eFileLock==SHARED_LOCK ){
1752 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001753 return SQLITE_OK;
1754 }
1755
drh7708e972008-11-29 00:56:52 +00001756 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001757 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001758 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001759 int rc = 0;
1760 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001761 if( ENOENT != tErrno ){
1762 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1763 }
1764 if( IS_LOCK_ERROR(rc) ){
1765 pFile->lastErrno = tErrno;
1766 }
1767 return rc;
1768 }
drh308c2a52010-05-14 11:30:18 +00001769 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001770 return SQLITE_OK;
1771}
1772
1773/*
drh9b35ea62008-11-29 02:20:26 +00001774** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001775*/
1776static int dotlockClose(sqlite3_file *id) {
1777 int rc;
1778 if( id ){
1779 unixFile *pFile = (unixFile*)id;
1780 dotlockUnlock(id, NO_LOCK);
1781 sqlite3_free(pFile->lockingContext);
1782 }
drh734c9862008-11-28 15:37:20 +00001783 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001784 return rc;
1785}
1786/****************** End of the dot-file lock implementation *******************
1787******************************************************************************/
1788
1789/******************************************************************************
1790************************** Begin flock Locking ********************************
1791**
1792** Use the flock() system call to do file locking.
1793**
drh6b9d6dd2008-12-03 19:34:47 +00001794** flock() locking is like dot-file locking in that the various
1795** fine-grain locking levels supported by SQLite are collapsed into
1796** a single exclusive lock. In other words, SHARED, RESERVED, and
1797** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1798** still works when you do this, but concurrency is reduced since
1799** only a single process can be reading the database at a time.
1800**
drh734c9862008-11-28 15:37:20 +00001801** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1802** compiling for VXWORKS.
1803*/
1804#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001805
drh6b9d6dd2008-12-03 19:34:47 +00001806/*
drhff812312011-02-23 13:33:46 +00001807** Retry flock() calls that fail with EINTR
1808*/
1809#ifdef EINTR
1810static int robust_flock(int fd, int op){
1811 int rc;
1812 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
1813 return rc;
1814}
1815#else
drh5c819272011-02-23 14:00:12 +00001816# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00001817#endif
1818
1819
1820/*
drh6b9d6dd2008-12-03 19:34:47 +00001821** This routine checks if there is a RESERVED lock held on the specified
1822** file by this or any other process. If such a lock is held, set *pResOut
1823** to a non-zero value otherwise *pResOut is set to zero. The return value
1824** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1825*/
drh734c9862008-11-28 15:37:20 +00001826static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1827 int rc = SQLITE_OK;
1828 int reserved = 0;
1829 unixFile *pFile = (unixFile*)id;
1830
1831 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1832
1833 assert( pFile );
1834
1835 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001836 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001837 reserved = 1;
1838 }
1839
1840 /* Otherwise see if some other process holds it. */
1841 if( !reserved ){
1842 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00001843 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00001844 if( !lrc ){
1845 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00001846 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00001847 if ( lrc ) {
1848 int tErrno = errno;
1849 /* unlock failed with an error */
1850 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1851 if( IS_LOCK_ERROR(lrc) ){
1852 pFile->lastErrno = tErrno;
1853 rc = lrc;
1854 }
1855 }
1856 } else {
1857 int tErrno = errno;
1858 reserved = 1;
1859 /* someone else might have it reserved */
1860 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1861 if( IS_LOCK_ERROR(lrc) ){
1862 pFile->lastErrno = tErrno;
1863 rc = lrc;
1864 }
1865 }
1866 }
drh308c2a52010-05-14 11:30:18 +00001867 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001868
1869#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1870 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1871 rc = SQLITE_OK;
1872 reserved=1;
1873 }
1874#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1875 *pResOut = reserved;
1876 return rc;
1877}
1878
drh6b9d6dd2008-12-03 19:34:47 +00001879/*
drh308c2a52010-05-14 11:30:18 +00001880** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001881** of the following:
1882**
1883** (1) SHARED_LOCK
1884** (2) RESERVED_LOCK
1885** (3) PENDING_LOCK
1886** (4) EXCLUSIVE_LOCK
1887**
1888** Sometimes when requesting one lock state, additional lock states
1889** are inserted in between. The locking might fail on one of the later
1890** transitions leaving the lock state different from what it started but
1891** still short of its goal. The following chart shows the allowed
1892** transitions and the inserted intermediate states:
1893**
1894** UNLOCKED -> SHARED
1895** SHARED -> RESERVED
1896** SHARED -> (PENDING) -> EXCLUSIVE
1897** RESERVED -> (PENDING) -> EXCLUSIVE
1898** PENDING -> EXCLUSIVE
1899**
1900** flock() only really support EXCLUSIVE locks. We track intermediate
1901** lock states in the sqlite3_file structure, but all locks SHARED or
1902** above are really EXCLUSIVE locks and exclude all other processes from
1903** access the file.
1904**
1905** This routine will only increase a lock. Use the sqlite3OsUnlock()
1906** routine to lower a locking level.
1907*/
drh308c2a52010-05-14 11:30:18 +00001908static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001909 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001910 unixFile *pFile = (unixFile*)id;
1911
1912 assert( pFile );
1913
1914 /* if we already have a lock, it is exclusive.
1915 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001916 if (pFile->eFileLock > NO_LOCK) {
1917 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001918 return SQLITE_OK;
1919 }
1920
1921 /* grab an exclusive lock */
1922
drhff812312011-02-23 13:33:46 +00001923 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00001924 int tErrno = errno;
1925 /* didn't get, must be busy */
1926 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1927 if( IS_LOCK_ERROR(rc) ){
1928 pFile->lastErrno = tErrno;
1929 }
1930 } else {
1931 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001932 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001933 }
drh308c2a52010-05-14 11:30:18 +00001934 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1935 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001936#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1937 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1938 rc = SQLITE_BUSY;
1939 }
1940#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1941 return rc;
1942}
1943
drh6b9d6dd2008-12-03 19:34:47 +00001944
1945/*
drh308c2a52010-05-14 11:30:18 +00001946** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001947** must be either NO_LOCK or SHARED_LOCK.
1948**
1949** If the locking level of the file descriptor is already at or below
1950** the requested locking level, this routine is a no-op.
1951*/
drh308c2a52010-05-14 11:30:18 +00001952static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001953 unixFile *pFile = (unixFile*)id;
1954
1955 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001956 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1957 pFile->eFileLock, getpid()));
1958 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001959
1960 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001961 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001962 return SQLITE_OK;
1963 }
1964
1965 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001966 if (eFileLock==SHARED_LOCK) {
1967 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001968 return SQLITE_OK;
1969 }
1970
1971 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00001972 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00001973 if (rc) {
1974 int r, tErrno = errno;
1975 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1976 if( IS_LOCK_ERROR(r) ){
1977 pFile->lastErrno = tErrno;
1978 }
1979#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1980 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1981 r = SQLITE_BUSY;
1982 }
1983#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1984
1985 return r;
1986 } else {
drh308c2a52010-05-14 11:30:18 +00001987 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001988 return SQLITE_OK;
1989 }
1990}
1991
1992/*
1993** Close a file.
1994*/
1995static int flockClose(sqlite3_file *id) {
1996 if( id ){
1997 flockUnlock(id, NO_LOCK);
1998 }
1999 return closeUnixFile(id);
2000}
2001
2002#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2003
2004/******************* End of the flock lock implementation *********************
2005******************************************************************************/
2006
2007/******************************************************************************
2008************************ Begin Named Semaphore Locking ************************
2009**
2010** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002011**
2012** Semaphore locking is like dot-lock and flock in that it really only
2013** supports EXCLUSIVE locking. Only a single process can read or write
2014** the database file at a time. This reduces potential concurrency, but
2015** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002016*/
2017#if OS_VXWORKS
2018
drh6b9d6dd2008-12-03 19:34:47 +00002019/*
2020** This routine checks if there is a RESERVED lock held on the specified
2021** file by this or any other process. If such a lock is held, set *pResOut
2022** to a non-zero value otherwise *pResOut is set to zero. The return value
2023** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2024*/
drh734c9862008-11-28 15:37:20 +00002025static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2026 int rc = SQLITE_OK;
2027 int reserved = 0;
2028 unixFile *pFile = (unixFile*)id;
2029
2030 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2031
2032 assert( pFile );
2033
2034 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002035 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002036 reserved = 1;
2037 }
2038
2039 /* Otherwise see if some other process holds it. */
2040 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002041 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002042 struct stat statBuf;
2043
2044 if( sem_trywait(pSem)==-1 ){
2045 int tErrno = errno;
2046 if( EAGAIN != tErrno ){
2047 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2048 pFile->lastErrno = tErrno;
2049 } else {
2050 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002051 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002052 }
2053 }else{
2054 /* we could have it if we want it */
2055 sem_post(pSem);
2056 }
2057 }
drh308c2a52010-05-14 11:30:18 +00002058 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002059
2060 *pResOut = reserved;
2061 return rc;
2062}
2063
drh6b9d6dd2008-12-03 19:34:47 +00002064/*
drh308c2a52010-05-14 11:30:18 +00002065** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002066** of the following:
2067**
2068** (1) SHARED_LOCK
2069** (2) RESERVED_LOCK
2070** (3) PENDING_LOCK
2071** (4) EXCLUSIVE_LOCK
2072**
2073** Sometimes when requesting one lock state, additional lock states
2074** are inserted in between. The locking might fail on one of the later
2075** transitions leaving the lock state different from what it started but
2076** still short of its goal. The following chart shows the allowed
2077** transitions and the inserted intermediate states:
2078**
2079** UNLOCKED -> SHARED
2080** SHARED -> RESERVED
2081** SHARED -> (PENDING) -> EXCLUSIVE
2082** RESERVED -> (PENDING) -> EXCLUSIVE
2083** PENDING -> EXCLUSIVE
2084**
2085** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2086** lock states in the sqlite3_file structure, but all locks SHARED or
2087** above are really EXCLUSIVE locks and exclude all other processes from
2088** access the file.
2089**
2090** This routine will only increase a lock. Use the sqlite3OsUnlock()
2091** routine to lower a locking level.
2092*/
drh308c2a52010-05-14 11:30:18 +00002093static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002094 unixFile *pFile = (unixFile*)id;
2095 int fd;
drh8af6c222010-05-14 12:43:01 +00002096 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002097 int rc = SQLITE_OK;
2098
2099 /* if we already have a lock, it is exclusive.
2100 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002101 if (pFile->eFileLock > NO_LOCK) {
2102 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002103 rc = SQLITE_OK;
2104 goto sem_end_lock;
2105 }
2106
2107 /* lock semaphore now but bail out when already locked. */
2108 if( sem_trywait(pSem)==-1 ){
2109 rc = SQLITE_BUSY;
2110 goto sem_end_lock;
2111 }
2112
2113 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002114 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002115
2116 sem_end_lock:
2117 return rc;
2118}
2119
drh6b9d6dd2008-12-03 19:34:47 +00002120/*
drh308c2a52010-05-14 11:30:18 +00002121** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002122** must be either NO_LOCK or SHARED_LOCK.
2123**
2124** If the locking level of the file descriptor is already at or below
2125** the requested locking level, this routine is a no-op.
2126*/
drh308c2a52010-05-14 11:30:18 +00002127static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002128 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002129 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002130
2131 assert( pFile );
2132 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002133 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2134 pFile->eFileLock, getpid()));
2135 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002136
2137 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002138 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002139 return SQLITE_OK;
2140 }
2141
2142 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002143 if (eFileLock==SHARED_LOCK) {
2144 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002145 return SQLITE_OK;
2146 }
2147
2148 /* no, really unlock. */
2149 if ( sem_post(pSem)==-1 ) {
2150 int rc, tErrno = errno;
2151 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2152 if( IS_LOCK_ERROR(rc) ){
2153 pFile->lastErrno = tErrno;
2154 }
2155 return rc;
2156 }
drh308c2a52010-05-14 11:30:18 +00002157 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002158 return SQLITE_OK;
2159}
2160
2161/*
2162 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002163 */
drh734c9862008-11-28 15:37:20 +00002164static int semClose(sqlite3_file *id) {
2165 if( id ){
2166 unixFile *pFile = (unixFile*)id;
2167 semUnlock(id, NO_LOCK);
2168 assert( pFile );
2169 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002170 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002171 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002172 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002173 }
2174 return SQLITE_OK;
2175}
2176
2177#endif /* OS_VXWORKS */
2178/*
2179** Named semaphore locking is only available on VxWorks.
2180**
2181*************** End of the named semaphore lock implementation ****************
2182******************************************************************************/
2183
2184
2185/******************************************************************************
2186*************************** Begin AFP Locking *********************************
2187**
2188** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2189** on Apple Macintosh computers - both OS9 and OSX.
2190**
2191** Third-party implementations of AFP are available. But this code here
2192** only works on OSX.
2193*/
2194
drhd2cb50b2009-01-09 21:41:17 +00002195#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002196/*
2197** The afpLockingContext structure contains all afp lock specific state
2198*/
drhbfe66312006-10-03 17:40:40 +00002199typedef struct afpLockingContext afpLockingContext;
2200struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002201 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002202 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002203};
2204
2205struct ByteRangeLockPB2
2206{
2207 unsigned long long offset; /* offset to first byte to lock */
2208 unsigned long long length; /* nbr of bytes to lock */
2209 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2210 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2211 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2212 int fd; /* file desc to assoc this lock with */
2213};
2214
drhfd131da2007-08-07 17:13:03 +00002215#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002216
drh6b9d6dd2008-12-03 19:34:47 +00002217/*
2218** This is a utility for setting or clearing a bit-range lock on an
2219** AFP filesystem.
2220**
2221** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2222*/
2223static int afpSetLock(
2224 const char *path, /* Name of the file to be locked or unlocked */
2225 unixFile *pFile, /* Open file descriptor on path */
2226 unsigned long long offset, /* First byte to be locked */
2227 unsigned long long length, /* Number of bytes to lock */
2228 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002229){
drh6b9d6dd2008-12-03 19:34:47 +00002230 struct ByteRangeLockPB2 pb;
2231 int err;
drhbfe66312006-10-03 17:40:40 +00002232
2233 pb.unLockFlag = setLockFlag ? 0 : 1;
2234 pb.startEndFlag = 0;
2235 pb.offset = offset;
2236 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002237 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002238
drh308c2a52010-05-14 11:30:18 +00002239 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002240 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002241 offset, length));
drhbfe66312006-10-03 17:40:40 +00002242 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2243 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002244 int rc;
2245 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002246 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2247 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002248#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2249 rc = SQLITE_BUSY;
2250#else
drh734c9862008-11-28 15:37:20 +00002251 rc = sqliteErrorFromPosixError(tErrno,
2252 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002253#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002254 if( IS_LOCK_ERROR(rc) ){
2255 pFile->lastErrno = tErrno;
2256 }
2257 return rc;
drhbfe66312006-10-03 17:40:40 +00002258 } else {
aswift5b1a2562008-08-22 00:22:35 +00002259 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002260 }
2261}
2262
drh6b9d6dd2008-12-03 19:34:47 +00002263/*
2264** This routine checks if there is a RESERVED lock held on the specified
2265** file by this or any other process. If such a lock is held, set *pResOut
2266** to a non-zero value otherwise *pResOut is set to zero. The return value
2267** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2268*/
danielk1977e339d652008-06-28 11:23:00 +00002269static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002270 int rc = SQLITE_OK;
2271 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002272 unixFile *pFile = (unixFile*)id;
2273
aswift5b1a2562008-08-22 00:22:35 +00002274 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2275
2276 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002277 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002278 if( context->reserved ){
2279 *pResOut = 1;
2280 return SQLITE_OK;
2281 }
drh8af6c222010-05-14 12:43:01 +00002282 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002283
2284 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002285 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002286 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002287 }
2288
2289 /* Otherwise see if some other process holds it.
2290 */
aswift5b1a2562008-08-22 00:22:35 +00002291 if( !reserved ){
2292 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002293 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002294 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002295 /* if we succeeded in taking the reserved lock, unlock it to restore
2296 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002297 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002298 } else {
2299 /* if we failed to get the lock then someone else must have it */
2300 reserved = 1;
2301 }
2302 if( IS_LOCK_ERROR(lrc) ){
2303 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002304 }
2305 }
drhbfe66312006-10-03 17:40:40 +00002306
drh7ed97b92010-01-20 13:07:21 +00002307 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002308 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002309
2310 *pResOut = reserved;
2311 return rc;
drhbfe66312006-10-03 17:40:40 +00002312}
2313
drh6b9d6dd2008-12-03 19:34:47 +00002314/*
drh308c2a52010-05-14 11:30:18 +00002315** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002316** of the following:
2317**
2318** (1) SHARED_LOCK
2319** (2) RESERVED_LOCK
2320** (3) PENDING_LOCK
2321** (4) EXCLUSIVE_LOCK
2322**
2323** Sometimes when requesting one lock state, additional lock states
2324** are inserted in between. The locking might fail on one of the later
2325** transitions leaving the lock state different from what it started but
2326** still short of its goal. The following chart shows the allowed
2327** transitions and the inserted intermediate states:
2328**
2329** UNLOCKED -> SHARED
2330** SHARED -> RESERVED
2331** SHARED -> (PENDING) -> EXCLUSIVE
2332** RESERVED -> (PENDING) -> EXCLUSIVE
2333** PENDING -> EXCLUSIVE
2334**
2335** This routine will only increase a lock. Use the sqlite3OsUnlock()
2336** routine to lower a locking level.
2337*/
drh308c2a52010-05-14 11:30:18 +00002338static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002339 int rc = SQLITE_OK;
2340 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002341 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002342 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002343
2344 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002345 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2346 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002347 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002348
drhbfe66312006-10-03 17:40:40 +00002349 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002350 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002351 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002352 */
drh308c2a52010-05-14 11:30:18 +00002353 if( pFile->eFileLock>=eFileLock ){
2354 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2355 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002356 return SQLITE_OK;
2357 }
2358
2359 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002360 ** (1) We never move from unlocked to anything higher than shared lock.
2361 ** (2) SQLite never explicitly requests a pendig lock.
2362 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002363 */
drh308c2a52010-05-14 11:30:18 +00002364 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2365 assert( eFileLock!=PENDING_LOCK );
2366 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002367
drh8af6c222010-05-14 12:43:01 +00002368 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002369 */
drh6c7d5c52008-11-21 20:32:33 +00002370 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002371 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002372
2373 /* If some thread using this PID has a lock via a different unixFile*
2374 ** handle that precludes the requested lock, return BUSY.
2375 */
drh8af6c222010-05-14 12:43:01 +00002376 if( (pFile->eFileLock!=pInode->eFileLock &&
2377 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002378 ){
2379 rc = SQLITE_BUSY;
2380 goto afp_end_lock;
2381 }
2382
2383 /* If a SHARED lock is requested, and some thread using this PID already
2384 ** has a SHARED or RESERVED lock, then increment reference counts and
2385 ** return SQLITE_OK.
2386 */
drh308c2a52010-05-14 11:30:18 +00002387 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002388 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002389 assert( eFileLock==SHARED_LOCK );
2390 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002391 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002392 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002393 pInode->nShared++;
2394 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002395 goto afp_end_lock;
2396 }
drhbfe66312006-10-03 17:40:40 +00002397
2398 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002399 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2400 ** be released.
2401 */
drh308c2a52010-05-14 11:30:18 +00002402 if( eFileLock==SHARED_LOCK
2403 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002404 ){
2405 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002406 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002407 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002408 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002409 goto afp_end_lock;
2410 }
2411 }
2412
2413 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002414 ** operating system calls for the specified lock.
2415 */
drh308c2a52010-05-14 11:30:18 +00002416 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002417 int lrc1, lrc2, lrc1Errno;
2418 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002419
drh8af6c222010-05-14 12:43:01 +00002420 assert( pInode->nShared==0 );
2421 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002422
2423 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002424 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002425 /* note that the quality of the randomness doesn't matter that much */
2426 lk = random();
drh8af6c222010-05-14 12:43:01 +00002427 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002428 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002429 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002430 if( IS_LOCK_ERROR(lrc1) ){
2431 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002432 }
aswift5b1a2562008-08-22 00:22:35 +00002433 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002434 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002435
aswift5b1a2562008-08-22 00:22:35 +00002436 if( IS_LOCK_ERROR(lrc1) ) {
2437 pFile->lastErrno = lrc1Errno;
2438 rc = lrc1;
2439 goto afp_end_lock;
2440 } else if( IS_LOCK_ERROR(lrc2) ){
2441 rc = lrc2;
2442 goto afp_end_lock;
2443 } else if( lrc1 != SQLITE_OK ) {
2444 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002445 } else {
drh308c2a52010-05-14 11:30:18 +00002446 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002447 pInode->nLock++;
2448 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002449 }
drh8af6c222010-05-14 12:43:01 +00002450 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002451 /* We are trying for an exclusive lock but another thread in this
2452 ** same process is still holding a shared lock. */
2453 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002454 }else{
2455 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2456 ** assumed that there is a SHARED or greater lock on the file
2457 ** already.
2458 */
2459 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002460 assert( 0!=pFile->eFileLock );
2461 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002462 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002463 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002464 if( !failed ){
2465 context->reserved = 1;
2466 }
drhbfe66312006-10-03 17:40:40 +00002467 }
drh308c2a52010-05-14 11:30:18 +00002468 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002469 /* Acquire an EXCLUSIVE lock */
2470
2471 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002472 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002473 */
drh6b9d6dd2008-12-03 19:34:47 +00002474 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002475 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002476 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002477 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002478 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002479 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002480 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002481 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002482 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2483 ** a critical I/O error
2484 */
2485 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2486 SQLITE_IOERR_LOCK;
2487 goto afp_end_lock;
2488 }
2489 }else{
aswift5b1a2562008-08-22 00:22:35 +00002490 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002491 }
2492 }
aswift5b1a2562008-08-22 00:22:35 +00002493 if( failed ){
2494 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002495 }
2496 }
2497
2498 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002499 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002500 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002501 }else if( eFileLock==EXCLUSIVE_LOCK ){
2502 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002503 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002504 }
2505
2506afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002507 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002508 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2509 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002510 return rc;
2511}
2512
2513/*
drh308c2a52010-05-14 11:30:18 +00002514** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002515** must be either NO_LOCK or SHARED_LOCK.
2516**
2517** If the locking level of the file descriptor is already at or below
2518** the requested locking level, this routine is a no-op.
2519*/
drh308c2a52010-05-14 11:30:18 +00002520static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002521 int rc = SQLITE_OK;
2522 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002523 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002524 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2525 int skipShared = 0;
2526#ifdef SQLITE_TEST
2527 int h = pFile->h;
2528#endif
drhbfe66312006-10-03 17:40:40 +00002529
2530 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002531 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002532 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002533 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002534
drh308c2a52010-05-14 11:30:18 +00002535 assert( eFileLock<=SHARED_LOCK );
2536 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002537 return SQLITE_OK;
2538 }
drh6c7d5c52008-11-21 20:32:33 +00002539 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002540 pInode = pFile->pInode;
2541 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002542 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002543 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002544 SimulateIOErrorBenign(1);
2545 SimulateIOError( h=(-1) )
2546 SimulateIOErrorBenign(0);
2547
2548#ifndef NDEBUG
2549 /* When reducing a lock such that other processes can start
2550 ** reading the database file again, make sure that the
2551 ** transaction counter was updated if any part of the database
2552 ** file changed. If the transaction counter is not updated,
2553 ** other connections to the same file might not realize that
2554 ** the file has changed and hence might not know to flush their
2555 ** cache. The use of a stale cache can lead to database corruption.
2556 */
2557 assert( pFile->inNormalWrite==0
2558 || pFile->dbUpdate==0
2559 || pFile->transCntrChng==1 );
2560 pFile->inNormalWrite = 0;
2561#endif
aswiftaebf4132008-11-21 00:10:35 +00002562
drh308c2a52010-05-14 11:30:18 +00002563 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002564 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002565 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002566 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002567 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002568 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2569 } else {
2570 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002571 }
2572 }
drh308c2a52010-05-14 11:30:18 +00002573 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002574 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002575 }
drh308c2a52010-05-14 11:30:18 +00002576 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002577 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2578 if( !rc ){
2579 context->reserved = 0;
2580 }
aswiftaebf4132008-11-21 00:10:35 +00002581 }
drh8af6c222010-05-14 12:43:01 +00002582 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2583 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002584 }
aswiftaebf4132008-11-21 00:10:35 +00002585 }
drh308c2a52010-05-14 11:30:18 +00002586 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002587
drh7ed97b92010-01-20 13:07:21 +00002588 /* Decrement the shared lock counter. Release the lock using an
2589 ** OS call only when all threads in this same process have released
2590 ** the lock.
2591 */
drh8af6c222010-05-14 12:43:01 +00002592 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2593 pInode->nShared--;
2594 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002595 SimulateIOErrorBenign(1);
2596 SimulateIOError( h=(-1) )
2597 SimulateIOErrorBenign(0);
2598 if( !skipShared ){
2599 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2600 }
2601 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002602 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002603 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002604 }
2605 }
2606 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002607 pInode->nLock--;
2608 assert( pInode->nLock>=0 );
2609 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002610 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002611 }
2612 }
drhbfe66312006-10-03 17:40:40 +00002613 }
drh7ed97b92010-01-20 13:07:21 +00002614
drh6c7d5c52008-11-21 20:32:33 +00002615 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002616 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002617 return rc;
2618}
2619
2620/*
drh339eb0b2008-03-07 15:34:11 +00002621** Close a file & cleanup AFP specific locking context
2622*/
danielk1977e339d652008-06-28 11:23:00 +00002623static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002624 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002625 if( id ){
2626 unixFile *pFile = (unixFile*)id;
2627 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002628 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002629 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002630 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002631 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002632 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002633 ** the last lock is cleared.
2634 */
dan08da86a2009-08-21 17:18:03 +00002635 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002636 }
danb0ac3e32010-06-16 10:55:42 +00002637 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002638 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002639 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002640 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002641 }
drh7ed97b92010-01-20 13:07:21 +00002642 return rc;
drhbfe66312006-10-03 17:40:40 +00002643}
2644
drhd2cb50b2009-01-09 21:41:17 +00002645#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002646/*
2647** The code above is the AFP lock implementation. The code is specific
2648** to MacOSX and does not work on other unix platforms. No alternative
2649** is available. If you don't compile for a mac, then the "unix-afp"
2650** VFS is not available.
2651**
2652********************* End of the AFP lock implementation **********************
2653******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002654
drh7ed97b92010-01-20 13:07:21 +00002655/******************************************************************************
2656*************************** Begin NFS Locking ********************************/
2657
2658#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2659/*
drh308c2a52010-05-14 11:30:18 +00002660 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002661 ** must be either NO_LOCK or SHARED_LOCK.
2662 **
2663 ** If the locking level of the file descriptor is already at or below
2664 ** the requested locking level, this routine is a no-op.
2665 */
drh308c2a52010-05-14 11:30:18 +00002666static int nfsUnlock(sqlite3_file *id, int eFileLock){
2667 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002668}
2669
2670#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2671/*
2672** The code above is the NFS lock implementation. The code is specific
2673** to MacOSX and does not work on other unix platforms. No alternative
2674** is available.
2675**
2676********************* End of the NFS lock implementation **********************
2677******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002678
2679/******************************************************************************
2680**************** Non-locking sqlite3_file methods *****************************
2681**
2682** The next division contains implementations for all methods of the
2683** sqlite3_file object other than the locking methods. The locking
2684** methods were defined in divisions above (one locking method per
2685** division). Those methods that are common to all locking modes
2686** are gather together into this division.
2687*/
drhbfe66312006-10-03 17:40:40 +00002688
2689/*
drh734c9862008-11-28 15:37:20 +00002690** Seek to the offset passed as the second argument, then read cnt
2691** bytes into pBuf. Return the number of bytes actually read.
2692**
2693** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2694** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2695** one system to another. Since SQLite does not define USE_PREAD
2696** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2697** See tickets #2741 and #2681.
2698**
2699** To avoid stomping the errno value on a failed read the lastErrno value
2700** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002701*/
drh734c9862008-11-28 15:37:20 +00002702static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2703 int got;
drh7ed97b92010-01-20 13:07:21 +00002704#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002705 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002706#endif
drh734c9862008-11-28 15:37:20 +00002707 TIMER_START;
2708#if defined(USE_PREAD)
drhff812312011-02-23 13:33:46 +00002709 do{ got = pread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002710 SimulateIOError( got = -1 );
2711#elif defined(USE_PREAD64)
drhff812312011-02-23 13:33:46 +00002712 do{ got = pread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002713 SimulateIOError( got = -1 );
2714#else
2715 newOffset = lseek(id->h, offset, SEEK_SET);
2716 SimulateIOError( newOffset-- );
2717 if( newOffset!=offset ){
2718 if( newOffset == -1 ){
2719 ((unixFile*)id)->lastErrno = errno;
2720 }else{
2721 ((unixFile*)id)->lastErrno = 0;
2722 }
2723 return -1;
2724 }
drhff812312011-02-23 13:33:46 +00002725 do{ got = read(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002726#endif
2727 TIMER_END;
2728 if( got<0 ){
2729 ((unixFile*)id)->lastErrno = errno;
2730 }
drh308c2a52010-05-14 11:30:18 +00002731 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002732 return got;
drhbfe66312006-10-03 17:40:40 +00002733}
2734
2735/*
drh734c9862008-11-28 15:37:20 +00002736** Read data from a file into a buffer. Return SQLITE_OK if all
2737** bytes were read successfully and SQLITE_IOERR if anything goes
2738** wrong.
drh339eb0b2008-03-07 15:34:11 +00002739*/
drh734c9862008-11-28 15:37:20 +00002740static int unixRead(
2741 sqlite3_file *id,
2742 void *pBuf,
2743 int amt,
2744 sqlite3_int64 offset
2745){
dan08da86a2009-08-21 17:18:03 +00002746 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002747 int got;
2748 assert( id );
drh08c6d442009-02-09 17:34:07 +00002749
dan08da86a2009-08-21 17:18:03 +00002750 /* If this is a database file (not a journal, master-journal or temp
2751 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002752#if 0
dane946c392009-08-22 11:39:46 +00002753 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002754 || offset>=PENDING_BYTE+512
2755 || offset+amt<=PENDING_BYTE
2756 );
dan7c246102010-04-12 19:00:29 +00002757#endif
drh08c6d442009-02-09 17:34:07 +00002758
dan08da86a2009-08-21 17:18:03 +00002759 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002760 if( got==amt ){
2761 return SQLITE_OK;
2762 }else if( got<0 ){
2763 /* lastErrno set by seekAndRead */
2764 return SQLITE_IOERR_READ;
2765 }else{
dan08da86a2009-08-21 17:18:03 +00002766 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002767 /* Unread parts of the buffer must be zero-filled */
2768 memset(&((char*)pBuf)[got], 0, amt-got);
2769 return SQLITE_IOERR_SHORT_READ;
2770 }
2771}
2772
2773/*
2774** Seek to the offset in id->offset then read cnt bytes into pBuf.
2775** Return the number of bytes actually read. Update the offset.
2776**
2777** To avoid stomping the errno value on a failed write the lastErrno value
2778** is set before returning.
2779*/
2780static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2781 int got;
drh7ed97b92010-01-20 13:07:21 +00002782#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002783 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002784#endif
drh734c9862008-11-28 15:37:20 +00002785 TIMER_START;
2786#if defined(USE_PREAD)
drhff812312011-02-23 13:33:46 +00002787 do{ got = pwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002788#elif defined(USE_PREAD64)
drhff812312011-02-23 13:33:46 +00002789 do{ got = pwrite64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002790#else
2791 newOffset = lseek(id->h, offset, SEEK_SET);
2792 if( newOffset!=offset ){
2793 if( newOffset == -1 ){
2794 ((unixFile*)id)->lastErrno = errno;
2795 }else{
2796 ((unixFile*)id)->lastErrno = 0;
2797 }
2798 return -1;
2799 }
drhff812312011-02-23 13:33:46 +00002800 do{ got = write(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002801#endif
2802 TIMER_END;
2803 if( got<0 ){
2804 ((unixFile*)id)->lastErrno = errno;
2805 }
2806
drh308c2a52010-05-14 11:30:18 +00002807 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002808 return got;
2809}
2810
2811
2812/*
2813** Write data from a buffer into a file. Return SQLITE_OK on success
2814** or some other error code on failure.
2815*/
2816static int unixWrite(
2817 sqlite3_file *id,
2818 const void *pBuf,
2819 int amt,
2820 sqlite3_int64 offset
2821){
dan08da86a2009-08-21 17:18:03 +00002822 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002823 int wrote = 0;
2824 assert( id );
2825 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002826
dan08da86a2009-08-21 17:18:03 +00002827 /* If this is a database file (not a journal, master-journal or temp
2828 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002829#if 0
dane946c392009-08-22 11:39:46 +00002830 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002831 || offset>=PENDING_BYTE+512
2832 || offset+amt<=PENDING_BYTE
2833 );
dan7c246102010-04-12 19:00:29 +00002834#endif
drh08c6d442009-02-09 17:34:07 +00002835
drh8f941bc2009-01-14 23:03:40 +00002836#ifndef NDEBUG
2837 /* If we are doing a normal write to a database file (as opposed to
2838 ** doing a hot-journal rollback or a write to some file other than a
2839 ** normal database file) then record the fact that the database
2840 ** has changed. If the transaction counter is modified, record that
2841 ** fact too.
2842 */
dan08da86a2009-08-21 17:18:03 +00002843 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002844 pFile->dbUpdate = 1; /* The database has been modified */
2845 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002846 int rc;
drh8f941bc2009-01-14 23:03:40 +00002847 char oldCntr[4];
2848 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002849 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002850 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002851 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002852 pFile->transCntrChng = 1; /* The transaction counter has changed */
2853 }
2854 }
2855 }
2856#endif
2857
dan08da86a2009-08-21 17:18:03 +00002858 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002859 amt -= wrote;
2860 offset += wrote;
2861 pBuf = &((char*)pBuf)[wrote];
2862 }
2863 SimulateIOError(( wrote=(-1), amt=1 ));
2864 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002865
drh734c9862008-11-28 15:37:20 +00002866 if( amt>0 ){
2867 if( wrote<0 ){
2868 /* lastErrno set by seekAndWrite */
2869 return SQLITE_IOERR_WRITE;
2870 }else{
dan08da86a2009-08-21 17:18:03 +00002871 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002872 return SQLITE_FULL;
2873 }
2874 }
dan6e09d692010-07-27 18:34:15 +00002875
drh734c9862008-11-28 15:37:20 +00002876 return SQLITE_OK;
2877}
2878
2879#ifdef SQLITE_TEST
2880/*
2881** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002882** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002883*/
2884int sqlite3_sync_count = 0;
2885int sqlite3_fullsync_count = 0;
2886#endif
2887
2888/*
drh89240432009-03-25 01:06:01 +00002889** We do not trust systems to provide a working fdatasync(). Some do.
2890** Others do no. To be safe, we will stick with the (slower) fsync().
2891** If you know that your system does support fdatasync() correctly,
2892** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002893*/
drh89240432009-03-25 01:06:01 +00002894#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002895# define fdatasync fsync
2896#endif
2897
2898/*
2899** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2900** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2901** only available on Mac OS X. But that could change.
2902*/
2903#ifdef F_FULLFSYNC
2904# define HAVE_FULLFSYNC 1
2905#else
2906# define HAVE_FULLFSYNC 0
2907#endif
2908
2909
2910/*
2911** The fsync() system call does not work as advertised on many
2912** unix systems. The following procedure is an attempt to make
2913** it work better.
2914**
2915** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2916** for testing when we want to run through the test suite quickly.
2917** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2918** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2919** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002920**
2921** SQLite sets the dataOnly flag if the size of the file is unchanged.
2922** The idea behind dataOnly is that it should only write the file content
2923** to disk, not the inode. We only set dataOnly if the file size is
2924** unchanged since the file size is part of the inode. However,
2925** Ted Ts'o tells us that fdatasync() will also write the inode if the
2926** file size has changed. The only real difference between fdatasync()
2927** and fsync(), Ted tells us, is that fdatasync() will not flush the
2928** inode if the mtime or owner or other inode attributes have changed.
2929** We only care about the file size, not the other file attributes, so
2930** as far as SQLite is concerned, an fdatasync() is always adequate.
2931** So, we always use fdatasync() if it is available, regardless of
2932** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002933*/
2934static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002935 int rc;
drh734c9862008-11-28 15:37:20 +00002936
2937 /* The following "ifdef/elif/else/" block has the same structure as
2938 ** the one below. It is replicated here solely to avoid cluttering
2939 ** up the real code with the UNUSED_PARAMETER() macros.
2940 */
2941#ifdef SQLITE_NO_SYNC
2942 UNUSED_PARAMETER(fd);
2943 UNUSED_PARAMETER(fullSync);
2944 UNUSED_PARAMETER(dataOnly);
2945#elif HAVE_FULLFSYNC
2946 UNUSED_PARAMETER(dataOnly);
2947#else
2948 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002949 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002950#endif
2951
2952 /* Record the number of times that we do a normal fsync() and
2953 ** FULLSYNC. This is used during testing to verify that this procedure
2954 ** gets called with the correct arguments.
2955 */
2956#ifdef SQLITE_TEST
2957 if( fullSync ) sqlite3_fullsync_count++;
2958 sqlite3_sync_count++;
2959#endif
2960
2961 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2962 ** no-op
2963 */
2964#ifdef SQLITE_NO_SYNC
2965 rc = SQLITE_OK;
2966#elif HAVE_FULLFSYNC
2967 if( fullSync ){
2968 rc = fcntl(fd, F_FULLFSYNC, 0);
2969 }else{
2970 rc = 1;
2971 }
2972 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002973 ** It shouldn't be possible for fullfsync to fail on the local
2974 ** file system (on OSX), so failure indicates that FULLFSYNC
2975 ** isn't supported for this file system. So, attempt an fsync
2976 ** and (for now) ignore the overhead of a superfluous fcntl call.
2977 ** It'd be better to detect fullfsync support once and avoid
2978 ** the fcntl call every time sync is called.
2979 */
drh734c9862008-11-28 15:37:20 +00002980 if( rc ) rc = fsync(fd);
2981
drh7ed97b92010-01-20 13:07:21 +00002982#elif defined(__APPLE__)
2983 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2984 ** so currently we default to the macro that redefines fdatasync to fsync
2985 */
2986 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002987#else
drh0b647ff2009-03-21 14:41:04 +00002988 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002989#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002990 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002991 rc = fsync(fd);
2992 }
drh0b647ff2009-03-21 14:41:04 +00002993#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002994#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2995
2996 if( OS_VXWORKS && rc!= -1 ){
2997 rc = 0;
2998 }
chw97185482008-11-17 08:05:31 +00002999 return rc;
drhbfe66312006-10-03 17:40:40 +00003000}
3001
drh734c9862008-11-28 15:37:20 +00003002/*
3003** Make sure all writes to a particular file are committed to disk.
3004**
3005** If dataOnly==0 then both the file itself and its metadata (file
3006** size, access time, etc) are synced. If dataOnly!=0 then only the
3007** file data is synced.
3008**
3009** Under Unix, also make sure that the directory entry for the file
3010** has been created by fsync-ing the directory that contains the file.
3011** If we do not do this and we encounter a power failure, the directory
3012** entry for the journal might not exist after we reboot. The next
3013** SQLite to access the file will not know that the journal exists (because
3014** the directory entry for the journal was never created) and the transaction
3015** will not roll back - possibly leading to database corruption.
3016*/
3017static int unixSync(sqlite3_file *id, int flags){
3018 int rc;
3019 unixFile *pFile = (unixFile*)id;
3020
3021 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3022 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3023
3024 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3025 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3026 || (flags&0x0F)==SQLITE_SYNC_FULL
3027 );
3028
3029 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3030 ** line is to test that doing so does not cause any problems.
3031 */
3032 SimulateDiskfullError( return SQLITE_FULL );
3033
3034 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003035 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003036 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3037 SimulateIOError( rc=1 );
3038 if( rc ){
3039 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003040 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003041 }
3042 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003043 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3044 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003045#ifndef SQLITE_DISABLE_DIRSYNC
3046 /* The directory sync is only attempted if full_fsync is
3047 ** turned off or unavailable. If a full_fsync occurred above,
3048 ** then the directory sync is superfluous.
3049 */
3050 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3051 /*
3052 ** We have received multiple reports of fsync() returning
3053 ** errors when applied to directories on certain file systems.
3054 ** A failed directory sync is not a big deal. So it seems
3055 ** better to ignore the error. Ticket #1657
3056 */
3057 /* pFile->lastErrno = errno; */
3058 /* return SQLITE_IOERR; */
3059 }
3060#endif
drh0e9365c2011-03-02 02:08:13 +00003061 /* Only need to sync once, so close the directory when we are done */
3062 robust_close(pFile, pFile->dirfd, __LINE__);
3063 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003064 }
3065 return rc;
3066}
3067
3068/*
3069** Truncate an open file to a specified size
3070*/
3071static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003072 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003073 int rc;
dan6e09d692010-07-27 18:34:15 +00003074 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003075 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003076
3077 /* If the user has configured a chunk-size for this file, truncate the
3078 ** file so that it consists of an integer number of chunks (i.e. the
3079 ** actual file size after the operation may be larger than the requested
3080 ** size).
3081 */
3082 if( pFile->szChunk ){
3083 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3084 }
3085
drhff812312011-02-23 13:33:46 +00003086 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003087 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003088 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003089 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003090 }else{
drh3313b142009-11-06 04:13:18 +00003091#ifndef NDEBUG
3092 /* If we are doing a normal write to a database file (as opposed to
3093 ** doing a hot-journal rollback or a write to some file other than a
3094 ** normal database file) and we truncate the file to zero length,
3095 ** that effectively updates the change counter. This might happen
3096 ** when restoring a database using the backup API from a zero-length
3097 ** source.
3098 */
dan6e09d692010-07-27 18:34:15 +00003099 if( pFile->inNormalWrite && nByte==0 ){
3100 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003101 }
3102#endif
3103
drh734c9862008-11-28 15:37:20 +00003104 return SQLITE_OK;
3105 }
3106}
3107
3108/*
3109** Determine the current size of a file in bytes
3110*/
3111static int unixFileSize(sqlite3_file *id, i64 *pSize){
3112 int rc;
3113 struct stat buf;
3114 assert( id );
3115 rc = fstat(((unixFile*)id)->h, &buf);
3116 SimulateIOError( rc=1 );
3117 if( rc!=0 ){
3118 ((unixFile*)id)->lastErrno = errno;
3119 return SQLITE_IOERR_FSTAT;
3120 }
3121 *pSize = buf.st_size;
3122
drh8af6c222010-05-14 12:43:01 +00003123 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003124 ** writes a single byte into that file in order to work around a bug
3125 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3126 ** layers, we need to report this file size as zero even though it is
3127 ** really 1. Ticket #3260.
3128 */
3129 if( *pSize==1 ) *pSize = 0;
3130
3131
3132 return SQLITE_OK;
3133}
3134
drhd2cb50b2009-01-09 21:41:17 +00003135#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003136/*
3137** Handler for proxy-locking file-control verbs. Defined below in the
3138** proxying locking division.
3139*/
3140static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003141#endif
drh715ff302008-12-03 22:32:44 +00003142
dan502019c2010-07-28 14:26:17 +00003143/*
3144** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3145** file-control operation.
3146**
3147** If the user has configured a chunk-size for this file, it could be
3148** that the file needs to be extended at this point. Otherwise, the
3149** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3150*/
3151static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3152 if( pFile->szChunk ){
3153 i64 nSize; /* Required file size */
3154 struct stat buf; /* Used to hold return values of fstat() */
3155
3156 if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
3157
3158 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3159 if( nSize>(i64)buf.st_size ){
3160#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003161 int rc;
3162 do{
3163 rc = posix_fallocate(pFile-.h, buf.st_size, nSize-buf.st_size;
3164 }while( rc<0 && errno=EINTR );
3165 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003166#else
3167 /* If the OS does not have posix_fallocate(), fake it. First use
3168 ** ftruncate() to set the file size, then write a single byte to
3169 ** the last byte in each block within the extended region. This
3170 ** is the same technique used by glibc to implement posix_fallocate()
3171 ** on systems that do not have a real fallocate() system call.
3172 */
3173 int nBlk = buf.st_blksize; /* File-system block size */
3174 i64 iWrite; /* Next offset to write to */
3175 int nWrite; /* Return value from seekAndWrite() */
3176
drhff812312011-02-23 13:33:46 +00003177 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003178 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003179 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003180 }
3181 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3182 do {
3183 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3184 iWrite += nBlk;
3185 } while( nWrite==1 && iWrite<nSize );
3186 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3187#endif
3188 }
3189 }
3190
3191 return SQLITE_OK;
3192}
danielk1977ad94b582007-08-20 06:44:22 +00003193
danielk1977e3026632004-06-22 11:29:02 +00003194/*
drh9e33c2c2007-08-31 18:34:59 +00003195** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003196*/
drhcc6bb3e2007-08-31 16:11:35 +00003197static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003198 switch( op ){
3199 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003200 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003201 return SQLITE_OK;
3202 }
drh7708e972008-11-29 00:56:52 +00003203 case SQLITE_LAST_ERRNO: {
3204 *(int*)pArg = ((unixFile*)id)->lastErrno;
3205 return SQLITE_OK;
3206 }
dan6e09d692010-07-27 18:34:15 +00003207 case SQLITE_FCNTL_CHUNK_SIZE: {
3208 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003209 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003210 }
drh9ff27ec2010-05-19 19:26:05 +00003211 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003212 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003213 }
drh8f941bc2009-01-14 23:03:40 +00003214#ifndef NDEBUG
3215 /* The pager calls this method to signal that it has done
3216 ** a rollback and that the database is therefore unchanged and
3217 ** it hence it is OK for the transaction change counter to be
3218 ** unchanged.
3219 */
3220 case SQLITE_FCNTL_DB_UNCHANGED: {
3221 ((unixFile*)id)->dbUpdate = 0;
3222 return SQLITE_OK;
3223 }
3224#endif
drhd2cb50b2009-01-09 21:41:17 +00003225#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003226 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003227 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003228 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003229 }
drhd2cb50b2009-01-09 21:41:17 +00003230#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003231 case SQLITE_FCNTL_SYNC_OMITTED: {
3232 return SQLITE_OK; /* A no-op */
3233 }
drh9e33c2c2007-08-31 18:34:59 +00003234 }
drh0b52b7d2011-01-26 19:46:22 +00003235 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003236}
3237
3238/*
danielk1977a3d4c882007-03-23 10:08:38 +00003239** Return the sector size in bytes of the underlying block device for
3240** the specified file. This is almost always 512 bytes, but may be
3241** larger for some devices.
3242**
3243** SQLite code assumes this function cannot fail. It also assumes that
3244** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003245** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003246** same for both.
3247*/
danielk1977397d65f2008-11-19 11:35:39 +00003248static int unixSectorSize(sqlite3_file *NotUsed){
3249 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003250 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003251}
3252
danielk197790949c22007-08-17 16:50:38 +00003253/*
danielk1977397d65f2008-11-19 11:35:39 +00003254** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003255*/
danielk1977397d65f2008-11-19 11:35:39 +00003256static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3257 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003258 return 0;
3259}
3260
drhd9e5c4f2010-05-12 18:01:39 +00003261#ifndef SQLITE_OMIT_WAL
3262
3263
3264/*
drhd91c68f2010-05-14 14:52:25 +00003265** Object used to represent an shared memory buffer.
3266**
3267** When multiple threads all reference the same wal-index, each thread
3268** has its own unixShm object, but they all point to a single instance
3269** of this unixShmNode object. In other words, each wal-index is opened
3270** only once per process.
3271**
3272** Each unixShmNode object is connected to a single unixInodeInfo object.
3273** We could coalesce this object into unixInodeInfo, but that would mean
3274** every open file that does not use shared memory (in other words, most
3275** open files) would have to carry around this extra information. So
3276** the unixInodeInfo object contains a pointer to this unixShmNode object
3277** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003278**
3279** unixMutexHeld() must be true when creating or destroying
3280** this object or while reading or writing the following fields:
3281**
3282** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003283**
3284** The following fields are read-only after the object is created:
3285**
3286** fid
3287** zFilename
3288**
drhd91c68f2010-05-14 14:52:25 +00003289** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003290** unixMutexHeld() is true when reading or writing any other field
3291** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003292*/
drhd91c68f2010-05-14 14:52:25 +00003293struct unixShmNode {
3294 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003295 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003296 char *zFilename; /* Name of the mmapped file */
3297 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003298 int szRegion; /* Size of shared-memory regions */
3299 int nRegion; /* Size of array apRegion */
3300 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003301 int nRef; /* Number of unixShm objects pointing to this */
3302 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003303#ifdef SQLITE_DEBUG
3304 u8 exclMask; /* Mask of exclusive locks held */
3305 u8 sharedMask; /* Mask of shared locks held */
3306 u8 nextShmId; /* Next available unixShm.id value */
3307#endif
3308};
3309
3310/*
drhd9e5c4f2010-05-12 18:01:39 +00003311** Structure used internally by this VFS to record the state of an
3312** open shared memory connection.
3313**
drhd91c68f2010-05-14 14:52:25 +00003314** The following fields are initialized when this object is created and
3315** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003316**
drhd91c68f2010-05-14 14:52:25 +00003317** unixShm.pFile
3318** unixShm.id
3319**
3320** All other fields are read/write. The unixShm.pFile->mutex must be held
3321** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003322*/
3323struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003324 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3325 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003326 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003327 u16 sharedMask; /* Mask of shared locks held */
3328 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003329#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003330 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003331#endif
3332};
3333
3334/*
drhd9e5c4f2010-05-12 18:01:39 +00003335** Constants used for locking
3336*/
drhbd9676c2010-06-23 17:58:38 +00003337#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003338#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003339
drhd9e5c4f2010-05-12 18:01:39 +00003340/*
drh73b64e42010-05-30 19:55:15 +00003341** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003342**
3343** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3344** otherwise.
3345*/
3346static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003347 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3348 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003349 int ofst, /* First byte of the locking range */
3350 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003351){
3352 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003353 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003354
drhd91c68f2010-05-14 14:52:25 +00003355 /* Access to the unixShmNode object is serialized by the caller */
3356 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003357
drh73b64e42010-05-30 19:55:15 +00003358 /* Shared locks never span more than one byte */
3359 assert( n==1 || lockType!=F_RDLCK );
3360
3361 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003362 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003363
drhd9e5c4f2010-05-12 18:01:39 +00003364 /* Initialize the locking parameters */
3365 memset(&f, 0, sizeof(f));
3366 f.l_type = lockType;
3367 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003368 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003369 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003370
drh73b64e42010-05-30 19:55:15 +00003371 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003372 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3373
3374 /* Update the global lock state and do debug tracing */
3375#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003376 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003377 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003378 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003379 if( rc==SQLITE_OK ){
3380 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003381 OSTRACE(("unlock %d ok", ofst));
3382 pShmNode->exclMask &= ~mask;
3383 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003384 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003385 OSTRACE(("read-lock %d ok", ofst));
3386 pShmNode->exclMask &= ~mask;
3387 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003388 }else{
3389 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003390 OSTRACE(("write-lock %d ok", ofst));
3391 pShmNode->exclMask |= mask;
3392 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003393 }
3394 }else{
3395 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003396 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003397 }else if( lockType==F_RDLCK ){
3398 OSTRACE(("read-lock failed"));
3399 }else{
3400 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003401 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003402 }
3403 }
drh20e1f082010-05-31 16:10:12 +00003404 OSTRACE((" - afterwards %03x,%03x\n",
3405 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003406 }
drhd9e5c4f2010-05-12 18:01:39 +00003407#endif
3408
3409 return rc;
3410}
3411
drhd9e5c4f2010-05-12 18:01:39 +00003412
3413/*
drhd91c68f2010-05-14 14:52:25 +00003414** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003415**
3416** This is not a VFS shared-memory method; it is a utility function called
3417** by VFS shared-memory methods.
3418*/
drhd91c68f2010-05-14 14:52:25 +00003419static void unixShmPurge(unixFile *pFd){
3420 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003421 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003422 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003423 int i;
drhd91c68f2010-05-14 14:52:25 +00003424 assert( p->pInode==pFd->pInode );
3425 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003426 for(i=0; i<p->nRegion; i++){
3427 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003428 }
dan18801912010-06-14 14:07:50 +00003429 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003430 if( p->h>=0 ){
3431 robust_close(pFd, p->h, __LINE__);
3432 p->h = -1;
3433 }
drhd91c68f2010-05-14 14:52:25 +00003434 p->pInode->pShmNode = 0;
3435 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003436 }
3437}
3438
3439/*
danda9fe0c2010-07-13 18:44:03 +00003440** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003441** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003442**
drh7234c6d2010-06-19 15:10:09 +00003443** The file used to implement shared-memory is in the same directory
3444** as the open database file and has the same name as the open database
3445** file with the "-shm" suffix added. For example, if the database file
3446** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003447** for shared memory will be called "/home/user1/config.db-shm".
3448**
3449** Another approach to is to use files in /dev/shm or /dev/tmp or an
3450** some other tmpfs mount. But if a file in a different directory
3451** from the database file is used, then differing access permissions
3452** or a chroot() might cause two different processes on the same
3453** database to end up using different files for shared memory -
3454** meaning that their memory would not really be shared - resulting
3455** in database corruption. Nevertheless, this tmpfs file usage
3456** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3457** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3458** option results in an incompatible build of SQLite; builds of SQLite
3459** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3460** same database file at the same time, database corruption will likely
3461** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3462** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003463**
3464** When opening a new shared-memory file, if no other instances of that
3465** file are currently open, in this process or in other processes, then
3466** the file must be truncated to zero length or have its header cleared.
3467*/
danda9fe0c2010-07-13 18:44:03 +00003468static int unixOpenSharedMemory(unixFile *pDbFd){
3469 struct unixShm *p = 0; /* The connection to be opened */
3470 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3471 int rc; /* Result code */
3472 unixInodeInfo *pInode; /* The inode of fd */
3473 char *zShmFilename; /* Name of the file used for SHM */
3474 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003475
danda9fe0c2010-07-13 18:44:03 +00003476 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003477 p = sqlite3_malloc( sizeof(*p) );
3478 if( p==0 ) return SQLITE_NOMEM;
3479 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003480 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003481
danda9fe0c2010-07-13 18:44:03 +00003482 /* Check to see if a unixShmNode object already exists. Reuse an existing
3483 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003484 */
3485 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003486 pInode = pDbFd->pInode;
3487 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003488 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003489 struct stat sStat; /* fstat() info for database file */
3490
3491 /* Call fstat() to figure out the permissions on the database file. If
3492 ** a new *-shm file is created, an attempt will be made to create it
3493 ** with the same permissions. The actual permissions the file is created
3494 ** with are subject to the current umask setting.
3495 */
3496 if( fstat(pDbFd->h, &sStat) ){
3497 rc = SQLITE_IOERR_FSTAT;
3498 goto shm_open_err;
3499 }
3500
drha4ced192010-07-15 18:32:40 +00003501#ifdef SQLITE_SHM_DIRECTORY
3502 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3503#else
drh7234c6d2010-06-19 15:10:09 +00003504 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003505#endif
drh7234c6d2010-06-19 15:10:09 +00003506 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003507 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003508 rc = SQLITE_NOMEM;
3509 goto shm_open_err;
3510 }
drhd91c68f2010-05-14 14:52:25 +00003511 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003512 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003513#ifdef SQLITE_SHM_DIRECTORY
3514 sqlite3_snprintf(nShmFilename, zShmFilename,
3515 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3516 (u32)sStat.st_ino, (u32)sStat.st_dev);
3517#else
drh7234c6d2010-06-19 15:10:09 +00003518 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003519#endif
drhd91c68f2010-05-14 14:52:25 +00003520 pShmNode->h = -1;
3521 pDbFd->pInode->pShmNode = pShmNode;
3522 pShmNode->pInode = pDbFd->pInode;
3523 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3524 if( pShmNode->mutex==0 ){
3525 rc = SQLITE_NOMEM;
3526 goto shm_open_err;
3527 }
drhd9e5c4f2010-05-12 18:01:39 +00003528
danddb0ac42010-07-14 14:48:58 +00003529 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003530 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003531 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003532 goto shm_open_err;
3533 }
3534
drhd9e5c4f2010-05-12 18:01:39 +00003535 /* Check to see if another process is holding the dead-man switch.
3536 ** If not, truncate the file to zero length.
3537 */
drhd91c68f2010-05-14 14:52:25 +00003538 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003539 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhff812312011-02-23 13:33:46 +00003540 if( robust_ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003541 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003542 }
3543 }
3544 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003545 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003546 }
3547 if( rc ) goto shm_open_err;
3548 }
3549
drhd91c68f2010-05-14 14:52:25 +00003550 /* Make the new connection a child of the unixShmNode */
3551 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003552#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003553 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003554#endif
drhd91c68f2010-05-14 14:52:25 +00003555 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003556 pDbFd->pShm = p;
3557 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003558
3559 /* The reference count on pShmNode has already been incremented under
3560 ** the cover of the unixEnterMutex() mutex and the pointer from the
3561 ** new (struct unixShm) object to the pShmNode has been set. All that is
3562 ** left to do is to link the new object into the linked list starting
3563 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3564 ** mutex.
3565 */
3566 sqlite3_mutex_enter(pShmNode->mutex);
3567 p->pNext = pShmNode->pFirst;
3568 pShmNode->pFirst = p;
3569 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003570 return SQLITE_OK;
3571
3572 /* Jump here on any error */
3573shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003574 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003575 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003576 unixLeaveMutex();
3577 return rc;
3578}
3579
3580/*
danda9fe0c2010-07-13 18:44:03 +00003581** This function is called to obtain a pointer to region iRegion of the
3582** shared-memory associated with the database file fd. Shared-memory regions
3583** are numbered starting from zero. Each shared-memory region is szRegion
3584** bytes in size.
3585**
3586** If an error occurs, an error code is returned and *pp is set to NULL.
3587**
3588** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3589** region has not been allocated (by any client, including one running in a
3590** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3591** bExtend is non-zero and the requested shared-memory region has not yet
3592** been allocated, it is allocated by this function.
3593**
3594** If the shared-memory region has already been allocated or is allocated by
3595** this call as described above, then it is mapped into this processes
3596** address space (if it is not already), *pp is set to point to the mapped
3597** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003598*/
danda9fe0c2010-07-13 18:44:03 +00003599static int unixShmMap(
3600 sqlite3_file *fd, /* Handle open on database file */
3601 int iRegion, /* Region to retrieve */
3602 int szRegion, /* Size of regions */
3603 int bExtend, /* True to extend file if necessary */
3604 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003605){
danda9fe0c2010-07-13 18:44:03 +00003606 unixFile *pDbFd = (unixFile*)fd;
3607 unixShm *p;
3608 unixShmNode *pShmNode;
3609 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003610
danda9fe0c2010-07-13 18:44:03 +00003611 /* If the shared-memory file has not yet been opened, open it now. */
3612 if( pDbFd->pShm==0 ){
3613 rc = unixOpenSharedMemory(pDbFd);
3614 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003615 }
drhd9e5c4f2010-05-12 18:01:39 +00003616
danda9fe0c2010-07-13 18:44:03 +00003617 p = pDbFd->pShm;
3618 pShmNode = p->pShmNode;
3619 sqlite3_mutex_enter(pShmNode->mutex);
3620 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3621
3622 if( pShmNode->nRegion<=iRegion ){
3623 char **apNew; /* New apRegion[] array */
3624 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3625 struct stat sStat; /* Used by fstat() */
3626
3627 pShmNode->szRegion = szRegion;
3628
3629 /* The requested region is not mapped into this processes address space.
3630 ** Check to see if it has been allocated (i.e. if the wal-index file is
3631 ** large enough to contain the requested region).
3632 */
3633 if( fstat(pShmNode->h, &sStat) ){
3634 rc = SQLITE_IOERR_SHMSIZE;
3635 goto shmpage_out;
3636 }
3637
3638 if( sStat.st_size<nByte ){
3639 /* The requested memory region does not exist. If bExtend is set to
3640 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3641 **
3642 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3643 ** the requested memory region.
3644 */
3645 if( !bExtend ) goto shmpage_out;
drhff812312011-02-23 13:33:46 +00003646 if( robust_ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003647 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003648 goto shmpage_out;
3649 }
3650 }
3651
3652 /* Map the requested memory region into this processes address space. */
3653 apNew = (char **)sqlite3_realloc(
3654 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3655 );
3656 if( !apNew ){
3657 rc = SQLITE_IOERR_NOMEM;
3658 goto shmpage_out;
3659 }
3660 pShmNode->apRegion = apNew;
3661 while(pShmNode->nRegion<=iRegion){
3662 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003663 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003664 );
3665 if( pMem==MAP_FAILED ){
3666 rc = SQLITE_IOERR;
3667 goto shmpage_out;
3668 }
3669 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3670 pShmNode->nRegion++;
3671 }
3672 }
3673
3674shmpage_out:
3675 if( pShmNode->nRegion>iRegion ){
3676 *pp = pShmNode->apRegion[iRegion];
3677 }else{
3678 *pp = 0;
3679 }
3680 sqlite3_mutex_leave(pShmNode->mutex);
3681 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003682}
3683
3684/*
drhd9e5c4f2010-05-12 18:01:39 +00003685** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003686**
3687** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3688** different here than in posix. In xShmLock(), one can go from unlocked
3689** to shared and back or from unlocked to exclusive and back. But one may
3690** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003691*/
3692static int unixShmLock(
3693 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003694 int ofst, /* First lock to acquire or release */
3695 int n, /* Number of locks to acquire or release */
3696 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003697){
drh73b64e42010-05-30 19:55:15 +00003698 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3699 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3700 unixShm *pX; /* For looping over all siblings */
3701 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3702 int rc = SQLITE_OK; /* Result code */
3703 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003704
drhd91c68f2010-05-14 14:52:25 +00003705 assert( pShmNode==pDbFd->pInode->pShmNode );
3706 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003707 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003708 assert( n>=1 );
3709 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3710 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3711 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3712 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3713 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003714
drhc99597c2010-05-31 01:41:15 +00003715 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003716 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003717 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003718 if( flags & SQLITE_SHM_UNLOCK ){
3719 u16 allMask = 0; /* Mask of locks held by siblings */
3720
3721 /* See if any siblings hold this same lock */
3722 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3723 if( pX==p ) continue;
3724 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3725 allMask |= pX->sharedMask;
3726 }
3727
3728 /* Unlock the system-level locks */
3729 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003730 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003731 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003732 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003733 }
drh73b64e42010-05-30 19:55:15 +00003734
3735 /* Undo the local locks */
3736 if( rc==SQLITE_OK ){
3737 p->exclMask &= ~mask;
3738 p->sharedMask &= ~mask;
3739 }
3740 }else if( flags & SQLITE_SHM_SHARED ){
3741 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3742
3743 /* Find out which shared locks are already held by sibling connections.
3744 ** If any sibling already holds an exclusive lock, go ahead and return
3745 ** SQLITE_BUSY.
3746 */
3747 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003748 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003749 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003750 break;
3751 }
3752 allShared |= pX->sharedMask;
3753 }
3754
3755 /* Get shared locks at the system level, if necessary */
3756 if( rc==SQLITE_OK ){
3757 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003758 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003759 }else{
drh73b64e42010-05-30 19:55:15 +00003760 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003761 }
drhd9e5c4f2010-05-12 18:01:39 +00003762 }
drh73b64e42010-05-30 19:55:15 +00003763
3764 /* Get the local shared locks */
3765 if( rc==SQLITE_OK ){
3766 p->sharedMask |= mask;
3767 }
3768 }else{
3769 /* Make sure no sibling connections hold locks that will block this
3770 ** lock. If any do, return SQLITE_BUSY right away.
3771 */
3772 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003773 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3774 rc = SQLITE_BUSY;
3775 break;
3776 }
3777 }
3778
3779 /* Get the exclusive locks at the system level. Then if successful
3780 ** also mark the local connection as being locked.
3781 */
3782 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003783 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003784 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003785 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003786 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003787 }
drhd9e5c4f2010-05-12 18:01:39 +00003788 }
3789 }
drhd91c68f2010-05-14 14:52:25 +00003790 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003791 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3792 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003793 return rc;
3794}
3795
drh286a2882010-05-20 23:51:06 +00003796/*
3797** Implement a memory barrier or memory fence on shared memory.
3798**
3799** All loads and stores begun before the barrier must complete before
3800** any load or store begun after the barrier.
3801*/
3802static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003803 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003804){
drhff828942010-06-26 21:34:06 +00003805 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003806 unixEnterMutex();
3807 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003808}
3809
dan18801912010-06-14 14:07:50 +00003810/*
danda9fe0c2010-07-13 18:44:03 +00003811** Close a connection to shared-memory. Delete the underlying
3812** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003813**
3814** If there is no shared memory associated with the connection then this
3815** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003816*/
danda9fe0c2010-07-13 18:44:03 +00003817static int unixShmUnmap(
3818 sqlite3_file *fd, /* The underlying database file */
3819 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003820){
danda9fe0c2010-07-13 18:44:03 +00003821 unixShm *p; /* The connection to be closed */
3822 unixShmNode *pShmNode; /* The underlying shared-memory file */
3823 unixShm **pp; /* For looping over sibling connections */
3824 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003825
danda9fe0c2010-07-13 18:44:03 +00003826 pDbFd = (unixFile*)fd;
3827 p = pDbFd->pShm;
3828 if( p==0 ) return SQLITE_OK;
3829 pShmNode = p->pShmNode;
3830
3831 assert( pShmNode==pDbFd->pInode->pShmNode );
3832 assert( pShmNode->pInode==pDbFd->pInode );
3833
3834 /* Remove connection p from the set of connections associated
3835 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003836 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003837 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3838 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003839
danda9fe0c2010-07-13 18:44:03 +00003840 /* Free the connection p */
3841 sqlite3_free(p);
3842 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003843 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003844
3845 /* If pShmNode->nRef has reached 0, then close the underlying
3846 ** shared-memory file, too */
3847 unixEnterMutex();
3848 assert( pShmNode->nRef>0 );
3849 pShmNode->nRef--;
3850 if( pShmNode->nRef==0 ){
3851 if( deleteFlag ) unlink(pShmNode->zFilename);
3852 unixShmPurge(pDbFd);
3853 }
3854 unixLeaveMutex();
3855
3856 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003857}
drh286a2882010-05-20 23:51:06 +00003858
danda9fe0c2010-07-13 18:44:03 +00003859
drhd9e5c4f2010-05-12 18:01:39 +00003860#else
drh6b017cc2010-06-14 18:01:46 +00003861# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003862# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003863# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003864# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003865#endif /* #ifndef SQLITE_OMIT_WAL */
3866
drh734c9862008-11-28 15:37:20 +00003867/*
3868** Here ends the implementation of all sqlite3_file methods.
3869**
3870********************** End sqlite3_file Methods *******************************
3871******************************************************************************/
3872
3873/*
drh6b9d6dd2008-12-03 19:34:47 +00003874** This division contains definitions of sqlite3_io_methods objects that
3875** implement various file locking strategies. It also contains definitions
3876** of "finder" functions. A finder-function is used to locate the appropriate
3877** sqlite3_io_methods object for a particular database file. The pAppData
3878** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3879** the correct finder-function for that VFS.
3880**
3881** Most finder functions return a pointer to a fixed sqlite3_io_methods
3882** object. The only interesting finder-function is autolockIoFinder, which
3883** looks at the filesystem type and tries to guess the best locking
3884** strategy from that.
3885**
drh1875f7a2008-12-08 18:19:17 +00003886** For finder-funtion F, two objects are created:
3887**
3888** (1) The real finder-function named "FImpt()".
3889**
dane946c392009-08-22 11:39:46 +00003890** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003891**
3892**
3893** A pointer to the F pointer is used as the pAppData value for VFS
3894** objects. We have to do this instead of letting pAppData point
3895** directly at the finder-function since C90 rules prevent a void*
3896** from be cast into a function pointer.
3897**
drh6b9d6dd2008-12-03 19:34:47 +00003898**
drh7708e972008-11-29 00:56:52 +00003899** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003900**
drh7708e972008-11-29 00:56:52 +00003901** * A constant sqlite3_io_methods object call METHOD that has locking
3902** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3903**
3904** * An I/O method finder function called FINDER that returns a pointer
3905** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003906*/
drhd9e5c4f2010-05-12 18:01:39 +00003907#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003908static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003909 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003910 CLOSE, /* xClose */ \
3911 unixRead, /* xRead */ \
3912 unixWrite, /* xWrite */ \
3913 unixTruncate, /* xTruncate */ \
3914 unixSync, /* xSync */ \
3915 unixFileSize, /* xFileSize */ \
3916 LOCK, /* xLock */ \
3917 UNLOCK, /* xUnlock */ \
3918 CKLOCK, /* xCheckReservedLock */ \
3919 unixFileControl, /* xFileControl */ \
3920 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003921 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003922 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00003923 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00003924 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00003925 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00003926}; \
drh0c2694b2009-09-03 16:23:44 +00003927static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3928 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003929 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003930} \
drh0c2694b2009-09-03 16:23:44 +00003931static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003932 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003933
3934/*
3935** Here are all of the sqlite3_io_methods objects for each of the
3936** locking strategies. Functions that return pointers to these methods
3937** are also created.
3938*/
3939IOMETHODS(
3940 posixIoFinder, /* Finder function name */
3941 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003942 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00003943 unixClose, /* xClose method */
3944 unixLock, /* xLock method */
3945 unixUnlock, /* xUnlock method */
3946 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003947)
drh7708e972008-11-29 00:56:52 +00003948IOMETHODS(
3949 nolockIoFinder, /* Finder function name */
3950 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003951 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003952 nolockClose, /* xClose method */
3953 nolockLock, /* xLock method */
3954 nolockUnlock, /* xUnlock method */
3955 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003956)
drh7708e972008-11-29 00:56:52 +00003957IOMETHODS(
3958 dotlockIoFinder, /* Finder function name */
3959 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003960 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003961 dotlockClose, /* xClose method */
3962 dotlockLock, /* xLock method */
3963 dotlockUnlock, /* xUnlock method */
3964 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003965)
drh7708e972008-11-29 00:56:52 +00003966
chw78a13182009-04-07 05:35:03 +00003967#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003968IOMETHODS(
3969 flockIoFinder, /* Finder function name */
3970 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003971 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003972 flockClose, /* xClose method */
3973 flockLock, /* xLock method */
3974 flockUnlock, /* xUnlock method */
3975 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003976)
drh7708e972008-11-29 00:56:52 +00003977#endif
3978
drh6c7d5c52008-11-21 20:32:33 +00003979#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003980IOMETHODS(
3981 semIoFinder, /* Finder function name */
3982 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003983 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003984 semClose, /* xClose method */
3985 semLock, /* xLock method */
3986 semUnlock, /* xUnlock method */
3987 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003988)
aswiftaebf4132008-11-21 00:10:35 +00003989#endif
drh7708e972008-11-29 00:56:52 +00003990
drhd2cb50b2009-01-09 21:41:17 +00003991#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003992IOMETHODS(
3993 afpIoFinder, /* Finder function name */
3994 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00003995 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00003996 afpClose, /* xClose method */
3997 afpLock, /* xLock method */
3998 afpUnlock, /* xUnlock method */
3999 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004000)
drh715ff302008-12-03 22:32:44 +00004001#endif
4002
4003/*
4004** The proxy locking method is a "super-method" in the sense that it
4005** opens secondary file descriptors for the conch and lock files and
4006** it uses proxy, dot-file, AFP, and flock() locking methods on those
4007** secondary files. For this reason, the division that implements
4008** proxy locking is located much further down in the file. But we need
4009** to go ahead and define the sqlite3_io_methods and finder function
4010** for proxy locking here. So we forward declare the I/O methods.
4011*/
drhd2cb50b2009-01-09 21:41:17 +00004012#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004013static int proxyClose(sqlite3_file*);
4014static int proxyLock(sqlite3_file*, int);
4015static int proxyUnlock(sqlite3_file*, int);
4016static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004017IOMETHODS(
4018 proxyIoFinder, /* Finder function name */
4019 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004020 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004021 proxyClose, /* xClose method */
4022 proxyLock, /* xLock method */
4023 proxyUnlock, /* xUnlock method */
4024 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004025)
aswiftaebf4132008-11-21 00:10:35 +00004026#endif
drh7708e972008-11-29 00:56:52 +00004027
drh7ed97b92010-01-20 13:07:21 +00004028/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4029#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4030IOMETHODS(
4031 nfsIoFinder, /* Finder function name */
4032 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004033 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004034 unixClose, /* xClose method */
4035 unixLock, /* xLock method */
4036 nfsUnlock, /* xUnlock method */
4037 unixCheckReservedLock /* xCheckReservedLock method */
4038)
4039#endif
drh7708e972008-11-29 00:56:52 +00004040
drhd2cb50b2009-01-09 21:41:17 +00004041#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004042/*
drh6b9d6dd2008-12-03 19:34:47 +00004043** This "finder" function attempts to determine the best locking strategy
4044** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004045** object that implements that strategy.
4046**
4047** This is for MacOSX only.
4048*/
drh1875f7a2008-12-08 18:19:17 +00004049static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004050 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004051 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004052){
4053 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004054 const char *zFilesystem; /* Filesystem type name */
4055 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004056 } aMap[] = {
4057 { "hfs", &posixIoMethods },
4058 { "ufs", &posixIoMethods },
4059 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004060 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004061 { "webdav", &nolockIoMethods },
4062 { 0, 0 }
4063 };
4064 int i;
4065 struct statfs fsInfo;
4066 struct flock lockInfo;
4067
4068 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004069 /* If filePath==NULL that means we are dealing with a transient file
4070 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004071 return &nolockIoMethods;
4072 }
4073 if( statfs(filePath, &fsInfo) != -1 ){
4074 if( fsInfo.f_flags & MNT_RDONLY ){
4075 return &nolockIoMethods;
4076 }
4077 for(i=0; aMap[i].zFilesystem; i++){
4078 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4079 return aMap[i].pMethods;
4080 }
4081 }
4082 }
4083
4084 /* Default case. Handles, amongst others, "nfs".
4085 ** Test byte-range lock using fcntl(). If the call succeeds,
4086 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004087 */
drh7708e972008-11-29 00:56:52 +00004088 lockInfo.l_len = 1;
4089 lockInfo.l_start = 0;
4090 lockInfo.l_whence = SEEK_SET;
4091 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004092 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004093 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4094 return &nfsIoMethods;
4095 } else {
4096 return &posixIoMethods;
4097 }
drh7708e972008-11-29 00:56:52 +00004098 }else{
4099 return &dotlockIoMethods;
4100 }
4101}
drh0c2694b2009-09-03 16:23:44 +00004102static const sqlite3_io_methods
4103 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004104
drhd2cb50b2009-01-09 21:41:17 +00004105#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004106
chw78a13182009-04-07 05:35:03 +00004107#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4108/*
4109** This "finder" function attempts to determine the best locking strategy
4110** for the database file "filePath". It then returns the sqlite3_io_methods
4111** object that implements that strategy.
4112**
4113** This is for VXWorks only.
4114*/
4115static const sqlite3_io_methods *autolockIoFinderImpl(
4116 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004117 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004118){
4119 struct flock lockInfo;
4120
4121 if( !filePath ){
4122 /* If filePath==NULL that means we are dealing with a transient file
4123 ** that does not need to be locked. */
4124 return &nolockIoMethods;
4125 }
4126
4127 /* Test if fcntl() is supported and use POSIX style locks.
4128 ** Otherwise fall back to the named semaphore method.
4129 */
4130 lockInfo.l_len = 1;
4131 lockInfo.l_start = 0;
4132 lockInfo.l_whence = SEEK_SET;
4133 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004134 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004135 return &posixIoMethods;
4136 }else{
4137 return &semIoMethods;
4138 }
4139}
drh0c2694b2009-09-03 16:23:44 +00004140static const sqlite3_io_methods
4141 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004142
4143#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4144
drh7708e972008-11-29 00:56:52 +00004145/*
4146** An abstract type for a pointer to a IO method finder function:
4147*/
drh0c2694b2009-09-03 16:23:44 +00004148typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004149
aswiftaebf4132008-11-21 00:10:35 +00004150
drh734c9862008-11-28 15:37:20 +00004151/****************************************************************************
4152**************************** sqlite3_vfs methods ****************************
4153**
4154** This division contains the implementation of methods on the
4155** sqlite3_vfs object.
4156*/
4157
danielk1977a3d4c882007-03-23 10:08:38 +00004158/*
danielk1977e339d652008-06-28 11:23:00 +00004159** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004160*/
4161static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004162 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004163 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004164 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004165 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004166 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004167 int noLock, /* Omit locking if true */
4168 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004169){
drh7708e972008-11-29 00:56:52 +00004170 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004171 unixFile *pNew = (unixFile *)pId;
4172 int rc = SQLITE_OK;
4173
drh8af6c222010-05-14 12:43:01 +00004174 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004175
dane946c392009-08-22 11:39:46 +00004176 /* Parameter isDelete is only used on vxworks. Express this explicitly
4177 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004178 */
drh7708e972008-11-29 00:56:52 +00004179 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004180
dan00157392010-10-05 11:33:15 +00004181 /* Usually the path zFilename should not be a relative pathname. The
4182 ** exception is when opening the proxy "conch" file in builds that
4183 ** include the special Apple locking styles.
4184 */
dan00157392010-10-05 11:33:15 +00004185#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004186 assert( zFilename==0 || zFilename[0]=='/'
4187 || pVfs->pAppData==(void*)&autolockIoFinder );
4188#else
4189 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004190#endif
dan00157392010-10-05 11:33:15 +00004191
drh308c2a52010-05-14 11:30:18 +00004192 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004193 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004194 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004195 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004196 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004197
drh6c7d5c52008-11-21 20:32:33 +00004198#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004199 pNew->pId = vxworksFindFileId(zFilename);
4200 if( pNew->pId==0 ){
4201 noLock = 1;
4202 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004203 }
4204#endif
4205
drhda0e7682008-07-30 15:27:54 +00004206 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004207 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004208 }else{
drh0c2694b2009-09-03 16:23:44 +00004209 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004210#if SQLITE_ENABLE_LOCKING_STYLE
4211 /* Cache zFilename in the locking context (AFP and dotlock override) for
4212 ** proxyLock activation is possible (remote proxy is based on db name)
4213 ** zFilename remains valid until file is closed, to support */
4214 pNew->lockingContext = (void*)zFilename;
4215#endif
drhda0e7682008-07-30 15:27:54 +00004216 }
danielk1977e339d652008-06-28 11:23:00 +00004217
drh7ed97b92010-01-20 13:07:21 +00004218 if( pLockingStyle == &posixIoMethods
4219#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4220 || pLockingStyle == &nfsIoMethods
4221#endif
4222 ){
drh7708e972008-11-29 00:56:52 +00004223 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004224 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004225 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004226 /* If an error occured in findInodeInfo(), close the file descriptor
4227 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004228 ** in two scenarios:
4229 **
4230 ** (a) A call to fstat() failed.
4231 ** (b) A malloc failed.
4232 **
4233 ** Scenario (b) may only occur if the process is holding no other
4234 ** file descriptors open on the same file. If there were other file
4235 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004236 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004237 ** handle h - as it is guaranteed that no posix locks will be released
4238 ** by doing so.
4239 **
4240 ** If scenario (a) caused the error then things are not so safe. The
4241 ** implicit assumption here is that if fstat() fails, things are in
4242 ** such bad shape that dropping a lock or two doesn't matter much.
4243 */
drh0e9365c2011-03-02 02:08:13 +00004244 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004245 h = -1;
4246 }
drh7708e972008-11-29 00:56:52 +00004247 unixLeaveMutex();
4248 }
danielk1977e339d652008-06-28 11:23:00 +00004249
drhd2cb50b2009-01-09 21:41:17 +00004250#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004251 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004252 /* AFP locking uses the file path so it needs to be included in
4253 ** the afpLockingContext.
4254 */
4255 afpLockingContext *pCtx;
4256 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4257 if( pCtx==0 ){
4258 rc = SQLITE_NOMEM;
4259 }else{
4260 /* NB: zFilename exists and remains valid until the file is closed
4261 ** according to requirement F11141. So we do not need to make a
4262 ** copy of the filename. */
4263 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004264 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004265 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004266 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004267 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004268 if( rc!=SQLITE_OK ){
4269 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004270 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004271 h = -1;
4272 }
drh7708e972008-11-29 00:56:52 +00004273 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004274 }
drh7708e972008-11-29 00:56:52 +00004275 }
4276#endif
danielk1977e339d652008-06-28 11:23:00 +00004277
drh7708e972008-11-29 00:56:52 +00004278 else if( pLockingStyle == &dotlockIoMethods ){
4279 /* Dotfile locking uses the file path so it needs to be included in
4280 ** the dotlockLockingContext
4281 */
4282 char *zLockFile;
4283 int nFilename;
drhea678832008-12-10 19:26:22 +00004284 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004285 zLockFile = (char *)sqlite3_malloc(nFilename);
4286 if( zLockFile==0 ){
4287 rc = SQLITE_NOMEM;
4288 }else{
4289 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004290 }
drh7708e972008-11-29 00:56:52 +00004291 pNew->lockingContext = zLockFile;
4292 }
danielk1977e339d652008-06-28 11:23:00 +00004293
drh6c7d5c52008-11-21 20:32:33 +00004294#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004295 else if( pLockingStyle == &semIoMethods ){
4296 /* Named semaphore locking uses the file path so it needs to be
4297 ** included in the semLockingContext
4298 */
4299 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004300 rc = findInodeInfo(pNew, &pNew->pInode);
4301 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4302 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004303 int n;
drh2238dcc2009-08-27 17:56:20 +00004304 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004305 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004306 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004307 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004308 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4309 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004310 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004311 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004312 }
chw97185482008-11-17 08:05:31 +00004313 }
drh7708e972008-11-29 00:56:52 +00004314 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004315 }
drh7708e972008-11-29 00:56:52 +00004316#endif
aswift5b1a2562008-08-22 00:22:35 +00004317
4318 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004319#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004320 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004321 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004322 h = -1;
chw97185482008-11-17 08:05:31 +00004323 unlink(zFilename);
4324 isDelete = 0;
4325 }
4326 pNew->isDelete = isDelete;
4327#endif
danielk1977e339d652008-06-28 11:23:00 +00004328 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004329 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4330 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004331 }else{
drh7708e972008-11-29 00:56:52 +00004332 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004333 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004334 }
danielk1977e339d652008-06-28 11:23:00 +00004335 return rc;
drh054889e2005-11-30 03:20:31 +00004336}
drh9c06c952005-11-26 00:25:00 +00004337
danielk1977ad94b582007-08-20 06:44:22 +00004338/*
4339** Open a file descriptor to the directory containing file zFilename.
4340** If successful, *pFd is set to the opened file descriptor and
4341** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4342** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4343** value.
4344**
4345** If SQLITE_OK is returned, the caller is responsible for closing
4346** the file descriptor *pFd using close().
4347*/
danielk1977fee2d252007-08-18 10:59:19 +00004348static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004349 int ii;
drh777b17a2007-09-20 10:02:54 +00004350 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004351 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004352
drh153c62c2007-08-24 03:51:33 +00004353 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004354 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004355 if( ii>0 ){
4356 zDirname[ii] = '\0';
4357 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004358 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004359#ifdef FD_CLOEXEC
4360 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4361#endif
drh308c2a52010-05-14 11:30:18 +00004362 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004363 }
4364 }
danielk1977fee2d252007-08-18 10:59:19 +00004365 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004366 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004367}
4368
danielk1977b4b47412007-08-17 15:53:36 +00004369/*
drh8b3cf822010-06-01 21:02:51 +00004370** Return the name of a directory in which to put temporary files.
4371** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004372*/
drh7234c6d2010-06-19 15:10:09 +00004373static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004374 static const char *azDirs[] = {
4375 0,
aswiftaebf4132008-11-21 00:10:35 +00004376 0,
danielk197717b90b52008-06-06 11:11:25 +00004377 "/var/tmp",
4378 "/usr/tmp",
4379 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004380 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004381 };
drh8b3cf822010-06-01 21:02:51 +00004382 unsigned int i;
4383 struct stat buf;
4384 const char *zDir = 0;
4385
4386 azDirs[0] = sqlite3_temp_directory;
4387 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004388 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004389 if( zDir==0 ) continue;
4390 if( stat(zDir, &buf) ) continue;
4391 if( !S_ISDIR(buf.st_mode) ) continue;
drh7234c6d2010-06-19 15:10:09 +00004392 if( access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004393 break;
4394 }
4395 return zDir;
4396}
4397
4398/*
4399** Create a temporary file name in zBuf. zBuf must be allocated
4400** by the calling process and must be big enough to hold at least
4401** pVfs->mxPathname bytes.
4402*/
4403static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004404 static const unsigned char zChars[] =
4405 "abcdefghijklmnopqrstuvwxyz"
4406 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4407 "0123456789";
drh41022642008-11-21 00:24:42 +00004408 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004409 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004410
4411 /* It's odd to simulate an io-error here, but really this is just
4412 ** using the io-error infrastructure to test that SQLite handles this
4413 ** function failing.
4414 */
4415 SimulateIOError( return SQLITE_IOERR );
4416
drh7234c6d2010-06-19 15:10:09 +00004417 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004418 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004419
4420 /* Check that the output buffer is large enough for the temporary file
4421 ** name. If it is not, return SQLITE_ERROR.
4422 */
danielk197700e13612008-11-17 19:18:54 +00004423 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004424 return SQLITE_ERROR;
4425 }
4426
4427 do{
4428 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004429 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004430 sqlite3_randomness(15, &zBuf[j]);
4431 for(i=0; i<15; i++, j++){
4432 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4433 }
4434 zBuf[j] = 0;
4435 }while( access(zBuf,0)==0 );
4436 return SQLITE_OK;
4437}
4438
drhd2cb50b2009-01-09 21:41:17 +00004439#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004440/*
4441** Routine to transform a unixFile into a proxy-locking unixFile.
4442** Implementation in the proxy-lock division, but used by unixOpen()
4443** if SQLITE_PREFER_PROXY_LOCKING is defined.
4444*/
4445static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004446#endif
drhc66d5b62008-12-03 22:48:32 +00004447
dan08da86a2009-08-21 17:18:03 +00004448/*
4449** Search for an unused file descriptor that was opened on the database
4450** file (not a journal or master-journal file) identified by pathname
4451** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4452** argument to this function.
4453**
4454** Such a file descriptor may exist if a database connection was closed
4455** but the associated file descriptor could not be closed because some
4456** other file descriptor open on the same file is holding a file-lock.
4457** Refer to comments in the unixClose() function and the lengthy comment
4458** describing "Posix Advisory Locking" at the start of this file for
4459** further details. Also, ticket #4018.
4460**
4461** If a suitable file descriptor is found, then it is returned. If no
4462** such file descriptor is located, -1 is returned.
4463*/
dane946c392009-08-22 11:39:46 +00004464static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4465 UnixUnusedFd *pUnused = 0;
4466
4467 /* Do not search for an unused file descriptor on vxworks. Not because
4468 ** vxworks would not benefit from the change (it might, we're not sure),
4469 ** but because no way to test it is currently available. It is better
4470 ** not to risk breaking vxworks support for the sake of such an obscure
4471 ** feature. */
4472#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004473 struct stat sStat; /* Results of stat() call */
4474
4475 /* A stat() call may fail for various reasons. If this happens, it is
4476 ** almost certain that an open() call on the same path will also fail.
4477 ** For this reason, if an error occurs in the stat() call here, it is
4478 ** ignored and -1 is returned. The caller will try to open a new file
4479 ** descriptor on the same path, fail, and return an error to SQLite.
4480 **
4481 ** Even if a subsequent open() call does succeed, the consequences of
4482 ** not searching for a resusable file descriptor are not dire. */
4483 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004484 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004485
4486 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004487 pInode = inodeList;
4488 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4489 || pInode->fileId.ino!=sStat.st_ino) ){
4490 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004491 }
drh8af6c222010-05-14 12:43:01 +00004492 if( pInode ){
dane946c392009-08-22 11:39:46 +00004493 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004494 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004495 pUnused = *pp;
4496 if( pUnused ){
4497 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004498 }
4499 }
4500 unixLeaveMutex();
4501 }
dane946c392009-08-22 11:39:46 +00004502#endif /* if !OS_VXWORKS */
4503 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004504}
danielk197717b90b52008-06-06 11:11:25 +00004505
4506/*
danddb0ac42010-07-14 14:48:58 +00004507** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004508** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004509** and a value suitable for passing as the third argument to open(2) is
4510** written to *pMode. If an IO error occurs, an SQLite error code is
4511** returned and the value of *pMode is not modified.
4512**
4513** If the file being opened is a temporary file, it is always created with
4514** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004515** is a database or master journal file, it is created with the permissions
4516** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004517**
drh8ab58662010-07-15 18:38:39 +00004518** Finally, if the file being opened is a WAL or regular journal file, then
4519** this function queries the file-system for the permissions on the
4520** corresponding database file and sets *pMode to this value. Whenever
4521** possible, WAL and journal files are created using the same permissions
4522** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004523*/
4524static int findCreateFileMode(
4525 const char *zPath, /* Path of file (possibly) being created */
4526 int flags, /* Flags passed as 4th argument to xOpen() */
4527 mode_t *pMode /* OUT: Permissions to open file with */
4528){
4529 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004530 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004531 char zDb[MAX_PATHNAME+1]; /* Database file path */
4532 int nDb; /* Number of valid bytes in zDb */
4533 struct stat sStat; /* Output of stat() on database file */
4534
dana0c989d2010-11-05 18:07:37 +00004535 /* zPath is a path to a WAL or journal file. The following block derives
4536 ** the path to the associated database file from zPath. This block handles
4537 ** the following naming conventions:
4538 **
4539 ** "<path to db>-journal"
4540 ** "<path to db>-wal"
4541 ** "<path to db>-journal-NNNN"
4542 ** "<path to db>-wal-NNNN"
4543 **
4544 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4545 ** used by the test_multiplex.c module.
4546 */
4547 nDb = sqlite3Strlen30(zPath) - 1;
4548 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4549 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004550 memcpy(zDb, zPath, nDb);
4551 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004552
danddb0ac42010-07-14 14:48:58 +00004553 if( 0==stat(zDb, &sStat) ){
4554 *pMode = sStat.st_mode & 0777;
4555 }else{
4556 rc = SQLITE_IOERR_FSTAT;
4557 }
4558 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4559 *pMode = 0600;
4560 }else{
4561 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4562 }
4563 return rc;
4564}
4565
4566/*
danielk1977ad94b582007-08-20 06:44:22 +00004567** Open the file zPath.
4568**
danielk1977b4b47412007-08-17 15:53:36 +00004569** Previously, the SQLite OS layer used three functions in place of this
4570** one:
4571**
4572** sqlite3OsOpenReadWrite();
4573** sqlite3OsOpenReadOnly();
4574** sqlite3OsOpenExclusive();
4575**
4576** These calls correspond to the following combinations of flags:
4577**
4578** ReadWrite() -> (READWRITE | CREATE)
4579** ReadOnly() -> (READONLY)
4580** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4581**
4582** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4583** true, the file was configured to be automatically deleted when the
4584** file handle closed. To achieve the same effect using this new
4585** interface, add the DELETEONCLOSE flag to those specified above for
4586** OpenExclusive().
4587*/
4588static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004589 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4590 const char *zPath, /* Pathname of file to be opened */
4591 sqlite3_file *pFile, /* The file descriptor to be filled in */
4592 int flags, /* Input flags to control the opening */
4593 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004594){
dan08da86a2009-08-21 17:18:03 +00004595 unixFile *p = (unixFile *)pFile;
4596 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004597 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004598 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004599 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004600 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004601 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004602
4603 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4604 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4605 int isCreate = (flags & SQLITE_OPEN_CREATE);
4606 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4607 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004608#if SQLITE_ENABLE_LOCKING_STYLE
4609 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4610#endif
danielk1977b4b47412007-08-17 15:53:36 +00004611
danielk1977fee2d252007-08-18 10:59:19 +00004612 /* If creating a master or main-file journal, this function will open
4613 ** a file-descriptor on the directory too. The first time unixSync()
4614 ** is called the directory file descriptor will be fsync()ed and close()d.
4615 */
danddb0ac42010-07-14 14:48:58 +00004616 int isOpenDirectory = (isCreate && (
4617 eType==SQLITE_OPEN_MASTER_JOURNAL
4618 || eType==SQLITE_OPEN_MAIN_JOURNAL
4619 || eType==SQLITE_OPEN_WAL
4620 ));
danielk1977fee2d252007-08-18 10:59:19 +00004621
danielk197717b90b52008-06-06 11:11:25 +00004622 /* If argument zPath is a NULL pointer, this function is required to open
4623 ** a temporary file. Use this buffer to store the file name in.
4624 */
4625 char zTmpname[MAX_PATHNAME+1];
4626 const char *zName = zPath;
4627
danielk1977fee2d252007-08-18 10:59:19 +00004628 /* Check the following statements are true:
4629 **
4630 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4631 ** (b) if CREATE is set, then READWRITE must also be set, and
4632 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004633 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004634 */
danielk1977b4b47412007-08-17 15:53:36 +00004635 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004636 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004637 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004638 assert(isDelete==0 || isCreate);
4639
danddb0ac42010-07-14 14:48:58 +00004640 /* The main DB, main journal, WAL file and master journal are never
4641 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004642 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4643 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4644 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004645 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004646
danielk1977fee2d252007-08-18 10:59:19 +00004647 /* Assert that the upper layer has set one of the "file-type" flags. */
4648 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4649 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4650 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004651 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004652 );
4653
dan08da86a2009-08-21 17:18:03 +00004654 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004655
dan08da86a2009-08-21 17:18:03 +00004656 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004657 UnixUnusedFd *pUnused;
4658 pUnused = findReusableFd(zName, flags);
4659 if( pUnused ){
4660 fd = pUnused->fd;
4661 }else{
dan6aa657f2009-08-24 18:57:58 +00004662 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004663 if( !pUnused ){
4664 return SQLITE_NOMEM;
4665 }
4666 }
4667 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004668 }else if( !zName ){
4669 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004670 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004671 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004672 if( rc!=SQLITE_OK ){
4673 return rc;
4674 }
4675 zName = zTmpname;
4676 }
4677
dan08da86a2009-08-21 17:18:03 +00004678 /* Determine the value of the flags parameter passed to POSIX function
4679 ** open(). These must be calculated even if open() is not called, as
4680 ** they may be stored as part of the file handle and used by the
4681 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004682 if( isReadonly ) openFlags |= O_RDONLY;
4683 if( isReadWrite ) openFlags |= O_RDWR;
4684 if( isCreate ) openFlags |= O_CREAT;
4685 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4686 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004687
danielk1977b4b47412007-08-17 15:53:36 +00004688 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004689 mode_t openMode; /* Permissions to create file with */
4690 rc = findCreateFileMode(zName, flags, &openMode);
4691 if( rc!=SQLITE_OK ){
4692 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004693 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004694 return rc;
4695 }
dane946c392009-08-22 11:39:46 +00004696 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004697 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004698 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4699 /* Failed to open the file for read/write access. Try read-only. */
4700 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004701 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004702 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004703 openFlags |= O_RDONLY;
4704 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004705 }
4706 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004707 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004708 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004709 }
danielk1977b4b47412007-08-17 15:53:36 +00004710 }
dan08da86a2009-08-21 17:18:03 +00004711 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004712 if( pOutFlags ){
4713 *pOutFlags = flags;
4714 }
4715
dane946c392009-08-22 11:39:46 +00004716 if( p->pUnused ){
4717 p->pUnused->fd = fd;
4718 p->pUnused->flags = flags;
4719 }
4720
danielk1977b4b47412007-08-17 15:53:36 +00004721 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004722#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004723 zPath = zName;
4724#else
danielk197717b90b52008-06-06 11:11:25 +00004725 unlink(zName);
chw97185482008-11-17 08:05:31 +00004726#endif
danielk1977b4b47412007-08-17 15:53:36 +00004727 }
drh41022642008-11-21 00:24:42 +00004728#if SQLITE_ENABLE_LOCKING_STYLE
4729 else{
dan08da86a2009-08-21 17:18:03 +00004730 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004731 }
4732#endif
4733
danielk1977fee2d252007-08-18 10:59:19 +00004734 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004735 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004736 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004737 /* It is safe to close fd at this point, because it is guaranteed not
4738 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004739 ** it would not be safe to close as this would release any locks held
4740 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004741 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00004742 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004743 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004744 }
4745 }
danielk1977e339d652008-06-28 11:23:00 +00004746
4747#ifdef FD_CLOEXEC
4748 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4749#endif
4750
drhda0e7682008-07-30 15:27:54 +00004751 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004752
drh7ed97b92010-01-20 13:07:21 +00004753
4754#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4755 struct statfs fsInfo;
4756 if( fstatfs(fd, &fsInfo) == -1 ){
4757 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00004758 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
4759 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004760 return SQLITE_IOERR_ACCESS;
4761 }
4762 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4763 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4764 }
4765#endif
4766
4767#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004768#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004769 isAutoProxy = 1;
4770#endif
4771 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004772 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4773 int useProxy = 0;
4774
dan08da86a2009-08-21 17:18:03 +00004775 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4776 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004777 if( envforce!=NULL ){
4778 useProxy = atoi(envforce)>0;
4779 }else{
4780 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004781 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004782 /* In theory, the close(fd) call is sub-optimal. If the file opened
4783 ** with fd is a database file, and there are other connections open
4784 ** on that file that are currently holding advisory locks on it,
4785 ** then the call to close() will cancel those locks. In practice,
4786 ** we're assuming that statfs() doesn't fail very often. At least
4787 ** not while other file descriptors opened by the same process on
4788 ** the same file are working. */
4789 p->lastErrno = errno;
4790 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00004791 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00004792 }
drh0e9365c2011-03-02 02:08:13 +00004793 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004794 rc = SQLITE_IOERR_ACCESS;
4795 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004796 }
4797 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4798 }
4799 if( useProxy ){
4800 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4801 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004802 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004803 if( rc!=SQLITE_OK ){
4804 /* Use unixClose to clean up the resources added in fillInUnixFile
4805 ** and clear all the structure's references. Specifically,
4806 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4807 */
4808 unixClose(pFile);
4809 return rc;
4810 }
aswiftaebf4132008-11-21 00:10:35 +00004811 }
dane946c392009-08-22 11:39:46 +00004812 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004813 }
4814 }
4815#endif
4816
dane946c392009-08-22 11:39:46 +00004817 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4818open_finished:
4819 if( rc!=SQLITE_OK ){
4820 sqlite3_free(p->pUnused);
4821 }
4822 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004823}
4824
dane946c392009-08-22 11:39:46 +00004825
danielk1977b4b47412007-08-17 15:53:36 +00004826/*
danielk1977fee2d252007-08-18 10:59:19 +00004827** Delete the file at zPath. If the dirSync argument is true, fsync()
4828** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004829*/
drh6b9d6dd2008-12-03 19:34:47 +00004830static int unixDelete(
4831 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4832 const char *zPath, /* Name of file to be deleted */
4833 int dirSync /* If true, fsync() directory after deleting file */
4834){
danielk1977fee2d252007-08-18 10:59:19 +00004835 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004836 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004837 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004838 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00004839 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00004840 }
danielk1977d39fa702008-10-16 13:27:40 +00004841#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004842 if( dirSync ){
4843 int fd;
4844 rc = openDirectory(zPath, &fd);
4845 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004846#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004847 if( fsync(fd)==-1 )
4848#else
4849 if( fsync(fd) )
4850#endif
4851 {
dane18d4952011-02-21 11:46:24 +00004852 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00004853 }
drh0e9365c2011-03-02 02:08:13 +00004854 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00004855 }
4856 }
danielk1977d138dd82008-10-15 16:02:48 +00004857#endif
danielk1977fee2d252007-08-18 10:59:19 +00004858 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004859}
4860
danielk197790949c22007-08-17 16:50:38 +00004861/*
4862** Test the existance of or access permissions of file zPath. The
4863** test performed depends on the value of flags:
4864**
4865** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4866** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4867** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4868**
4869** Otherwise return 0.
4870*/
danielk1977861f7452008-06-05 11:39:11 +00004871static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004872 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4873 const char *zPath, /* Path of the file to examine */
4874 int flags, /* What do we want to learn about the zPath file? */
4875 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004876){
rse25c0d1a2007-09-20 08:38:14 +00004877 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004878 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004879 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004880 switch( flags ){
4881 case SQLITE_ACCESS_EXISTS:
4882 amode = F_OK;
4883 break;
4884 case SQLITE_ACCESS_READWRITE:
4885 amode = W_OK|R_OK;
4886 break;
drh50d3f902007-08-27 21:10:36 +00004887 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004888 amode = R_OK;
4889 break;
4890
4891 default:
4892 assert(!"Invalid flags argument");
4893 }
danielk1977861f7452008-06-05 11:39:11 +00004894 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004895 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4896 struct stat buf;
4897 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4898 *pResOut = 0;
4899 }
4900 }
danielk1977861f7452008-06-05 11:39:11 +00004901 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004902}
4903
danielk1977b4b47412007-08-17 15:53:36 +00004904
4905/*
4906** Turn a relative pathname into a full pathname. The relative path
4907** is stored as a nul-terminated string in the buffer pointed to by
4908** zPath.
4909**
4910** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4911** (in this case, MAX_PATHNAME bytes). The full-path is written to
4912** this buffer before returning.
4913*/
danielk1977adfb9b02007-09-17 07:02:56 +00004914static int unixFullPathname(
4915 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4916 const char *zPath, /* Possibly relative input path */
4917 int nOut, /* Size of output buffer in bytes */
4918 char *zOut /* Output buffer */
4919){
danielk1977843e65f2007-09-01 16:16:15 +00004920
4921 /* It's odd to simulate an io-error here, but really this is just
4922 ** using the io-error infrastructure to test that SQLite handles this
4923 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004924 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004925 */
4926 SimulateIOError( return SQLITE_ERROR );
4927
drh153c62c2007-08-24 03:51:33 +00004928 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004929 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004930
drh3c7f2dc2007-12-06 13:26:20 +00004931 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004932 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004933 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004934 }else{
4935 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004936 if( getcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00004937 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004938 }
drhea678832008-12-10 19:26:22 +00004939 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004940 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004941 }
4942 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004943}
4944
drh0ccebe72005-06-07 22:22:50 +00004945
drh761df872006-12-21 01:29:22 +00004946#ifndef SQLITE_OMIT_LOAD_EXTENSION
4947/*
4948** Interfaces for opening a shared library, finding entry points
4949** within the shared library, and closing the shared library.
4950*/
4951#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004952static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4953 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004954 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4955}
danielk197795c8a542007-09-01 06:51:27 +00004956
4957/*
4958** SQLite calls this function immediately after a call to unixDlSym() or
4959** unixDlOpen() fails (returns a null pointer). If a more detailed error
4960** message is available, it is written to zBufOut. If no error message
4961** is available, zBufOut is left unmodified and SQLite uses a default
4962** error message.
4963*/
danielk1977397d65f2008-11-19 11:35:39 +00004964static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00004965 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004966 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004967 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004968 zErr = dlerror();
4969 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004970 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004971 }
drh6c7d5c52008-11-21 20:32:33 +00004972 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004973}
drh1875f7a2008-12-08 18:19:17 +00004974static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4975 /*
4976 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4977 ** cast into a pointer to a function. And yet the library dlsym() routine
4978 ** returns a void* which is really a pointer to a function. So how do we
4979 ** use dlsym() with -pedantic-errors?
4980 **
4981 ** Variable x below is defined to be a pointer to a function taking
4982 ** parameters void* and const char* and returning a pointer to a function.
4983 ** We initialize x by assigning it a pointer to the dlsym() function.
4984 ** (That assignment requires a cast.) Then we call the function that
4985 ** x points to.
4986 **
4987 ** This work-around is unlikely to work correctly on any system where
4988 ** you really cannot cast a function pointer into void*. But then, on the
4989 ** other hand, dlsym() will not work on such a system either, so we have
4990 ** not really lost anything.
4991 */
4992 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004993 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004994 x = (void(*(*)(void*,const char*))(void))dlsym;
4995 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004996}
danielk1977397d65f2008-11-19 11:35:39 +00004997static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4998 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004999 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005000}
danielk1977b4b47412007-08-17 15:53:36 +00005001#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5002 #define unixDlOpen 0
5003 #define unixDlError 0
5004 #define unixDlSym 0
5005 #define unixDlClose 0
5006#endif
5007
5008/*
danielk197790949c22007-08-17 16:50:38 +00005009** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005010*/
danielk1977397d65f2008-11-19 11:35:39 +00005011static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5012 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005013 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005014
drhbbd42a62004-05-22 17:41:58 +00005015 /* We have to initialize zBuf to prevent valgrind from reporting
5016 ** errors. The reports issued by valgrind are incorrect - we would
5017 ** prefer that the randomness be increased by making use of the
5018 ** uninitialized space in zBuf - but valgrind errors tend to worry
5019 ** some users. Rather than argue, it seems easier just to initialize
5020 ** the whole array and silence valgrind, even if that means less randomness
5021 ** in the random seed.
5022 **
5023 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005024 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005025 ** tests repeatable.
5026 */
danielk1977b4b47412007-08-17 15:53:36 +00005027 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005028#if !defined(SQLITE_TEST)
5029 {
drh842b8642005-01-21 17:53:17 +00005030 int pid, fd;
5031 fd = open("/dev/urandom", O_RDONLY);
5032 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005033 time_t t;
5034 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005035 memcpy(zBuf, &t, sizeof(t));
5036 pid = getpid();
5037 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005038 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005039 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005040 }else{
drhff812312011-02-23 13:33:46 +00005041 do{ nBuf = read(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005042 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005043 }
drhbbd42a62004-05-22 17:41:58 +00005044 }
5045#endif
drh72cbd072008-10-14 17:58:38 +00005046 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005047}
5048
danielk1977b4b47412007-08-17 15:53:36 +00005049
drhbbd42a62004-05-22 17:41:58 +00005050/*
5051** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005052** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005053** The return value is the number of microseconds of sleep actually
5054** requested from the underlying operating system, a number which
5055** might be greater than or equal to the argument, but not less
5056** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005057*/
danielk1977397d65f2008-11-19 11:35:39 +00005058static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005059#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005060 struct timespec sp;
5061
5062 sp.tv_sec = microseconds / 1000000;
5063 sp.tv_nsec = (microseconds % 1000000) * 1000;
5064 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005065 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005066 return microseconds;
5067#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005068 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005069 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005070 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005071#else
danielk1977b4b47412007-08-17 15:53:36 +00005072 int seconds = (microseconds+999999)/1000000;
5073 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005074 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005075 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005076#endif
drh88f474a2006-01-02 20:00:12 +00005077}
5078
5079/*
drh6b9d6dd2008-12-03 19:34:47 +00005080** The following variable, if set to a non-zero value, is interpreted as
5081** the number of seconds since 1970 and is used to set the result of
5082** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005083*/
5084#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005085int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005086#endif
5087
5088/*
drhb7e8ea22010-05-03 14:32:30 +00005089** Find the current time (in Universal Coordinated Time). Write into *piNow
5090** the current time and date as a Julian Day number times 86_400_000. In
5091** other words, write into *piNow the number of milliseconds since the Julian
5092** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5093** proleptic Gregorian calendar.
5094**
5095** On success, return 0. Return 1 if the time and date cannot be found.
5096*/
5097static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5098 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5099#if defined(NO_GETTOD)
5100 time_t t;
5101 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005102 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005103#elif OS_VXWORKS
5104 struct timespec sNow;
5105 clock_gettime(CLOCK_REALTIME, &sNow);
5106 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5107#else
5108 struct timeval sNow;
5109 gettimeofday(&sNow, 0);
5110 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5111#endif
5112
5113#ifdef SQLITE_TEST
5114 if( sqlite3_current_time ){
5115 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5116 }
5117#endif
5118 UNUSED_PARAMETER(NotUsed);
5119 return 0;
5120}
5121
5122/*
drhbbd42a62004-05-22 17:41:58 +00005123** Find the current time (in Universal Coordinated Time). Write the
5124** current time and date as a Julian Day number into *prNow and
5125** return 0. Return 1 if the time and date cannot be found.
5126*/
danielk1977397d65f2008-11-19 11:35:39 +00005127static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005128 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005129 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005130 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005131 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005132 return 0;
5133}
danielk1977b4b47412007-08-17 15:53:36 +00005134
drh6b9d6dd2008-12-03 19:34:47 +00005135/*
5136** We added the xGetLastError() method with the intention of providing
5137** better low-level error messages when operating-system problems come up
5138** during SQLite operation. But so far, none of that has been implemented
5139** in the core. So this routine is never called. For now, it is merely
5140** a place-holder.
5141*/
danielk1977397d65f2008-11-19 11:35:39 +00005142static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5143 UNUSED_PARAMETER(NotUsed);
5144 UNUSED_PARAMETER(NotUsed2);
5145 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005146 return 0;
5147}
5148
drhf2424c52010-04-26 00:04:55 +00005149
5150/*
drh734c9862008-11-28 15:37:20 +00005151************************ End of sqlite3_vfs methods ***************************
5152******************************************************************************/
5153
drh715ff302008-12-03 22:32:44 +00005154/******************************************************************************
5155************************** Begin Proxy Locking ********************************
5156**
5157** Proxy locking is a "uber-locking-method" in this sense: It uses the
5158** other locking methods on secondary lock files. Proxy locking is a
5159** meta-layer over top of the primitive locking implemented above. For
5160** this reason, the division that implements of proxy locking is deferred
5161** until late in the file (here) after all of the other I/O methods have
5162** been defined - so that the primitive locking methods are available
5163** as services to help with the implementation of proxy locking.
5164**
5165****
5166**
5167** The default locking schemes in SQLite use byte-range locks on the
5168** database file to coordinate safe, concurrent access by multiple readers
5169** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5170** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5171** as POSIX read & write locks over fixed set of locations (via fsctl),
5172** on AFP and SMB only exclusive byte-range locks are available via fsctl
5173** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5174** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5175** address in the shared range is taken for a SHARED lock, the entire
5176** shared range is taken for an EXCLUSIVE lock):
5177**
5178** PENDING_BYTE 0x40000000
5179** RESERVED_BYTE 0x40000001
5180** SHARED_RANGE 0x40000002 -> 0x40000200
5181**
5182** This works well on the local file system, but shows a nearly 100x
5183** slowdown in read performance on AFP because the AFP client disables
5184** the read cache when byte-range locks are present. Enabling the read
5185** cache exposes a cache coherency problem that is present on all OS X
5186** supported network file systems. NFS and AFP both observe the
5187** close-to-open semantics for ensuring cache coherency
5188** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5189** address the requirements for concurrent database access by multiple
5190** readers and writers
5191** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5192**
5193** To address the performance and cache coherency issues, proxy file locking
5194** changes the way database access is controlled by limiting access to a
5195** single host at a time and moving file locks off of the database file
5196** and onto a proxy file on the local file system.
5197**
5198**
5199** Using proxy locks
5200** -----------------
5201**
5202** C APIs
5203**
5204** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5205** <proxy_path> | ":auto:");
5206** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5207**
5208**
5209** SQL pragmas
5210**
5211** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5212** PRAGMA [database.]lock_proxy_file
5213**
5214** Specifying ":auto:" means that if there is a conch file with a matching
5215** host ID in it, the proxy path in the conch file will be used, otherwise
5216** a proxy path based on the user's temp dir
5217** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5218** actual proxy file name is generated from the name and path of the
5219** database file. For example:
5220**
5221** For database path "/Users/me/foo.db"
5222** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5223**
5224** Once a lock proxy is configured for a database connection, it can not
5225** be removed, however it may be switched to a different proxy path via
5226** the above APIs (assuming the conch file is not being held by another
5227** connection or process).
5228**
5229**
5230** How proxy locking works
5231** -----------------------
5232**
5233** Proxy file locking relies primarily on two new supporting files:
5234**
5235** * conch file to limit access to the database file to a single host
5236** at a time
5237**
5238** * proxy file to act as a proxy for the advisory locks normally
5239** taken on the database
5240**
5241** The conch file - to use a proxy file, sqlite must first "hold the conch"
5242** by taking an sqlite-style shared lock on the conch file, reading the
5243** contents and comparing the host's unique host ID (see below) and lock
5244** proxy path against the values stored in the conch. The conch file is
5245** stored in the same directory as the database file and the file name
5246** is patterned after the database file name as ".<databasename>-conch".
5247** If the conch file does not exist, or it's contents do not match the
5248** host ID and/or proxy path, then the lock is escalated to an exclusive
5249** lock and the conch file contents is updated with the host ID and proxy
5250** path and the lock is downgraded to a shared lock again. If the conch
5251** is held by another process (with a shared lock), the exclusive lock
5252** will fail and SQLITE_BUSY is returned.
5253**
5254** The proxy file - a single-byte file used for all advisory file locks
5255** normally taken on the database file. This allows for safe sharing
5256** of the database file for multiple readers and writers on the same
5257** host (the conch ensures that they all use the same local lock file).
5258**
drh715ff302008-12-03 22:32:44 +00005259** Requesting the lock proxy does not immediately take the conch, it is
5260** only taken when the first request to lock database file is made.
5261** This matches the semantics of the traditional locking behavior, where
5262** opening a connection to a database file does not take a lock on it.
5263** The shared lock and an open file descriptor are maintained until
5264** the connection to the database is closed.
5265**
5266** The proxy file and the lock file are never deleted so they only need
5267** to be created the first time they are used.
5268**
5269** Configuration options
5270** ---------------------
5271**
5272** SQLITE_PREFER_PROXY_LOCKING
5273**
5274** Database files accessed on non-local file systems are
5275** automatically configured for proxy locking, lock files are
5276** named automatically using the same logic as
5277** PRAGMA lock_proxy_file=":auto:"
5278**
5279** SQLITE_PROXY_DEBUG
5280**
5281** Enables the logging of error messages during host id file
5282** retrieval and creation
5283**
drh715ff302008-12-03 22:32:44 +00005284** LOCKPROXYDIR
5285**
5286** Overrides the default directory used for lock proxy files that
5287** are named automatically via the ":auto:" setting
5288**
5289** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5290**
5291** Permissions to use when creating a directory for storing the
5292** lock proxy files, only used when LOCKPROXYDIR is not set.
5293**
5294**
5295** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5296** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5297** force proxy locking to be used for every database file opened, and 0
5298** will force automatic proxy locking to be disabled for all database
5299** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5300** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5301*/
5302
5303/*
5304** Proxy locking is only available on MacOSX
5305*/
drhd2cb50b2009-01-09 21:41:17 +00005306#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005307
drh715ff302008-12-03 22:32:44 +00005308/*
5309** The proxyLockingContext has the path and file structures for the remote
5310** and local proxy files in it
5311*/
5312typedef struct proxyLockingContext proxyLockingContext;
5313struct proxyLockingContext {
5314 unixFile *conchFile; /* Open conch file */
5315 char *conchFilePath; /* Name of the conch file */
5316 unixFile *lockProxy; /* Open proxy lock file */
5317 char *lockProxyPath; /* Name of the proxy lock file */
5318 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005319 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005320 void *oldLockingContext; /* Original lockingcontext to restore on close */
5321 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5322};
5323
drh7ed97b92010-01-20 13:07:21 +00005324/*
5325** The proxy lock file path for the database at dbPath is written into lPath,
5326** which must point to valid, writable memory large enough for a maxLen length
5327** file path.
drh715ff302008-12-03 22:32:44 +00005328*/
drh715ff302008-12-03 22:32:44 +00005329static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5330 int len;
5331 int dbLen;
5332 int i;
5333
5334#ifdef LOCKPROXYDIR
5335 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5336#else
5337# ifdef _CS_DARWIN_USER_TEMP_DIR
5338 {
drh7ed97b92010-01-20 13:07:21 +00005339 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005340 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5341 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005342 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005343 }
drh7ed97b92010-01-20 13:07:21 +00005344 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005345 }
5346# else
5347 len = strlcpy(lPath, "/tmp/", maxLen);
5348# endif
5349#endif
5350
5351 if( lPath[len-1]!='/' ){
5352 len = strlcat(lPath, "/", maxLen);
5353 }
5354
5355 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005356 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005357 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005358 char c = dbPath[i];
5359 lPath[i+len] = (c=='/')?'_':c;
5360 }
5361 lPath[i+len]='\0';
5362 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005363 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005364 return SQLITE_OK;
5365}
5366
drh7ed97b92010-01-20 13:07:21 +00005367/*
5368 ** Creates the lock file and any missing directories in lockPath
5369 */
5370static int proxyCreateLockPath(const char *lockPath){
5371 int i, len;
5372 char buf[MAXPATHLEN];
5373 int start = 0;
5374
5375 assert(lockPath!=NULL);
5376 /* try to create all the intermediate directories */
5377 len = (int)strlen(lockPath);
5378 buf[0] = lockPath[0];
5379 for( i=1; i<len; i++ ){
5380 if( lockPath[i] == '/' && (i - start > 0) ){
5381 /* only mkdir if leaf dir != "." or "/" or ".." */
5382 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5383 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5384 buf[i]='\0';
5385 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5386 int err=errno;
5387 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005388 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005389 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005390 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005391 return err;
5392 }
5393 }
5394 }
5395 start=i+1;
5396 }
5397 buf[i] = lockPath[i];
5398 }
drh308c2a52010-05-14 11:30:18 +00005399 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005400 return 0;
5401}
5402
drh715ff302008-12-03 22:32:44 +00005403/*
5404** Create a new VFS file descriptor (stored in memory obtained from
5405** sqlite3_malloc) and open the file named "path" in the file descriptor.
5406**
5407** The caller is responsible not only for closing the file descriptor
5408** but also for freeing the memory associated with the file descriptor.
5409*/
drh7ed97b92010-01-20 13:07:21 +00005410static int proxyCreateUnixFile(
5411 const char *path, /* path for the new unixFile */
5412 unixFile **ppFile, /* unixFile created and returned by ref */
5413 int islockfile /* if non zero missing dirs will be created */
5414) {
5415 int fd = -1;
5416 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005417 unixFile *pNew;
5418 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005419 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005420 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005421 int terrno = 0;
5422 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005423
drh7ed97b92010-01-20 13:07:21 +00005424 /* 1. first try to open/create the file
5425 ** 2. if that fails, and this is a lock file (not-conch), try creating
5426 ** the parent directories and then try again.
5427 ** 3. if that fails, try to open the file read-only
5428 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5429 */
5430 pUnused = findReusableFd(path, openFlags);
5431 if( pUnused ){
5432 fd = pUnused->fd;
5433 }else{
5434 pUnused = sqlite3_malloc(sizeof(*pUnused));
5435 if( !pUnused ){
5436 return SQLITE_NOMEM;
5437 }
5438 }
5439 if( fd<0 ){
5440 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5441 terrno = errno;
5442 if( fd<0 && errno==ENOENT && islockfile ){
5443 if( proxyCreateLockPath(path) == SQLITE_OK ){
5444 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5445 }
5446 }
5447 }
5448 if( fd<0 ){
5449 openFlags = O_RDONLY;
5450 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5451 terrno = errno;
5452 }
5453 if( fd<0 ){
5454 if( islockfile ){
5455 return SQLITE_BUSY;
5456 }
5457 switch (terrno) {
5458 case EACCES:
5459 return SQLITE_PERM;
5460 case EIO:
5461 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5462 default:
drh9978c972010-02-23 17:36:32 +00005463 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005464 }
5465 }
5466
5467 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5468 if( pNew==NULL ){
5469 rc = SQLITE_NOMEM;
5470 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005471 }
5472 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005473 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005474 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005475 pUnused->fd = fd;
5476 pUnused->flags = openFlags;
5477 pNew->pUnused = pUnused;
5478
5479 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5480 if( rc==SQLITE_OK ){
5481 *ppFile = pNew;
5482 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005483 }
drh7ed97b92010-01-20 13:07:21 +00005484end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005485 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005486 sqlite3_free(pNew);
5487 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005488 return rc;
5489}
5490
drh7ed97b92010-01-20 13:07:21 +00005491#ifdef SQLITE_TEST
5492/* simulate multiple hosts by creating unique hostid file paths */
5493int sqlite3_hostid_num = 0;
5494#endif
5495
5496#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5497
drh0ab216a2010-07-02 17:10:40 +00005498/* Not always defined in the headers as it ought to be */
5499extern int gethostuuid(uuid_t id, const struct timespec *wait);
5500
drh7ed97b92010-01-20 13:07:21 +00005501/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5502** bytes of writable memory.
5503*/
5504static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005505 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5506 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005507#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5508 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005509 {
5510 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5511 if( gethostuuid(pHostID, &timeout) ){
5512 int err = errno;
5513 if( pError ){
5514 *pError = err;
5515 }
5516 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005517 }
drh7ed97b92010-01-20 13:07:21 +00005518 }
drhe8b0c9b2010-09-25 14:13:17 +00005519#endif
drh7ed97b92010-01-20 13:07:21 +00005520#ifdef SQLITE_TEST
5521 /* simulate multiple hosts by creating unique hostid file paths */
5522 if( sqlite3_hostid_num != 0){
5523 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5524 }
5525#endif
5526
5527 return SQLITE_OK;
5528}
5529
5530/* The conch file contains the header, host id and lock file path
5531 */
5532#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5533#define PROXY_HEADERLEN 1 /* conch file header length */
5534#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5535#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5536
5537/*
5538** Takes an open conch file, copies the contents to a new path and then moves
5539** it back. The newly created file's file descriptor is assigned to the
5540** conch file structure and finally the original conch file descriptor is
5541** closed. Returns zero if successful.
5542*/
5543static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5544 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5545 unixFile *conchFile = pCtx->conchFile;
5546 char tPath[MAXPATHLEN];
5547 char buf[PROXY_MAXCONCHLEN];
5548 char *cPath = pCtx->conchFilePath;
5549 size_t readLen = 0;
5550 size_t pathLen = 0;
5551 char errmsg[64] = "";
5552 int fd = -1;
5553 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005554 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005555
5556 /* create a new path by replace the trailing '-conch' with '-break' */
5557 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5558 if( pathLen>MAXPATHLEN || pathLen<6 ||
5559 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005560 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005561 goto end_breaklock;
5562 }
5563 /* read the conch content */
5564 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5565 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005566 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005567 goto end_breaklock;
5568 }
5569 /* write it out to the temporary break file */
5570 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5571 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005572 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005573 goto end_breaklock;
5574 }
drh0ab216a2010-07-02 17:10:40 +00005575 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005576 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005577 goto end_breaklock;
5578 }
5579 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005580 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005581 goto end_breaklock;
5582 }
5583 rc = 0;
5584 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005585 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005586 conchFile->h = fd;
5587 conchFile->openFlags = O_RDWR | O_CREAT;
5588
5589end_breaklock:
5590 if( rc ){
5591 if( fd>=0 ){
5592 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005593 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005594 }
5595 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5596 }
5597 return rc;
5598}
5599
5600/* Take the requested lock on the conch file and break a stale lock if the
5601** host id matches.
5602*/
5603static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5604 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5605 unixFile *conchFile = pCtx->conchFile;
5606 int rc = SQLITE_OK;
5607 int nTries = 0;
5608 struct timespec conchModTime;
5609
5610 do {
5611 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5612 nTries ++;
5613 if( rc==SQLITE_BUSY ){
5614 /* If the lock failed (busy):
5615 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5616 * 2nd try: fail if the mod time changed or host id is different, wait
5617 * 10 sec and try again
5618 * 3rd try: break the lock unless the mod time has changed.
5619 */
5620 struct stat buf;
5621 if( fstat(conchFile->h, &buf) ){
5622 pFile->lastErrno = errno;
5623 return SQLITE_IOERR_LOCK;
5624 }
5625
5626 if( nTries==1 ){
5627 conchModTime = buf.st_mtimespec;
5628 usleep(500000); /* wait 0.5 sec and try the lock again*/
5629 continue;
5630 }
5631
5632 assert( nTries>1 );
5633 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5634 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5635 return SQLITE_BUSY;
5636 }
5637
5638 if( nTries==2 ){
5639 char tBuf[PROXY_MAXCONCHLEN];
5640 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5641 if( len<0 ){
5642 pFile->lastErrno = errno;
5643 return SQLITE_IOERR_LOCK;
5644 }
5645 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5646 /* don't break the lock if the host id doesn't match */
5647 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5648 return SQLITE_BUSY;
5649 }
5650 }else{
5651 /* don't break the lock on short read or a version mismatch */
5652 return SQLITE_BUSY;
5653 }
5654 usleep(10000000); /* wait 10 sec and try the lock again */
5655 continue;
5656 }
5657
5658 assert( nTries==3 );
5659 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5660 rc = SQLITE_OK;
5661 if( lockType==EXCLUSIVE_LOCK ){
5662 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5663 }
5664 if( !rc ){
5665 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5666 }
5667 }
5668 }
5669 } while( rc==SQLITE_BUSY && nTries<3 );
5670
5671 return rc;
5672}
5673
5674/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005675** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5676** lockPath means that the lockPath in the conch file will be used if the
5677** host IDs match, or a new lock path will be generated automatically
5678** and written to the conch file.
5679*/
5680static int proxyTakeConch(unixFile *pFile){
5681 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5682
drh7ed97b92010-01-20 13:07:21 +00005683 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005684 return SQLITE_OK;
5685 }else{
5686 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005687 uuid_t myHostID;
5688 int pError = 0;
5689 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005690 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005691 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005692 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005693 int createConch = 0;
5694 int hostIdMatch = 0;
5695 int readLen = 0;
5696 int tryOldLockPath = 0;
5697 int forceNewLockPath = 0;
5698
drh308c2a52010-05-14 11:30:18 +00005699 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5700 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005701
drh7ed97b92010-01-20 13:07:21 +00005702 rc = proxyGetHostID(myHostID, &pError);
5703 if( (rc&0xff)==SQLITE_IOERR ){
5704 pFile->lastErrno = pError;
5705 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005706 }
drh7ed97b92010-01-20 13:07:21 +00005707 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005708 if( rc!=SQLITE_OK ){
5709 goto end_takeconch;
5710 }
drh7ed97b92010-01-20 13:07:21 +00005711 /* read the existing conch file */
5712 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5713 if( readLen<0 ){
5714 /* I/O error: lastErrno set by seekAndRead */
5715 pFile->lastErrno = conchFile->lastErrno;
5716 rc = SQLITE_IOERR_READ;
5717 goto end_takeconch;
5718 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5719 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5720 /* a short read or version format mismatch means we need to create a new
5721 ** conch file.
5722 */
5723 createConch = 1;
5724 }
5725 /* if the host id matches and the lock path already exists in the conch
5726 ** we'll try to use the path there, if we can't open that path, we'll
5727 ** retry with a new auto-generated path
5728 */
5729 do { /* in case we need to try again for an :auto: named lock file */
5730
5731 if( !createConch && !forceNewLockPath ){
5732 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5733 PROXY_HOSTIDLEN);
5734 /* if the conch has data compare the contents */
5735 if( !pCtx->lockProxyPath ){
5736 /* for auto-named local lock file, just check the host ID and we'll
5737 ** use the local lock file path that's already in there
5738 */
5739 if( hostIdMatch ){
5740 size_t pathLen = (readLen - PROXY_PATHINDEX);
5741
5742 if( pathLen>=MAXPATHLEN ){
5743 pathLen=MAXPATHLEN-1;
5744 }
5745 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5746 lockPath[pathLen] = 0;
5747 tempLockPath = lockPath;
5748 tryOldLockPath = 1;
5749 /* create a copy of the lock path if the conch is taken */
5750 goto end_takeconch;
5751 }
5752 }else if( hostIdMatch
5753 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5754 readLen-PROXY_PATHINDEX)
5755 ){
5756 /* conch host and lock path match */
5757 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005758 }
drh7ed97b92010-01-20 13:07:21 +00005759 }
5760
5761 /* if the conch isn't writable and doesn't match, we can't take it */
5762 if( (conchFile->openFlags&O_RDWR) == 0 ){
5763 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005764 goto end_takeconch;
5765 }
drh7ed97b92010-01-20 13:07:21 +00005766
5767 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005768 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005769 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5770 tempLockPath = lockPath;
5771 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005772 }
drh7ed97b92010-01-20 13:07:21 +00005773
5774 /* update conch with host and path (this will fail if other process
5775 ** has a shared lock already), if the host id matches, use the big
5776 ** stick.
drh715ff302008-12-03 22:32:44 +00005777 */
drh7ed97b92010-01-20 13:07:21 +00005778 futimes(conchFile->h, NULL);
5779 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005780 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005781 /* We are trying for an exclusive lock but another thread in this
5782 ** same process is still holding a shared lock. */
5783 rc = SQLITE_BUSY;
5784 } else {
5785 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005786 }
drh715ff302008-12-03 22:32:44 +00005787 }else{
drh7ed97b92010-01-20 13:07:21 +00005788 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005789 }
drh7ed97b92010-01-20 13:07:21 +00005790 if( rc==SQLITE_OK ){
5791 char writeBuffer[PROXY_MAXCONCHLEN];
5792 int writeSize = 0;
5793
5794 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5795 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5796 if( pCtx->lockProxyPath!=NULL ){
5797 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5798 }else{
5799 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5800 }
5801 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00005802 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00005803 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5804 fsync(conchFile->h);
5805 /* If we created a new conch file (not just updated the contents of a
5806 ** valid conch file), try to match the permissions of the database
5807 */
5808 if( rc==SQLITE_OK && createConch ){
5809 struct stat buf;
5810 int err = fstat(pFile->h, &buf);
5811 if( err==0 ){
5812 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5813 S_IROTH|S_IWOTH);
5814 /* try to match the database file R/W permissions, ignore failure */
5815#ifndef SQLITE_PROXY_DEBUG
5816 fchmod(conchFile->h, cmode);
5817#else
drhff812312011-02-23 13:33:46 +00005818 do{
5819 rc = fchmod(conchFile->h, cmode);
5820 }while( rc==(-1) && errno==EINTR );
5821 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00005822 int code = errno;
5823 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5824 cmode, code, strerror(code));
5825 } else {
5826 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5827 }
5828 }else{
5829 int code = errno;
5830 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5831 err, code, strerror(code));
5832#endif
5833 }
drh715ff302008-12-03 22:32:44 +00005834 }
5835 }
drh7ed97b92010-01-20 13:07:21 +00005836 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5837
5838 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005839 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005840 if( rc==SQLITE_OK && pFile->openFlags ){
5841 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00005842 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005843 }
5844 pFile->h = -1;
5845 int fd = open(pCtx->dbPath, pFile->openFlags,
5846 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005847 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005848 if( fd>=0 ){
5849 pFile->h = fd;
5850 }else{
drh9978c972010-02-23 17:36:32 +00005851 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005852 during locking */
5853 }
5854 }
5855 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5856 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5857 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5858 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5859 /* we couldn't create the proxy lock file with the old lock file path
5860 ** so try again via auto-naming
5861 */
5862 forceNewLockPath = 1;
5863 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005864 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005865 }
5866 }
5867 if( rc==SQLITE_OK ){
5868 /* Need to make a copy of path if we extracted the value
5869 ** from the conch file or the path was allocated on the stack
5870 */
5871 if( tempLockPath ){
5872 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5873 if( !pCtx->lockProxyPath ){
5874 rc = SQLITE_NOMEM;
5875 }
5876 }
5877 }
5878 if( rc==SQLITE_OK ){
5879 pCtx->conchHeld = 1;
5880
5881 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5882 afpLockingContext *afpCtx;
5883 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5884 afpCtx->dbPath = pCtx->lockProxyPath;
5885 }
5886 } else {
5887 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5888 }
drh308c2a52010-05-14 11:30:18 +00005889 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5890 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005891 return rc;
drh308c2a52010-05-14 11:30:18 +00005892 } while (1); /* in case we need to retry the :auto: lock file -
5893 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005894 }
5895}
5896
5897/*
5898** If pFile holds a lock on a conch file, then release that lock.
5899*/
5900static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005901 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005902 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5903 unixFile *conchFile; /* Name of the conch file */
5904
5905 pCtx = (proxyLockingContext *)pFile->lockingContext;
5906 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005907 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005908 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005909 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005910 if( pCtx->conchHeld>0 ){
5911 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5912 }
drh715ff302008-12-03 22:32:44 +00005913 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005914 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5915 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005916 return rc;
5917}
5918
5919/*
5920** Given the name of a database file, compute the name of its conch file.
5921** Store the conch filename in memory obtained from sqlite3_malloc().
5922** Make *pConchPath point to the new name. Return SQLITE_OK on success
5923** or SQLITE_NOMEM if unable to obtain memory.
5924**
5925** The caller is responsible for ensuring that the allocated memory
5926** space is eventually freed.
5927**
5928** *pConchPath is set to NULL if a memory allocation error occurs.
5929*/
5930static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5931 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005932 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005933 char *conchPath; /* buffer in which to construct conch name */
5934
5935 /* Allocate space for the conch filename and initialize the name to
5936 ** the name of the original database file. */
5937 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5938 if( conchPath==0 ){
5939 return SQLITE_NOMEM;
5940 }
5941 memcpy(conchPath, dbPath, len+1);
5942
5943 /* now insert a "." before the last / character */
5944 for( i=(len-1); i>=0; i-- ){
5945 if( conchPath[i]=='/' ){
5946 i++;
5947 break;
5948 }
5949 }
5950 conchPath[i]='.';
5951 while ( i<len ){
5952 conchPath[i+1]=dbPath[i];
5953 i++;
5954 }
5955
5956 /* append the "-conch" suffix to the file */
5957 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005958 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005959
5960 return SQLITE_OK;
5961}
5962
5963
5964/* Takes a fully configured proxy locking-style unix file and switches
5965** the local lock file path
5966*/
5967static int switchLockProxyPath(unixFile *pFile, const char *path) {
5968 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5969 char *oldPath = pCtx->lockProxyPath;
5970 int rc = SQLITE_OK;
5971
drh308c2a52010-05-14 11:30:18 +00005972 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005973 return SQLITE_BUSY;
5974 }
5975
5976 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5977 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5978 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5979 return SQLITE_OK;
5980 }else{
5981 unixFile *lockProxy = pCtx->lockProxy;
5982 pCtx->lockProxy=NULL;
5983 pCtx->conchHeld = 0;
5984 if( lockProxy!=NULL ){
5985 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5986 if( rc ) return rc;
5987 sqlite3_free(lockProxy);
5988 }
5989 sqlite3_free(oldPath);
5990 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5991 }
5992
5993 return rc;
5994}
5995
5996/*
5997** pFile is a file that has been opened by a prior xOpen call. dbPath
5998** is a string buffer at least MAXPATHLEN+1 characters in size.
5999**
6000** This routine find the filename associated with pFile and writes it
6001** int dbPath.
6002*/
6003static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006004#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006005 if( pFile->pMethod == &afpIoMethods ){
6006 /* afp style keeps a reference to the db path in the filePath field
6007 ** of the struct */
drhea678832008-12-10 19:26:22 +00006008 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006009 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6010 } else
drh715ff302008-12-03 22:32:44 +00006011#endif
6012 if( pFile->pMethod == &dotlockIoMethods ){
6013 /* dot lock style uses the locking context to store the dot lock
6014 ** file path */
6015 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6016 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6017 }else{
6018 /* all other styles use the locking context to store the db file path */
6019 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006020 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006021 }
6022 return SQLITE_OK;
6023}
6024
6025/*
6026** Takes an already filled in unix file and alters it so all file locking
6027** will be performed on the local proxy lock file. The following fields
6028** are preserved in the locking context so that they can be restored and
6029** the unix structure properly cleaned up at close time:
6030** ->lockingContext
6031** ->pMethod
6032*/
6033static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6034 proxyLockingContext *pCtx;
6035 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6036 char *lockPath=NULL;
6037 int rc = SQLITE_OK;
6038
drh308c2a52010-05-14 11:30:18 +00006039 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006040 return SQLITE_BUSY;
6041 }
6042 proxyGetDbPathForUnixFile(pFile, dbPath);
6043 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6044 lockPath=NULL;
6045 }else{
6046 lockPath=(char *)path;
6047 }
6048
drh308c2a52010-05-14 11:30:18 +00006049 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6050 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006051
6052 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6053 if( pCtx==0 ){
6054 return SQLITE_NOMEM;
6055 }
6056 memset(pCtx, 0, sizeof(*pCtx));
6057
6058 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6059 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006060 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6061 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6062 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6063 ** (c) the file system is read-only, then enable no-locking access.
6064 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6065 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6066 */
6067 struct statfs fsInfo;
6068 struct stat conchInfo;
6069 int goLockless = 0;
6070
6071 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6072 int err = errno;
6073 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6074 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6075 }
6076 }
6077 if( goLockless ){
6078 pCtx->conchHeld = -1; /* read only FS/ lockless */
6079 rc = SQLITE_OK;
6080 }
6081 }
drh715ff302008-12-03 22:32:44 +00006082 }
6083 if( rc==SQLITE_OK && lockPath ){
6084 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6085 }
6086
6087 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006088 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6089 if( pCtx->dbPath==NULL ){
6090 rc = SQLITE_NOMEM;
6091 }
6092 }
6093 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006094 /* all memory is allocated, proxys are created and assigned,
6095 ** switch the locking context and pMethod then return.
6096 */
drh715ff302008-12-03 22:32:44 +00006097 pCtx->oldLockingContext = pFile->lockingContext;
6098 pFile->lockingContext = pCtx;
6099 pCtx->pOldMethod = pFile->pMethod;
6100 pFile->pMethod = &proxyIoMethods;
6101 }else{
6102 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006103 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006104 sqlite3_free(pCtx->conchFile);
6105 }
drhd56b1212010-08-11 06:14:15 +00006106 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006107 sqlite3_free(pCtx->conchFilePath);
6108 sqlite3_free(pCtx);
6109 }
drh308c2a52010-05-14 11:30:18 +00006110 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6111 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006112 return rc;
6113}
6114
6115
6116/*
6117** This routine handles sqlite3_file_control() calls that are specific
6118** to proxy locking.
6119*/
6120static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6121 switch( op ){
6122 case SQLITE_GET_LOCKPROXYFILE: {
6123 unixFile *pFile = (unixFile*)id;
6124 if( pFile->pMethod == &proxyIoMethods ){
6125 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6126 proxyTakeConch(pFile);
6127 if( pCtx->lockProxyPath ){
6128 *(const char **)pArg = pCtx->lockProxyPath;
6129 }else{
6130 *(const char **)pArg = ":auto: (not held)";
6131 }
6132 } else {
6133 *(const char **)pArg = NULL;
6134 }
6135 return SQLITE_OK;
6136 }
6137 case SQLITE_SET_LOCKPROXYFILE: {
6138 unixFile *pFile = (unixFile*)id;
6139 int rc = SQLITE_OK;
6140 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6141 if( pArg==NULL || (const char *)pArg==0 ){
6142 if( isProxyStyle ){
6143 /* turn off proxy locking - not supported */
6144 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6145 }else{
6146 /* turn off proxy locking - already off - NOOP */
6147 rc = SQLITE_OK;
6148 }
6149 }else{
6150 const char *proxyPath = (const char *)pArg;
6151 if( isProxyStyle ){
6152 proxyLockingContext *pCtx =
6153 (proxyLockingContext*)pFile->lockingContext;
6154 if( !strcmp(pArg, ":auto:")
6155 || (pCtx->lockProxyPath &&
6156 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6157 ){
6158 rc = SQLITE_OK;
6159 }else{
6160 rc = switchLockProxyPath(pFile, proxyPath);
6161 }
6162 }else{
6163 /* turn on proxy file locking */
6164 rc = proxyTransformUnixFile(pFile, proxyPath);
6165 }
6166 }
6167 return rc;
6168 }
6169 default: {
6170 assert( 0 ); /* The call assures that only valid opcodes are sent */
6171 }
6172 }
6173 /*NOTREACHED*/
6174 return SQLITE_ERROR;
6175}
6176
6177/*
6178** Within this division (the proxying locking implementation) the procedures
6179** above this point are all utilities. The lock-related methods of the
6180** proxy-locking sqlite3_io_method object follow.
6181*/
6182
6183
6184/*
6185** This routine checks if there is a RESERVED lock held on the specified
6186** file by this or any other process. If such a lock is held, set *pResOut
6187** to a non-zero value otherwise *pResOut is set to zero. The return value
6188** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6189*/
6190static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6191 unixFile *pFile = (unixFile*)id;
6192 int rc = proxyTakeConch(pFile);
6193 if( rc==SQLITE_OK ){
6194 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006195 if( pCtx->conchHeld>0 ){
6196 unixFile *proxy = pCtx->lockProxy;
6197 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6198 }else{ /* conchHeld < 0 is lockless */
6199 pResOut=0;
6200 }
drh715ff302008-12-03 22:32:44 +00006201 }
6202 return rc;
6203}
6204
6205/*
drh308c2a52010-05-14 11:30:18 +00006206** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006207** of the following:
6208**
6209** (1) SHARED_LOCK
6210** (2) RESERVED_LOCK
6211** (3) PENDING_LOCK
6212** (4) EXCLUSIVE_LOCK
6213**
6214** Sometimes when requesting one lock state, additional lock states
6215** are inserted in between. The locking might fail on one of the later
6216** transitions leaving the lock state different from what it started but
6217** still short of its goal. The following chart shows the allowed
6218** transitions and the inserted intermediate states:
6219**
6220** UNLOCKED -> SHARED
6221** SHARED -> RESERVED
6222** SHARED -> (PENDING) -> EXCLUSIVE
6223** RESERVED -> (PENDING) -> EXCLUSIVE
6224** PENDING -> EXCLUSIVE
6225**
6226** This routine will only increase a lock. Use the sqlite3OsUnlock()
6227** routine to lower a locking level.
6228*/
drh308c2a52010-05-14 11:30:18 +00006229static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006230 unixFile *pFile = (unixFile*)id;
6231 int rc = proxyTakeConch(pFile);
6232 if( rc==SQLITE_OK ){
6233 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006234 if( pCtx->conchHeld>0 ){
6235 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006236 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6237 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006238 }else{
6239 /* conchHeld < 0 is lockless */
6240 }
drh715ff302008-12-03 22:32:44 +00006241 }
6242 return rc;
6243}
6244
6245
6246/*
drh308c2a52010-05-14 11:30:18 +00006247** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006248** must be either NO_LOCK or SHARED_LOCK.
6249**
6250** If the locking level of the file descriptor is already at or below
6251** the requested locking level, this routine is a no-op.
6252*/
drh308c2a52010-05-14 11:30:18 +00006253static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006254 unixFile *pFile = (unixFile*)id;
6255 int rc = proxyTakeConch(pFile);
6256 if( rc==SQLITE_OK ){
6257 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006258 if( pCtx->conchHeld>0 ){
6259 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006260 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6261 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006262 }else{
6263 /* conchHeld < 0 is lockless */
6264 }
drh715ff302008-12-03 22:32:44 +00006265 }
6266 return rc;
6267}
6268
6269/*
6270** Close a file that uses proxy locks.
6271*/
6272static int proxyClose(sqlite3_file *id) {
6273 if( id ){
6274 unixFile *pFile = (unixFile*)id;
6275 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6276 unixFile *lockProxy = pCtx->lockProxy;
6277 unixFile *conchFile = pCtx->conchFile;
6278 int rc = SQLITE_OK;
6279
6280 if( lockProxy ){
6281 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6282 if( rc ) return rc;
6283 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6284 if( rc ) return rc;
6285 sqlite3_free(lockProxy);
6286 pCtx->lockProxy = 0;
6287 }
6288 if( conchFile ){
6289 if( pCtx->conchHeld ){
6290 rc = proxyReleaseConch(pFile);
6291 if( rc ) return rc;
6292 }
6293 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6294 if( rc ) return rc;
6295 sqlite3_free(conchFile);
6296 }
drhd56b1212010-08-11 06:14:15 +00006297 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006298 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006299 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006300 /* restore the original locking context and pMethod then close it */
6301 pFile->lockingContext = pCtx->oldLockingContext;
6302 pFile->pMethod = pCtx->pOldMethod;
6303 sqlite3_free(pCtx);
6304 return pFile->pMethod->xClose(id);
6305 }
6306 return SQLITE_OK;
6307}
6308
6309
6310
drhd2cb50b2009-01-09 21:41:17 +00006311#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006312/*
6313** The proxy locking style is intended for use with AFP filesystems.
6314** And since AFP is only supported on MacOSX, the proxy locking is also
6315** restricted to MacOSX.
6316**
6317**
6318******************* End of the proxy lock implementation **********************
6319******************************************************************************/
6320
drh734c9862008-11-28 15:37:20 +00006321/*
danielk1977e339d652008-06-28 11:23:00 +00006322** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006323**
6324** This routine registers all VFS implementations for unix-like operating
6325** systems. This routine, and the sqlite3_os_end() routine that follows,
6326** should be the only routines in this file that are visible from other
6327** files.
drh6b9d6dd2008-12-03 19:34:47 +00006328**
6329** This routine is called once during SQLite initialization and by a
6330** single thread. The memory allocation and mutex subsystems have not
6331** necessarily been initialized when this routine is called, and so they
6332** should not be used.
drh153c62c2007-08-24 03:51:33 +00006333*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006334int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006335 /*
6336 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006337 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6338 ** to the "finder" function. (pAppData is a pointer to a pointer because
6339 ** silly C90 rules prohibit a void* from being cast to a function pointer
6340 ** and so we have to go through the intermediate pointer to avoid problems
6341 ** when compiling with -pedantic-errors on GCC.)
6342 **
6343 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006344 ** finder-function. The finder-function returns a pointer to the
6345 ** sqlite_io_methods object that implements the desired locking
6346 ** behaviors. See the division above that contains the IOMETHODS
6347 ** macro for addition information on finder-functions.
6348 **
6349 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6350 ** object. But the "autolockIoFinder" available on MacOSX does a little
6351 ** more than that; it looks at the filesystem type that hosts the
6352 ** database file and tries to choose an locking method appropriate for
6353 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006354 */
drh7708e972008-11-29 00:56:52 +00006355 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006356 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006357 sizeof(unixFile), /* szOsFile */ \
6358 MAX_PATHNAME, /* mxPathname */ \
6359 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006360 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006361 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006362 unixOpen, /* xOpen */ \
6363 unixDelete, /* xDelete */ \
6364 unixAccess, /* xAccess */ \
6365 unixFullPathname, /* xFullPathname */ \
6366 unixDlOpen, /* xDlOpen */ \
6367 unixDlError, /* xDlError */ \
6368 unixDlSym, /* xDlSym */ \
6369 unixDlClose, /* xDlClose */ \
6370 unixRandomness, /* xRandomness */ \
6371 unixSleep, /* xSleep */ \
6372 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006373 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006374 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006375 }
6376
drh6b9d6dd2008-12-03 19:34:47 +00006377 /*
6378 ** All default VFSes for unix are contained in the following array.
6379 **
6380 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6381 ** by the SQLite core when the VFS is registered. So the following
6382 ** array cannot be const.
6383 */
danielk1977e339d652008-06-28 11:23:00 +00006384 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006385#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006386 UNIXVFS("unix", autolockIoFinder ),
6387#else
6388 UNIXVFS("unix", posixIoFinder ),
6389#endif
6390 UNIXVFS("unix-none", nolockIoFinder ),
6391 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006392#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006393 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006394#endif
6395#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006396 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006397#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006398 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006399#endif
chw78a13182009-04-07 05:35:03 +00006400#endif
drhd2cb50b2009-01-09 21:41:17 +00006401#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006402 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006403 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006404 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006405#endif
drh153c62c2007-08-24 03:51:33 +00006406 };
drh6b9d6dd2008-12-03 19:34:47 +00006407 unsigned int i; /* Loop counter */
6408
6409 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006410 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006411 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006412 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006413 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006414}
danielk1977e339d652008-06-28 11:23:00 +00006415
6416/*
drh6b9d6dd2008-12-03 19:34:47 +00006417** Shutdown the operating system interface.
6418**
6419** Some operating systems might need to do some cleanup in this routine,
6420** to release dynamically allocated objects. But not on unix.
6421** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006422*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006423int sqlite3_os_end(void){
6424 return SQLITE_OK;
6425}
drhdce8bdb2007-08-16 13:01:44 +00006426
danielk197729bafea2008-06-26 10:41:19 +00006427#endif /* SQLITE_OS_UNIX */