blob: 9966ed6097bfd8c46cf6426244f97b5ec64b5c3c [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhf2424c52010-04-26 00:04:55 +0000122#include <sys/mman.h>
danielk1977e339d652008-06-28 11:23:00 +0000123
drh40bbb0a2008-09-23 10:23:26 +0000124#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000125# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000126# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <semaphore.h>
128# include <limits.h>
129# else
drh9b35ea62008-11-29 02:20:26 +0000130# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000131# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
drhf8b4d8c2010-03-05 13:53:22 +0000135#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000136# include <sys/mount.h>
137#endif
138
drh9cbe6352005-11-29 03:13:21 +0000139/*
drh7ed97b92010-01-20 13:07:21 +0000140** Allowed values of unixFile.fsFlags
141*/
142#define SQLITE_FSFLAGS_IS_MSDOS 0x1
143
144/*
drhf1a221e2006-01-15 17:27:17 +0000145** If we are to be thread-safe, include the pthreads header and define
146** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000147*/
drhd677b3d2007-08-20 22:48:41 +0000148#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000149# include <pthread.h>
150# define SQLITE_UNIX_THREADS 1
151#endif
152
153/*
154** Default permissions when creating a new file
155*/
156#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
157# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
158#endif
159
danielk1977b4b47412007-08-17 15:53:36 +0000160/*
aswiftaebf4132008-11-21 00:10:35 +0000161 ** Default permissions when creating auto proxy dir
162 */
163#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
164# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
165#endif
166
167/*
danielk1977b4b47412007-08-17 15:53:36 +0000168** Maximum supported path-length.
169*/
170#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000171
drh734c9862008-11-28 15:37:20 +0000172/*
drh734c9862008-11-28 15:37:20 +0000173** Only set the lastErrno if the error code is a real error and not
174** a normal expected return code of SQLITE_BUSY or SQLITE_OK
175*/
176#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
177
drhd91c68f2010-05-14 14:52:25 +0000178/* Forward references */
179typedef struct unixShm unixShm; /* Connection shared memory */
180typedef struct unixShmNode unixShmNode; /* Shared memory instance */
181typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
182typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000183
184/*
dane946c392009-08-22 11:39:46 +0000185** Sometimes, after a file handle is closed by SQLite, the file descriptor
186** cannot be closed immediately. In these cases, instances of the following
187** structure are used to store the file descriptor while waiting for an
188** opportunity to either close or reuse it.
189*/
dane946c392009-08-22 11:39:46 +0000190struct UnixUnusedFd {
191 int fd; /* File descriptor to close */
192 int flags; /* Flags this file descriptor was opened with */
193 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
194};
195
196/*
drh9b35ea62008-11-29 02:20:26 +0000197** The unixFile structure is subclass of sqlite3_file specific to the unix
198** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000199*/
drh054889e2005-11-30 03:20:31 +0000200typedef struct unixFile unixFile;
201struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000202 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000203 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000204 int h; /* The file descriptor */
205 int dirfd; /* File descriptor for the directory */
206 unsigned char eFileLock; /* The type of lock held on this fd */
207 int lastErrno; /* The unix errno from last I/O error */
208 void *lockingContext; /* Locking style specific state */
209 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
210 int fileFlags; /* Miscellanous flags */
211 const char *zPath; /* Name of the file */
212 unixShm *pShm; /* Shared memory segment information */
drh08c6d442009-02-09 17:34:07 +0000213#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000214 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000215#endif
drh7ed97b92010-01-20 13:07:21 +0000216#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000217 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000218#endif
219#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000220 int isDelete; /* Delete on close if true */
221 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000222#endif
drh8f941bc2009-01-14 23:03:40 +0000223#ifndef NDEBUG
224 /* The next group of variables are used to track whether or not the
225 ** transaction counter in bytes 24-27 of database files are updated
226 ** whenever any part of the database changes. An assertion fault will
227 ** occur if a file is updated without also updating the transaction
228 ** counter. This test is made to avoid new problems similar to the
229 ** one described by ticket #3584.
230 */
231 unsigned char transCntrChng; /* True if the transaction counter changed */
232 unsigned char dbUpdate; /* True if any part of database file changed */
233 unsigned char inNormalWrite; /* True if in a normal write operation */
234#endif
danielk1977967a4a12007-08-20 14:23:44 +0000235#ifdef SQLITE_TEST
236 /* In test mode, increase the size of this structure a bit so that
237 ** it is larger than the struct CrashFile defined in test6.c.
238 */
239 char aPadding[32];
240#endif
drh9cbe6352005-11-29 03:13:21 +0000241};
242
drh0ccebe72005-06-07 22:22:50 +0000243/*
drh0c2694b2009-09-03 16:23:44 +0000244** The following macros define bits in unixFile.fileFlags
245*/
246#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
247
248/*
drh198bf392006-01-06 21:52:49 +0000249** Include code that is common to all os_*.c files
250*/
251#include "os_common.h"
252
253/*
drh0ccebe72005-06-07 22:22:50 +0000254** Define various macros that are missing from some systems.
255*/
drhbbd42a62004-05-22 17:41:58 +0000256#ifndef O_LARGEFILE
257# define O_LARGEFILE 0
258#endif
259#ifdef SQLITE_DISABLE_LFS
260# undef O_LARGEFILE
261# define O_LARGEFILE 0
262#endif
263#ifndef O_NOFOLLOW
264# define O_NOFOLLOW 0
265#endif
266#ifndef O_BINARY
267# define O_BINARY 0
268#endif
269
270/*
271** The DJGPP compiler environment looks mostly like Unix, but it
272** lacks the fcntl() system call. So redefine fcntl() to be something
273** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000274** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000275*/
276#ifdef __DJGPP__
277# define fcntl(A,B,C) 0
278#endif
279
280/*
drh2b4b5962005-06-15 17:47:55 +0000281** The threadid macro resolves to the thread-id or to 0. Used for
282** testing and debugging only.
283*/
drhd677b3d2007-08-20 22:48:41 +0000284#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000285#define threadid pthread_self()
286#else
287#define threadid 0
288#endif
289
danielk197713adf8a2004-06-03 16:08:41 +0000290
drh107886a2008-11-21 22:21:50 +0000291/*
dan9359c7b2009-08-21 08:29:10 +0000292** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000293** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000294** vxworksFileId objects used by this file, all of which may be
295** shared by multiple threads.
296**
297** Function unixMutexHeld() is used to assert() that the global mutex
298** is held when required. This function is only used as part of assert()
299** statements. e.g.
300**
301** unixEnterMutex()
302** assert( unixMutexHeld() );
303** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000304*/
305static void unixEnterMutex(void){
306 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
307}
308static void unixLeaveMutex(void){
309 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
310}
dan9359c7b2009-08-21 08:29:10 +0000311#ifdef SQLITE_DEBUG
312static int unixMutexHeld(void) {
313 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
314}
315#endif
drh107886a2008-11-21 22:21:50 +0000316
drh734c9862008-11-28 15:37:20 +0000317
318#ifdef SQLITE_DEBUG
319/*
320** Helper function for printing out trace information from debugging
321** binaries. This returns the string represetation of the supplied
322** integer lock-type.
323*/
drh308c2a52010-05-14 11:30:18 +0000324static const char *azFileLock(int eFileLock){
325 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000326 case NO_LOCK: return "NONE";
327 case SHARED_LOCK: return "SHARED";
328 case RESERVED_LOCK: return "RESERVED";
329 case PENDING_LOCK: return "PENDING";
330 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000331 }
332 return "ERROR";
333}
334#endif
335
336#ifdef SQLITE_LOCK_TRACE
337/*
338** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000339**
drh734c9862008-11-28 15:37:20 +0000340** This routine is used for troubleshooting locks on multithreaded
341** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
342** command-line option on the compiler. This code is normally
343** turned off.
344*/
345static int lockTrace(int fd, int op, struct flock *p){
346 char *zOpName, *zType;
347 int s;
348 int savedErrno;
349 if( op==F_GETLK ){
350 zOpName = "GETLK";
351 }else if( op==F_SETLK ){
352 zOpName = "SETLK";
353 }else{
354 s = fcntl(fd, op, p);
355 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
356 return s;
357 }
358 if( p->l_type==F_RDLCK ){
359 zType = "RDLCK";
360 }else if( p->l_type==F_WRLCK ){
361 zType = "WRLCK";
362 }else if( p->l_type==F_UNLCK ){
363 zType = "UNLCK";
364 }else{
365 assert( 0 );
366 }
367 assert( p->l_whence==SEEK_SET );
368 s = fcntl(fd, op, p);
369 savedErrno = errno;
370 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
371 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
372 (int)p->l_pid, s);
373 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
374 struct flock l2;
375 l2 = *p;
376 fcntl(fd, F_GETLK, &l2);
377 if( l2.l_type==F_RDLCK ){
378 zType = "RDLCK";
379 }else if( l2.l_type==F_WRLCK ){
380 zType = "WRLCK";
381 }else if( l2.l_type==F_UNLCK ){
382 zType = "UNLCK";
383 }else{
384 assert( 0 );
385 }
386 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
387 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
388 }
389 errno = savedErrno;
390 return s;
391}
392#define fcntl lockTrace
393#endif /* SQLITE_LOCK_TRACE */
394
395
396
397/*
398** This routine translates a standard POSIX errno code into something
399** useful to the clients of the sqlite3 functions. Specifically, it is
400** intended to translate a variety of "try again" errors into SQLITE_BUSY
401** and a variety of "please close the file descriptor NOW" errors into
402** SQLITE_IOERR
403**
404** Errors during initialization of locks, or file system support for locks,
405** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
406*/
407static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
408 switch (posixError) {
409 case 0:
410 return SQLITE_OK;
411
412 case EAGAIN:
413 case ETIMEDOUT:
414 case EBUSY:
415 case EINTR:
416 case ENOLCK:
417 /* random NFS retry error, unless during file system support
418 * introspection, in which it actually means what it says */
419 return SQLITE_BUSY;
420
421 case EACCES:
422 /* EACCES is like EAGAIN during locking operations, but not any other time*/
423 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
424 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
425 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
426 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
427 return SQLITE_BUSY;
428 }
429 /* else fall through */
430 case EPERM:
431 return SQLITE_PERM;
432
433 case EDEADLK:
434 return SQLITE_IOERR_BLOCKED;
435
436#if EOPNOTSUPP!=ENOTSUP
437 case EOPNOTSUPP:
438 /* something went terribly awry, unless during file system support
439 * introspection, in which it actually means what it says */
440#endif
441#ifdef ENOTSUP
442 case ENOTSUP:
443 /* invalid fd, unless during file system support introspection, in which
444 * it actually means what it says */
445#endif
446 case EIO:
447 case EBADF:
448 case EINVAL:
449 case ENOTCONN:
450 case ENODEV:
451 case ENXIO:
452 case ENOENT:
453 case ESTALE:
454 case ENOSYS:
455 /* these should force the client to close the file and reconnect */
456
457 default:
458 return sqliteIOErr;
459 }
460}
461
462
463
464/******************************************************************************
465****************** Begin Unique File ID Utility Used By VxWorks ***************
466**
467** On most versions of unix, we can get a unique ID for a file by concatenating
468** the device number and the inode number. But this does not work on VxWorks.
469** On VxWorks, a unique file id must be based on the canonical filename.
470**
471** A pointer to an instance of the following structure can be used as a
472** unique file ID in VxWorks. Each instance of this structure contains
473** a copy of the canonical filename. There is also a reference count.
474** The structure is reclaimed when the number of pointers to it drops to
475** zero.
476**
477** There are never very many files open at one time and lookups are not
478** a performance-critical path, so it is sufficient to put these
479** structures on a linked list.
480*/
481struct vxworksFileId {
482 struct vxworksFileId *pNext; /* Next in a list of them all */
483 int nRef; /* Number of references to this one */
484 int nName; /* Length of the zCanonicalName[] string */
485 char *zCanonicalName; /* Canonical filename */
486};
487
488#if OS_VXWORKS
489/*
drh9b35ea62008-11-29 02:20:26 +0000490** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000491** variable:
492*/
493static struct vxworksFileId *vxworksFileList = 0;
494
495/*
496** Simplify a filename into its canonical form
497** by making the following changes:
498**
499** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000500** * convert /./ into just /
501** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000502**
503** Changes are made in-place. Return the new name length.
504**
505** The original filename is in z[0..n-1]. Return the number of
506** characters in the simplified name.
507*/
508static int vxworksSimplifyName(char *z, int n){
509 int i, j;
510 while( n>1 && z[n-1]=='/' ){ n--; }
511 for(i=j=0; i<n; i++){
512 if( z[i]=='/' ){
513 if( z[i+1]=='/' ) continue;
514 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
515 i += 1;
516 continue;
517 }
518 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
519 while( j>0 && z[j-1]!='/' ){ j--; }
520 if( j>0 ){ j--; }
521 i += 2;
522 continue;
523 }
524 }
525 z[j++] = z[i];
526 }
527 z[j] = 0;
528 return j;
529}
530
531/*
532** Find a unique file ID for the given absolute pathname. Return
533** a pointer to the vxworksFileId object. This pointer is the unique
534** file ID.
535**
536** The nRef field of the vxworksFileId object is incremented before
537** the object is returned. A new vxworksFileId object is created
538** and added to the global list if necessary.
539**
540** If a memory allocation error occurs, return NULL.
541*/
542static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
543 struct vxworksFileId *pNew; /* search key and new file ID */
544 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
545 int n; /* Length of zAbsoluteName string */
546
547 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000548 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000549 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
550 if( pNew==0 ) return 0;
551 pNew->zCanonicalName = (char*)&pNew[1];
552 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
553 n = vxworksSimplifyName(pNew->zCanonicalName, n);
554
555 /* Search for an existing entry that matching the canonical name.
556 ** If found, increment the reference count and return a pointer to
557 ** the existing file ID.
558 */
559 unixEnterMutex();
560 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
561 if( pCandidate->nName==n
562 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
563 ){
564 sqlite3_free(pNew);
565 pCandidate->nRef++;
566 unixLeaveMutex();
567 return pCandidate;
568 }
569 }
570
571 /* No match was found. We will make a new file ID */
572 pNew->nRef = 1;
573 pNew->nName = n;
574 pNew->pNext = vxworksFileList;
575 vxworksFileList = pNew;
576 unixLeaveMutex();
577 return pNew;
578}
579
580/*
581** Decrement the reference count on a vxworksFileId object. Free
582** the object when the reference count reaches zero.
583*/
584static void vxworksReleaseFileId(struct vxworksFileId *pId){
585 unixEnterMutex();
586 assert( pId->nRef>0 );
587 pId->nRef--;
588 if( pId->nRef==0 ){
589 struct vxworksFileId **pp;
590 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
591 assert( *pp==pId );
592 *pp = pId->pNext;
593 sqlite3_free(pId);
594 }
595 unixLeaveMutex();
596}
597#endif /* OS_VXWORKS */
598/*************** End of Unique File ID Utility Used By VxWorks ****************
599******************************************************************************/
600
601
602/******************************************************************************
603*************************** Posix Advisory Locking ****************************
604**
drh9b35ea62008-11-29 02:20:26 +0000605** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000606** section 6.5.2.2 lines 483 through 490 specify that when a process
607** sets or clears a lock, that operation overrides any prior locks set
608** by the same process. It does not explicitly say so, but this implies
609** that it overrides locks set by the same process using a different
610** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000611**
612** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000613** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
614**
615** Suppose ./file1 and ./file2 are really the same file (because
616** one is a hard or symbolic link to the other) then if you set
617** an exclusive lock on fd1, then try to get an exclusive lock
618** on fd2, it works. I would have expected the second lock to
619** fail since there was already a lock on the file due to fd1.
620** But not so. Since both locks came from the same process, the
621** second overrides the first, even though they were on different
622** file descriptors opened on different file names.
623**
drh734c9862008-11-28 15:37:20 +0000624** This means that we cannot use POSIX locks to synchronize file access
625** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000626** to synchronize access for threads in separate processes, but not
627** threads within the same process.
628**
629** To work around the problem, SQLite has to manage file locks internally
630** on its own. Whenever a new database is opened, we have to find the
631** specific inode of the database file (the inode is determined by the
632** st_dev and st_ino fields of the stat structure that fstat() fills in)
633** and check for locks already existing on that inode. When locks are
634** created or removed, we have to look at our own internal record of the
635** locks to see if another thread has previously set a lock on that same
636** inode.
637**
drh9b35ea62008-11-29 02:20:26 +0000638** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
639** For VxWorks, we have to use the alternative unique ID system based on
640** canonical filename and implemented in the previous division.)
641**
danielk1977ad94b582007-08-20 06:44:22 +0000642** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000643** descriptor. It is now a structure that holds the integer file
644** descriptor and a pointer to a structure that describes the internal
645** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000646** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000647** point to the same locking structure. The locking structure keeps
648** a reference count (so we will know when to delete it) and a "cnt"
649** field that tells us its internal lock status. cnt==0 means the
650** file is unlocked. cnt==-1 means the file has an exclusive lock.
651** cnt>0 means there are cnt shared locks on the file.
652**
653** Any attempt to lock or unlock a file first checks the locking
654** structure. The fcntl() system call is only invoked to set a
655** POSIX lock if the internal lock structure transitions between
656** a locked and an unlocked state.
657**
drh734c9862008-11-28 15:37:20 +0000658** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000659**
660** If you close a file descriptor that points to a file that has locks,
661** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000662** released. To work around this problem, each unixInodeInfo object
663** maintains a count of the number of pending locks on tha inode.
664** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000665** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000666** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000667** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000668** be closed and that list is walked (and cleared) when the last lock
669** clears.
670**
drh9b35ea62008-11-29 02:20:26 +0000671** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000672**
drh9b35ea62008-11-29 02:20:26 +0000673** Many older versions of linux use the LinuxThreads library which is
674** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000675** A cannot be modified or overridden by a different thread B.
676** Only thread A can modify the lock. Locking behavior is correct
677** if the appliation uses the newer Native Posix Thread Library (NPTL)
678** on linux - with NPTL a lock created by thread A can override locks
679** in thread B. But there is no way to know at compile-time which
680** threading library is being used. So there is no way to know at
681** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000682** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000683** current process.
drh5fdae772004-06-29 03:29:00 +0000684**
drh8af6c222010-05-14 12:43:01 +0000685** SQLite used to support LinuxThreads. But support for LinuxThreads
686** was dropped beginning with version 3.7.0. SQLite will still work with
687** LinuxThreads provided that (1) there is no more than one connection
688** per database file in the same process and (2) database connections
689** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000690*/
691
692/*
693** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000694** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000695*/
696struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000697 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000698#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000699 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000700#else
drh107886a2008-11-21 22:21:50 +0000701 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000702#endif
703};
704
705/*
drhbbd42a62004-05-22 17:41:58 +0000706** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000707** inode. Or, on LinuxThreads, there is one of these structures for
708** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000709**
danielk1977ad94b582007-08-20 06:44:22 +0000710** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000711** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000712** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000713*/
drh8af6c222010-05-14 12:43:01 +0000714struct unixInodeInfo {
715 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000716 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000717 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000718 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000719 unixShmNode *pShmNode; /* Shared memory associated with this inode */
720 int nLock; /* Number of outstanding file locks */
721 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
722 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
723 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000724#if defined(SQLITE_ENABLE_LOCKING_STYLE)
725 unsigned long long sharedByte; /* for AFP simulated shared lock */
726#endif
drh6c7d5c52008-11-21 20:32:33 +0000727#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000728 sem_t *pSem; /* Named POSIX semaphore */
729 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000730#endif
drhbbd42a62004-05-22 17:41:58 +0000731};
732
drhda0e7682008-07-30 15:27:54 +0000733/*
drh8af6c222010-05-14 12:43:01 +0000734** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000735*/
drhd91c68f2010-05-14 14:52:25 +0000736static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000737
drh5fdae772004-06-29 03:29:00 +0000738/*
danb0ac3e32010-06-16 10:55:42 +0000739** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
740** If all such file descriptors are closed without error, the list is
741** cleared and SQLITE_OK returned.
742**
743** Otherwise, if an error occurs, then successfully closed file descriptor
744** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
745** not deleted and SQLITE_IOERR_CLOSE returned.
746*/
747static int closePendingFds(unixFile *pFile){
748 int rc = SQLITE_OK;
749 unixInodeInfo *pInode = pFile->pInode;
750 UnixUnusedFd *pError = 0;
751 UnixUnusedFd *p;
752 UnixUnusedFd *pNext;
753 for(p=pInode->pUnused; p; p=pNext){
754 pNext = p->pNext;
755 if( close(p->fd) ){
756 pFile->lastErrno = errno;
757 rc = SQLITE_IOERR_CLOSE;
758 p->pNext = pError;
759 pError = p;
760 }else{
761 sqlite3_free(p);
762 }
763 }
764 pInode->pUnused = pError;
765 return rc;
766}
767
768/*
drh8af6c222010-05-14 12:43:01 +0000769** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000770**
771** The mutex entered using the unixEnterMutex() function must be held
772** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000773*/
danb0ac3e32010-06-16 10:55:42 +0000774static void releaseInodeInfo(unixFile *pFile){
775 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000776 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000777 if( pInode ){
778 pInode->nRef--;
779 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000780 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000781 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000782 if( pInode->pPrev ){
783 assert( pInode->pPrev->pNext==pInode );
784 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000785 }else{
drh8af6c222010-05-14 12:43:01 +0000786 assert( inodeList==pInode );
787 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000788 }
drh8af6c222010-05-14 12:43:01 +0000789 if( pInode->pNext ){
790 assert( pInode->pNext->pPrev==pInode );
791 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000792 }
drh8af6c222010-05-14 12:43:01 +0000793 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000794 }
drhbbd42a62004-05-22 17:41:58 +0000795 }
796}
797
798/*
drh8af6c222010-05-14 12:43:01 +0000799** Given a file descriptor, locate the unixInodeInfo object that
800** describes that file descriptor. Create a new one if necessary. The
801** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000802**
dan9359c7b2009-08-21 08:29:10 +0000803** The mutex entered using the unixEnterMutex() function must be held
804** when this function is called.
805**
drh6c7d5c52008-11-21 20:32:33 +0000806** Return an appropriate error code.
807*/
drh8af6c222010-05-14 12:43:01 +0000808static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000809 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000810 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000811){
812 int rc; /* System call return code */
813 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000814 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
815 struct stat statbuf; /* Low-level file information */
816 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000817
dan9359c7b2009-08-21 08:29:10 +0000818 assert( unixMutexHeld() );
819
drh6c7d5c52008-11-21 20:32:33 +0000820 /* Get low-level information about the file that we can used to
821 ** create a unique name for the file.
822 */
823 fd = pFile->h;
824 rc = fstat(fd, &statbuf);
825 if( rc!=0 ){
826 pFile->lastErrno = errno;
827#ifdef EOVERFLOW
828 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
829#endif
830 return SQLITE_IOERR;
831 }
832
drheb0d74f2009-02-03 15:27:02 +0000833#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000834 /* On OS X on an msdos filesystem, the inode number is reported
835 ** incorrectly for zero-size files. See ticket #3260. To work
836 ** around this problem (we consider it a bug in OS X, not SQLite)
837 ** we always increase the file size to 1 by writing a single byte
838 ** prior to accessing the inode number. The one byte written is
839 ** an ASCII 'S' character which also happens to be the first byte
840 ** in the header of every SQLite database. In this way, if there
841 ** is a race condition such that another thread has already populated
842 ** the first page of the database, no damage is done.
843 */
drh7ed97b92010-01-20 13:07:21 +0000844 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +0000845 rc = write(fd, "S", 1);
846 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000847 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000848 return SQLITE_IOERR;
849 }
drh6c7d5c52008-11-21 20:32:33 +0000850 rc = fstat(fd, &statbuf);
851 if( rc!=0 ){
852 pFile->lastErrno = errno;
853 return SQLITE_IOERR;
854 }
855 }
drheb0d74f2009-02-03 15:27:02 +0000856#endif
drh6c7d5c52008-11-21 20:32:33 +0000857
drh8af6c222010-05-14 12:43:01 +0000858 memset(&fileId, 0, sizeof(fileId));
859 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000860#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000861 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000862#else
drh8af6c222010-05-14 12:43:01 +0000863 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000864#endif
drh8af6c222010-05-14 12:43:01 +0000865 pInode = inodeList;
866 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
867 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000868 }
drh8af6c222010-05-14 12:43:01 +0000869 if( pInode==0 ){
870 pInode = sqlite3_malloc( sizeof(*pInode) );
871 if( pInode==0 ){
872 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000873 }
drh8af6c222010-05-14 12:43:01 +0000874 memset(pInode, 0, sizeof(*pInode));
875 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
876 pInode->nRef = 1;
877 pInode->pNext = inodeList;
878 pInode->pPrev = 0;
879 if( inodeList ) inodeList->pPrev = pInode;
880 inodeList = pInode;
881 }else{
882 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000883 }
drh8af6c222010-05-14 12:43:01 +0000884 *ppInode = pInode;
885 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000886}
drh6c7d5c52008-11-21 20:32:33 +0000887
aswift5b1a2562008-08-22 00:22:35 +0000888
889/*
danielk197713adf8a2004-06-03 16:08:41 +0000890** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000891** file by this or any other process. If such a lock is held, set *pResOut
892** to a non-zero value otherwise *pResOut is set to zero. The return value
893** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000894*/
danielk1977861f7452008-06-05 11:39:11 +0000895static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000896 int rc = SQLITE_OK;
897 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000898 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000899
danielk1977861f7452008-06-05 11:39:11 +0000900 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
901
drh054889e2005-11-30 03:20:31 +0000902 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000903 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000904
905 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000906 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000907 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000908 }
909
drh2ac3ee92004-06-07 16:27:46 +0000910 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000911 */
danielk197709480a92009-02-09 05:32:32 +0000912#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000913 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000914 struct flock lock;
915 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000916 lock.l_start = RESERVED_BYTE;
917 lock.l_len = 1;
918 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +0000919 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
920 int tErrno = errno;
921 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
922 pFile->lastErrno = tErrno;
923 } else if( lock.l_type!=F_UNLCK ){
924 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000925 }
926 }
danielk197709480a92009-02-09 05:32:32 +0000927#endif
danielk197713adf8a2004-06-03 16:08:41 +0000928
drh6c7d5c52008-11-21 20:32:33 +0000929 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +0000930 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +0000931
aswift5b1a2562008-08-22 00:22:35 +0000932 *pResOut = reserved;
933 return rc;
danielk197713adf8a2004-06-03 16:08:41 +0000934}
935
936/*
drh308c2a52010-05-14 11:30:18 +0000937** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +0000938** of the following:
939**
drh2ac3ee92004-06-07 16:27:46 +0000940** (1) SHARED_LOCK
941** (2) RESERVED_LOCK
942** (3) PENDING_LOCK
943** (4) EXCLUSIVE_LOCK
944**
drhb3e04342004-06-08 00:47:47 +0000945** Sometimes when requesting one lock state, additional lock states
946** are inserted in between. The locking might fail on one of the later
947** transitions leaving the lock state different from what it started but
948** still short of its goal. The following chart shows the allowed
949** transitions and the inserted intermediate states:
950**
951** UNLOCKED -> SHARED
952** SHARED -> RESERVED
953** SHARED -> (PENDING) -> EXCLUSIVE
954** RESERVED -> (PENDING) -> EXCLUSIVE
955** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000956**
drha6abd042004-06-09 17:37:22 +0000957** This routine will only increase a lock. Use the sqlite3OsUnlock()
958** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000959*/
drh308c2a52010-05-14 11:30:18 +0000960static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +0000961 /* The following describes the implementation of the various locks and
962 ** lock transitions in terms of the POSIX advisory shared and exclusive
963 ** lock primitives (called read-locks and write-locks below, to avoid
964 ** confusion with SQLite lock names). The algorithms are complicated
965 ** slightly in order to be compatible with windows systems simultaneously
966 ** accessing the same database file, in case that is ever required.
967 **
968 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
969 ** byte', each single bytes at well known offsets, and the 'shared byte
970 ** range', a range of 510 bytes at a well known offset.
971 **
972 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
973 ** byte'. If this is successful, a random byte from the 'shared byte
974 ** range' is read-locked and the lock on the 'pending byte' released.
975 **
danielk197790ba3bd2004-06-25 08:32:25 +0000976 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
977 ** A RESERVED lock is implemented by grabbing a write-lock on the
978 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000979 **
980 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000981 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
982 ** on the 'pending byte'. This ensures that no new SHARED locks can be
983 ** obtained, but existing SHARED locks are allowed to persist. A process
984 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
985 ** This property is used by the algorithm for rolling back a journal file
986 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000987 **
danielk197790ba3bd2004-06-25 08:32:25 +0000988 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
989 ** implemented by obtaining a write-lock on the entire 'shared byte
990 ** range'. Since all other locks require a read-lock on one of the bytes
991 ** within this range, this ensures that no other locks are held on the
992 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000993 **
994 ** The reason a single byte cannot be used instead of the 'shared byte
995 ** range' is that some versions of windows do not support read-locks. By
996 ** locking a random byte from a range, concurrent SHARED locks may exist
997 ** even if the locking primitive used is always a write-lock.
998 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000999 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001000 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001001 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001002 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001003 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001004 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001005
drh054889e2005-11-30 03:20:31 +00001006 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001007 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1008 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001009 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001010
1011 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001012 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001013 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001014 */
drh308c2a52010-05-14 11:30:18 +00001015 if( pFile->eFileLock>=eFileLock ){
1016 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1017 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001018 return SQLITE_OK;
1019 }
1020
drh0c2694b2009-09-03 16:23:44 +00001021 /* Make sure the locking sequence is correct.
1022 ** (1) We never move from unlocked to anything higher than shared lock.
1023 ** (2) SQLite never explicitly requests a pendig lock.
1024 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001025 */
drh308c2a52010-05-14 11:30:18 +00001026 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1027 assert( eFileLock!=PENDING_LOCK );
1028 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001029
drh8af6c222010-05-14 12:43:01 +00001030 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001031 */
drh6c7d5c52008-11-21 20:32:33 +00001032 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001033 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001034
danielk1977ad94b582007-08-20 06:44:22 +00001035 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001036 ** handle that precludes the requested lock, return BUSY.
1037 */
drh8af6c222010-05-14 12:43:01 +00001038 if( (pFile->eFileLock!=pInode->eFileLock &&
1039 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001040 ){
1041 rc = SQLITE_BUSY;
1042 goto end_lock;
1043 }
1044
1045 /* If a SHARED lock is requested, and some thread using this PID already
1046 ** has a SHARED or RESERVED lock, then increment reference counts and
1047 ** return SQLITE_OK.
1048 */
drh308c2a52010-05-14 11:30:18 +00001049 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001050 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001051 assert( eFileLock==SHARED_LOCK );
1052 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001053 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001054 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001055 pInode->nShared++;
1056 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001057 goto end_lock;
1058 }
1059
danielk19779a1d0ab2004-06-01 14:09:28 +00001060
drh3cde3bb2004-06-12 02:17:14 +00001061 /* A PENDING lock is needed before acquiring a SHARED lock and before
1062 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1063 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001064 */
drh0c2694b2009-09-03 16:23:44 +00001065 lock.l_len = 1L;
1066 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001067 if( eFileLock==SHARED_LOCK
1068 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001069 ){
drh308c2a52010-05-14 11:30:18 +00001070 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001071 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001072 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001073 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001074 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001075 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1076 if( IS_LOCK_ERROR(rc) ){
1077 pFile->lastErrno = tErrno;
1078 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001079 goto end_lock;
1080 }
drh3cde3bb2004-06-12 02:17:14 +00001081 }
1082
1083
1084 /* If control gets to this point, then actually go ahead and make
1085 ** operating system calls for the specified lock.
1086 */
drh308c2a52010-05-14 11:30:18 +00001087 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001088 assert( pInode->nShared==0 );
1089 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001090
drh2ac3ee92004-06-07 16:27:46 +00001091 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001092 lock.l_start = SHARED_FIRST;
1093 lock.l_len = SHARED_SIZE;
1094 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1095 tErrno = errno;
1096 }
drh2ac3ee92004-06-07 16:27:46 +00001097 /* Drop the temporary PENDING lock */
1098 lock.l_start = PENDING_BYTE;
1099 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001100 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001101 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001102 if( s != -1 ){
1103 /* This could happen with a network mount */
1104 tErrno = errno;
1105 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1106 if( IS_LOCK_ERROR(rc) ){
1107 pFile->lastErrno = tErrno;
1108 }
1109 goto end_lock;
1110 }
drh2b4b5962005-06-15 17:47:55 +00001111 }
drhe2396a12007-03-29 20:19:58 +00001112 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001113 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1114 if( IS_LOCK_ERROR(rc) ){
1115 pFile->lastErrno = tErrno;
1116 }
drhbbd42a62004-05-22 17:41:58 +00001117 }else{
drh308c2a52010-05-14 11:30:18 +00001118 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001119 pInode->nLock++;
1120 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001121 }
drh8af6c222010-05-14 12:43:01 +00001122 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001123 /* We are trying for an exclusive lock but another thread in this
1124 ** same process is still holding a shared lock. */
1125 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001126 }else{
drh3cde3bb2004-06-12 02:17:14 +00001127 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001128 ** assumed that there is a SHARED or greater lock on the file
1129 ** already.
1130 */
drh308c2a52010-05-14 11:30:18 +00001131 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001132 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001133 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001134 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001135 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001136 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001137 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001138 lock.l_start = SHARED_FIRST;
1139 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001140 break;
1141 default:
1142 assert(0);
1143 }
drh7ed97b92010-01-20 13:07:21 +00001144 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001145 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001146 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001147 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1148 if( IS_LOCK_ERROR(rc) ){
1149 pFile->lastErrno = tErrno;
1150 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001151 }
drhbbd42a62004-05-22 17:41:58 +00001152 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001153
drh8f941bc2009-01-14 23:03:40 +00001154
1155#ifndef NDEBUG
1156 /* Set up the transaction-counter change checking flags when
1157 ** transitioning from a SHARED to a RESERVED lock. The change
1158 ** from SHARED to RESERVED marks the beginning of a normal
1159 ** write operation (not a hot journal rollback).
1160 */
1161 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001162 && pFile->eFileLock<=SHARED_LOCK
1163 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001164 ){
1165 pFile->transCntrChng = 0;
1166 pFile->dbUpdate = 0;
1167 pFile->inNormalWrite = 1;
1168 }
1169#endif
1170
1171
danielk1977ecb2a962004-06-02 06:30:16 +00001172 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001173 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001174 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001175 }else if( eFileLock==EXCLUSIVE_LOCK ){
1176 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001177 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001178 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001179
1180end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001181 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001182 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1183 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001184 return rc;
1185}
1186
1187/*
dan08da86a2009-08-21 17:18:03 +00001188** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001189** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001190*/
1191static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001192 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001193 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001194 p->pNext = pInode->pUnused;
1195 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001196 pFile->h = -1;
1197 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001198}
1199
1200/*
drh308c2a52010-05-14 11:30:18 +00001201** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001202** must be either NO_LOCK or SHARED_LOCK.
1203**
1204** If the locking level of the file descriptor is already at or below
1205** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001206**
1207** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1208** the byte range is divided into 2 parts and the first part is unlocked then
1209** set to a read lock, then the other part is simply unlocked. This works
1210** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1211** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001212*/
drh308c2a52010-05-14 11:30:18 +00001213static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001214 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001215 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001216 struct flock lock;
1217 int rc = SQLITE_OK;
1218 int h;
drh0c2694b2009-09-03 16:23:44 +00001219 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001220
drh054889e2005-11-30 03:20:31 +00001221 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001222 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001223 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001224 getpid()));
drha6abd042004-06-09 17:37:22 +00001225
drh308c2a52010-05-14 11:30:18 +00001226 assert( eFileLock<=SHARED_LOCK );
1227 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001228 return SQLITE_OK;
1229 }
drh6c7d5c52008-11-21 20:32:33 +00001230 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001231 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001232 pInode = pFile->pInode;
1233 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001234 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001235 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001236 SimulateIOErrorBenign(1);
1237 SimulateIOError( h=(-1) )
1238 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001239
1240#ifndef NDEBUG
1241 /* When reducing a lock such that other processes can start
1242 ** reading the database file again, make sure that the
1243 ** transaction counter was updated if any part of the database
1244 ** file changed. If the transaction counter is not updated,
1245 ** other connections to the same file might not realize that
1246 ** the file has changed and hence might not know to flush their
1247 ** cache. The use of a stale cache can lead to database corruption.
1248 */
dan7c246102010-04-12 19:00:29 +00001249#if 0
drh8f941bc2009-01-14 23:03:40 +00001250 assert( pFile->inNormalWrite==0
1251 || pFile->dbUpdate==0
1252 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001253#endif
drh8f941bc2009-01-14 23:03:40 +00001254 pFile->inNormalWrite = 0;
1255#endif
1256
drh7ed97b92010-01-20 13:07:21 +00001257 /* downgrading to a shared lock on NFS involves clearing the write lock
1258 ** before establishing the readlock - to avoid a race condition we downgrade
1259 ** the lock in 2 blocks, so that part of the range will be covered by a
1260 ** write lock until the rest is covered by a read lock:
1261 ** 1: [WWWWW]
1262 ** 2: [....W]
1263 ** 3: [RRRRW]
1264 ** 4: [RRRR.]
1265 */
drh308c2a52010-05-14 11:30:18 +00001266 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001267 if( handleNFSUnlock ){
1268 off_t divSize = SHARED_SIZE - 1;
1269
1270 lock.l_type = F_UNLCK;
1271 lock.l_whence = SEEK_SET;
1272 lock.l_start = SHARED_FIRST;
1273 lock.l_len = divSize;
1274 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001275 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001276 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1277 if( IS_LOCK_ERROR(rc) ){
1278 pFile->lastErrno = tErrno;
1279 }
1280 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001281 }
drh7ed97b92010-01-20 13:07:21 +00001282 lock.l_type = F_RDLCK;
1283 lock.l_whence = SEEK_SET;
1284 lock.l_start = SHARED_FIRST;
1285 lock.l_len = divSize;
1286 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001287 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001288 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1289 if( IS_LOCK_ERROR(rc) ){
1290 pFile->lastErrno = tErrno;
1291 }
1292 goto end_unlock;
1293 }
1294 lock.l_type = F_UNLCK;
1295 lock.l_whence = SEEK_SET;
1296 lock.l_start = SHARED_FIRST+divSize;
1297 lock.l_len = SHARED_SIZE-divSize;
1298 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001299 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001300 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1301 if( IS_LOCK_ERROR(rc) ){
1302 pFile->lastErrno = tErrno;
1303 }
1304 goto end_unlock;
1305 }
1306 }else{
1307 lock.l_type = F_RDLCK;
1308 lock.l_whence = SEEK_SET;
1309 lock.l_start = SHARED_FIRST;
1310 lock.l_len = SHARED_SIZE;
1311 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001312 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001313 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1314 if( IS_LOCK_ERROR(rc) ){
1315 pFile->lastErrno = tErrno;
1316 }
1317 goto end_unlock;
1318 }
drh9c105bb2004-10-02 20:38:28 +00001319 }
1320 }
drhbbd42a62004-05-22 17:41:58 +00001321 lock.l_type = F_UNLCK;
1322 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001323 lock.l_start = PENDING_BYTE;
1324 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001325 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001326 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001327 }else{
drh0c2694b2009-09-03 16:23:44 +00001328 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001329 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1330 if( IS_LOCK_ERROR(rc) ){
1331 pFile->lastErrno = tErrno;
1332 }
drhcd731cf2009-03-28 23:23:02 +00001333 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001334 }
drhbbd42a62004-05-22 17:41:58 +00001335 }
drh308c2a52010-05-14 11:30:18 +00001336 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001337 /* Decrement the shared lock counter. Release the lock using an
1338 ** OS call only when all threads in this same process have released
1339 ** the lock.
1340 */
drh8af6c222010-05-14 12:43:01 +00001341 pInode->nShared--;
1342 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001343 lock.l_type = F_UNLCK;
1344 lock.l_whence = SEEK_SET;
1345 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001346 SimulateIOErrorBenign(1);
1347 SimulateIOError( h=(-1) )
1348 SimulateIOErrorBenign(0);
1349 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001350 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001351 }else{
drh0c2694b2009-09-03 16:23:44 +00001352 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001353 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001354 if( IS_LOCK_ERROR(rc) ){
1355 pFile->lastErrno = tErrno;
1356 }
drh8af6c222010-05-14 12:43:01 +00001357 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001358 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001359 }
drha6abd042004-06-09 17:37:22 +00001360 }
1361
drhbbd42a62004-05-22 17:41:58 +00001362 /* Decrement the count of locks against this same file. When the
1363 ** count reaches zero, close any other file descriptors whose close
1364 ** was deferred because of outstanding locks.
1365 */
drh8af6c222010-05-14 12:43:01 +00001366 pInode->nLock--;
1367 assert( pInode->nLock>=0 );
1368 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001369 int rc2 = closePendingFds(pFile);
1370 if( rc==SQLITE_OK ){
1371 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001372 }
drhbbd42a62004-05-22 17:41:58 +00001373 }
1374 }
aswift5b1a2562008-08-22 00:22:35 +00001375
1376end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001377 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001378 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001379 return rc;
drhbbd42a62004-05-22 17:41:58 +00001380}
1381
1382/*
drh308c2a52010-05-14 11:30:18 +00001383** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001384** must be either NO_LOCK or SHARED_LOCK.
1385**
1386** If the locking level of the file descriptor is already at or below
1387** the requested locking level, this routine is a no-op.
1388*/
drh308c2a52010-05-14 11:30:18 +00001389static int unixUnlock(sqlite3_file *id, int eFileLock){
1390 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001391}
1392
1393/*
danielk1977e339d652008-06-28 11:23:00 +00001394** This function performs the parts of the "close file" operation
1395** common to all locking schemes. It closes the directory and file
1396** handles, if they are valid, and sets all fields of the unixFile
1397** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001398**
1399** It is *not* necessary to hold the mutex when this routine is called,
1400** even on VxWorks. A mutex will be acquired on VxWorks by the
1401** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001402*/
1403static int closeUnixFile(sqlite3_file *id){
1404 unixFile *pFile = (unixFile*)id;
1405 if( pFile ){
1406 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001407 int err = close(pFile->dirfd);
1408 if( err ){
1409 pFile->lastErrno = errno;
1410 return SQLITE_IOERR_DIR_CLOSE;
1411 }else{
1412 pFile->dirfd=-1;
1413 }
danielk1977e339d652008-06-28 11:23:00 +00001414 }
1415 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001416 int err = close(pFile->h);
1417 if( err ){
1418 pFile->lastErrno = errno;
1419 return SQLITE_IOERR_CLOSE;
1420 }
danielk1977e339d652008-06-28 11:23:00 +00001421 }
drh6c7d5c52008-11-21 20:32:33 +00001422#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001423 if( pFile->pId ){
1424 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001425 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001426 }
drh107886a2008-11-21 22:21:50 +00001427 vxworksReleaseFileId(pFile->pId);
1428 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001429 }
1430#endif
drhff59a112010-05-14 20:15:51 +00001431 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001432 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001433 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001434 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001435 }
1436 return SQLITE_OK;
1437}
1438
1439/*
danielk1977e3026632004-06-22 11:29:02 +00001440** Close a file.
1441*/
danielk197762079062007-08-15 17:08:46 +00001442static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001443 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001444 if( id ){
1445 unixFile *pFile = (unixFile *)id;
1446 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001447 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001448 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001449 /* If there are outstanding locks, do not actually close the file just
1450 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001451 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001452 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001453 */
dan08da86a2009-08-21 17:18:03 +00001454 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001455 }
danb0ac3e32010-06-16 10:55:42 +00001456 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001457 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001458 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001459 }
aswiftaebf4132008-11-21 00:10:35 +00001460 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001461}
1462
drh734c9862008-11-28 15:37:20 +00001463/************** End of the posix advisory lock implementation *****************
1464******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001465
drh734c9862008-11-28 15:37:20 +00001466/******************************************************************************
1467****************************** No-op Locking **********************************
1468**
1469** Of the various locking implementations available, this is by far the
1470** simplest: locking is ignored. No attempt is made to lock the database
1471** file for reading or writing.
1472**
1473** This locking mode is appropriate for use on read-only databases
1474** (ex: databases that are burned into CD-ROM, for example.) It can
1475** also be used if the application employs some external mechanism to
1476** prevent simultaneous access of the same database by two or more
1477** database connections. But there is a serious risk of database
1478** corruption if this locking mode is used in situations where multiple
1479** database connections are accessing the same database file at the same
1480** time and one or more of those connections are writing.
1481*/
drhbfe66312006-10-03 17:40:40 +00001482
drh734c9862008-11-28 15:37:20 +00001483static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1484 UNUSED_PARAMETER(NotUsed);
1485 *pResOut = 0;
1486 return SQLITE_OK;
1487}
drh734c9862008-11-28 15:37:20 +00001488static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1489 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1490 return SQLITE_OK;
1491}
drh734c9862008-11-28 15:37:20 +00001492static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1493 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1494 return SQLITE_OK;
1495}
1496
1497/*
drh9b35ea62008-11-29 02:20:26 +00001498** Close the file.
drh734c9862008-11-28 15:37:20 +00001499*/
1500static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001501 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001502}
1503
1504/******************* End of the no-op lock implementation *********************
1505******************************************************************************/
1506
1507/******************************************************************************
1508************************* Begin dot-file Locking ******************************
1509**
drh0c2694b2009-09-03 16:23:44 +00001510** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001511** files in order to control access to the database. This works on just
1512** about every filesystem imaginable. But there are serious downsides:
1513**
1514** (1) There is zero concurrency. A single reader blocks all other
1515** connections from reading or writing the database.
1516**
1517** (2) An application crash or power loss can leave stale lock files
1518** sitting around that need to be cleared manually.
1519**
1520** Nevertheless, a dotlock is an appropriate locking mode for use if no
1521** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001522**
1523** Dotfile locking works by creating a file in the same directory as the
1524** database and with the same name but with a ".lock" extension added.
1525** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1526** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001527*/
1528
1529/*
1530** The file suffix added to the data base filename in order to create the
1531** lock file.
1532*/
1533#define DOTLOCK_SUFFIX ".lock"
1534
drh7708e972008-11-29 00:56:52 +00001535/*
1536** This routine checks if there is a RESERVED lock held on the specified
1537** file by this or any other process. If such a lock is held, set *pResOut
1538** to a non-zero value otherwise *pResOut is set to zero. The return value
1539** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1540**
1541** In dotfile locking, either a lock exists or it does not. So in this
1542** variation of CheckReservedLock(), *pResOut is set to true if any lock
1543** is held on the file and false if the file is unlocked.
1544*/
drh734c9862008-11-28 15:37:20 +00001545static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1546 int rc = SQLITE_OK;
1547 int reserved = 0;
1548 unixFile *pFile = (unixFile*)id;
1549
1550 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1551
1552 assert( pFile );
1553
1554 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001555 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001556 /* Either this connection or some other connection in the same process
1557 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001558 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001559 }else{
1560 /* The lock is held if and only if the lockfile exists */
1561 const char *zLockFile = (const char*)pFile->lockingContext;
1562 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001563 }
drh308c2a52010-05-14 11:30:18 +00001564 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001565 *pResOut = reserved;
1566 return rc;
1567}
1568
drh7708e972008-11-29 00:56:52 +00001569/*
drh308c2a52010-05-14 11:30:18 +00001570** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001571** of the following:
1572**
1573** (1) SHARED_LOCK
1574** (2) RESERVED_LOCK
1575** (3) PENDING_LOCK
1576** (4) EXCLUSIVE_LOCK
1577**
1578** Sometimes when requesting one lock state, additional lock states
1579** are inserted in between. The locking might fail on one of the later
1580** transitions leaving the lock state different from what it started but
1581** still short of its goal. The following chart shows the allowed
1582** transitions and the inserted intermediate states:
1583**
1584** UNLOCKED -> SHARED
1585** SHARED -> RESERVED
1586** SHARED -> (PENDING) -> EXCLUSIVE
1587** RESERVED -> (PENDING) -> EXCLUSIVE
1588** PENDING -> EXCLUSIVE
1589**
1590** This routine will only increase a lock. Use the sqlite3OsUnlock()
1591** routine to lower a locking level.
1592**
1593** With dotfile locking, we really only support state (4): EXCLUSIVE.
1594** But we track the other locking levels internally.
1595*/
drh308c2a52010-05-14 11:30:18 +00001596static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001597 unixFile *pFile = (unixFile*)id;
1598 int fd;
1599 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001600 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001601
drh7708e972008-11-29 00:56:52 +00001602
1603 /* If we have any lock, then the lock file already exists. All we have
1604 ** to do is adjust our internal record of the lock level.
1605 */
drh308c2a52010-05-14 11:30:18 +00001606 if( pFile->eFileLock > NO_LOCK ){
1607 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001608#if !OS_VXWORKS
1609 /* Always update the timestamp on the old file */
1610 utimes(zLockFile, NULL);
1611#endif
drh7708e972008-11-29 00:56:52 +00001612 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001613 }
1614
1615 /* grab an exclusive lock */
1616 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1617 if( fd<0 ){
1618 /* failed to open/create the file, someone else may have stolen the lock */
1619 int tErrno = errno;
1620 if( EEXIST == tErrno ){
1621 rc = SQLITE_BUSY;
1622 } else {
1623 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1624 if( IS_LOCK_ERROR(rc) ){
1625 pFile->lastErrno = tErrno;
1626 }
1627 }
drh7708e972008-11-29 00:56:52 +00001628 return rc;
drh734c9862008-11-28 15:37:20 +00001629 }
1630 if( close(fd) ){
1631 pFile->lastErrno = errno;
1632 rc = SQLITE_IOERR_CLOSE;
1633 }
1634
1635 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001636 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001637 return rc;
1638}
1639
drh7708e972008-11-29 00:56:52 +00001640/*
drh308c2a52010-05-14 11:30:18 +00001641** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001642** must be either NO_LOCK or SHARED_LOCK.
1643**
1644** If the locking level of the file descriptor is already at or below
1645** the requested locking level, this routine is a no-op.
1646**
1647** When the locking level reaches NO_LOCK, delete the lock file.
1648*/
drh308c2a52010-05-14 11:30:18 +00001649static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001650 unixFile *pFile = (unixFile*)id;
1651 char *zLockFile = (char *)pFile->lockingContext;
1652
1653 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001654 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1655 pFile->eFileLock, getpid()));
1656 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001657
1658 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001659 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001660 return SQLITE_OK;
1661 }
drh7708e972008-11-29 00:56:52 +00001662
1663 /* To downgrade to shared, simply update our internal notion of the
1664 ** lock state. No need to mess with the file on disk.
1665 */
drh308c2a52010-05-14 11:30:18 +00001666 if( eFileLock==SHARED_LOCK ){
1667 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001668 return SQLITE_OK;
1669 }
1670
drh7708e972008-11-29 00:56:52 +00001671 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001672 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001673 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001674 int rc = 0;
1675 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001676 if( ENOENT != tErrno ){
1677 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1678 }
1679 if( IS_LOCK_ERROR(rc) ){
1680 pFile->lastErrno = tErrno;
1681 }
1682 return rc;
1683 }
drh308c2a52010-05-14 11:30:18 +00001684 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001685 return SQLITE_OK;
1686}
1687
1688/*
drh9b35ea62008-11-29 02:20:26 +00001689** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001690*/
1691static int dotlockClose(sqlite3_file *id) {
1692 int rc;
1693 if( id ){
1694 unixFile *pFile = (unixFile*)id;
1695 dotlockUnlock(id, NO_LOCK);
1696 sqlite3_free(pFile->lockingContext);
1697 }
drh734c9862008-11-28 15:37:20 +00001698 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001699 return rc;
1700}
1701/****************** End of the dot-file lock implementation *******************
1702******************************************************************************/
1703
1704/******************************************************************************
1705************************** Begin flock Locking ********************************
1706**
1707** Use the flock() system call to do file locking.
1708**
drh6b9d6dd2008-12-03 19:34:47 +00001709** flock() locking is like dot-file locking in that the various
1710** fine-grain locking levels supported by SQLite are collapsed into
1711** a single exclusive lock. In other words, SHARED, RESERVED, and
1712** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1713** still works when you do this, but concurrency is reduced since
1714** only a single process can be reading the database at a time.
1715**
drh734c9862008-11-28 15:37:20 +00001716** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1717** compiling for VXWORKS.
1718*/
1719#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001720
drh6b9d6dd2008-12-03 19:34:47 +00001721/*
1722** This routine checks if there is a RESERVED lock held on the specified
1723** file by this or any other process. If such a lock is held, set *pResOut
1724** to a non-zero value otherwise *pResOut is set to zero. The return value
1725** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1726*/
drh734c9862008-11-28 15:37:20 +00001727static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1728 int rc = SQLITE_OK;
1729 int reserved = 0;
1730 unixFile *pFile = (unixFile*)id;
1731
1732 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1733
1734 assert( pFile );
1735
1736 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001737 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001738 reserved = 1;
1739 }
1740
1741 /* Otherwise see if some other process holds it. */
1742 if( !reserved ){
1743 /* attempt to get the lock */
1744 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1745 if( !lrc ){
1746 /* got the lock, unlock it */
1747 lrc = flock(pFile->h, LOCK_UN);
1748 if ( lrc ) {
1749 int tErrno = errno;
1750 /* unlock failed with an error */
1751 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1752 if( IS_LOCK_ERROR(lrc) ){
1753 pFile->lastErrno = tErrno;
1754 rc = lrc;
1755 }
1756 }
1757 } else {
1758 int tErrno = errno;
1759 reserved = 1;
1760 /* someone else might have it reserved */
1761 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1762 if( IS_LOCK_ERROR(lrc) ){
1763 pFile->lastErrno = tErrno;
1764 rc = lrc;
1765 }
1766 }
1767 }
drh308c2a52010-05-14 11:30:18 +00001768 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001769
1770#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1771 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1772 rc = SQLITE_OK;
1773 reserved=1;
1774 }
1775#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1776 *pResOut = reserved;
1777 return rc;
1778}
1779
drh6b9d6dd2008-12-03 19:34:47 +00001780/*
drh308c2a52010-05-14 11:30:18 +00001781** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001782** of the following:
1783**
1784** (1) SHARED_LOCK
1785** (2) RESERVED_LOCK
1786** (3) PENDING_LOCK
1787** (4) EXCLUSIVE_LOCK
1788**
1789** Sometimes when requesting one lock state, additional lock states
1790** are inserted in between. The locking might fail on one of the later
1791** transitions leaving the lock state different from what it started but
1792** still short of its goal. The following chart shows the allowed
1793** transitions and the inserted intermediate states:
1794**
1795** UNLOCKED -> SHARED
1796** SHARED -> RESERVED
1797** SHARED -> (PENDING) -> EXCLUSIVE
1798** RESERVED -> (PENDING) -> EXCLUSIVE
1799** PENDING -> EXCLUSIVE
1800**
1801** flock() only really support EXCLUSIVE locks. We track intermediate
1802** lock states in the sqlite3_file structure, but all locks SHARED or
1803** above are really EXCLUSIVE locks and exclude all other processes from
1804** access the file.
1805**
1806** This routine will only increase a lock. Use the sqlite3OsUnlock()
1807** routine to lower a locking level.
1808*/
drh308c2a52010-05-14 11:30:18 +00001809static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001810 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001811 unixFile *pFile = (unixFile*)id;
1812
1813 assert( pFile );
1814
1815 /* if we already have a lock, it is exclusive.
1816 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001817 if (pFile->eFileLock > NO_LOCK) {
1818 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001819 return SQLITE_OK;
1820 }
1821
1822 /* grab an exclusive lock */
1823
1824 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1825 int tErrno = errno;
1826 /* didn't get, must be busy */
1827 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1828 if( IS_LOCK_ERROR(rc) ){
1829 pFile->lastErrno = tErrno;
1830 }
1831 } else {
1832 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001833 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001834 }
drh308c2a52010-05-14 11:30:18 +00001835 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1836 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001837#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1838 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1839 rc = SQLITE_BUSY;
1840 }
1841#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1842 return rc;
1843}
1844
drh6b9d6dd2008-12-03 19:34:47 +00001845
1846/*
drh308c2a52010-05-14 11:30:18 +00001847** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001848** must be either NO_LOCK or SHARED_LOCK.
1849**
1850** If the locking level of the file descriptor is already at or below
1851** the requested locking level, this routine is a no-op.
1852*/
drh308c2a52010-05-14 11:30:18 +00001853static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001854 unixFile *pFile = (unixFile*)id;
1855
1856 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001857 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1858 pFile->eFileLock, getpid()));
1859 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001860
1861 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001862 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001863 return SQLITE_OK;
1864 }
1865
1866 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001867 if (eFileLock==SHARED_LOCK) {
1868 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001869 return SQLITE_OK;
1870 }
1871
1872 /* no, really, unlock. */
1873 int rc = flock(pFile->h, LOCK_UN);
1874 if (rc) {
1875 int r, tErrno = errno;
1876 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1877 if( IS_LOCK_ERROR(r) ){
1878 pFile->lastErrno = tErrno;
1879 }
1880#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1881 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1882 r = SQLITE_BUSY;
1883 }
1884#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1885
1886 return r;
1887 } else {
drh308c2a52010-05-14 11:30:18 +00001888 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001889 return SQLITE_OK;
1890 }
1891}
1892
1893/*
1894** Close a file.
1895*/
1896static int flockClose(sqlite3_file *id) {
1897 if( id ){
1898 flockUnlock(id, NO_LOCK);
1899 }
1900 return closeUnixFile(id);
1901}
1902
1903#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1904
1905/******************* End of the flock lock implementation *********************
1906******************************************************************************/
1907
1908/******************************************************************************
1909************************ Begin Named Semaphore Locking ************************
1910**
1911** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00001912**
1913** Semaphore locking is like dot-lock and flock in that it really only
1914** supports EXCLUSIVE locking. Only a single process can read or write
1915** the database file at a time. This reduces potential concurrency, but
1916** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00001917*/
1918#if OS_VXWORKS
1919
drh6b9d6dd2008-12-03 19:34:47 +00001920/*
1921** This routine checks if there is a RESERVED lock held on the specified
1922** file by this or any other process. If such a lock is held, set *pResOut
1923** to a non-zero value otherwise *pResOut is set to zero. The return value
1924** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1925*/
drh734c9862008-11-28 15:37:20 +00001926static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1927 int rc = SQLITE_OK;
1928 int reserved = 0;
1929 unixFile *pFile = (unixFile*)id;
1930
1931 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1932
1933 assert( pFile );
1934
1935 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001936 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001937 reserved = 1;
1938 }
1939
1940 /* Otherwise see if some other process holds it. */
1941 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00001942 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001943 struct stat statBuf;
1944
1945 if( sem_trywait(pSem)==-1 ){
1946 int tErrno = errno;
1947 if( EAGAIN != tErrno ){
1948 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1949 pFile->lastErrno = tErrno;
1950 } else {
1951 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00001952 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00001953 }
1954 }else{
1955 /* we could have it if we want it */
1956 sem_post(pSem);
1957 }
1958 }
drh308c2a52010-05-14 11:30:18 +00001959 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001960
1961 *pResOut = reserved;
1962 return rc;
1963}
1964
drh6b9d6dd2008-12-03 19:34:47 +00001965/*
drh308c2a52010-05-14 11:30:18 +00001966** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001967** of the following:
1968**
1969** (1) SHARED_LOCK
1970** (2) RESERVED_LOCK
1971** (3) PENDING_LOCK
1972** (4) EXCLUSIVE_LOCK
1973**
1974** Sometimes when requesting one lock state, additional lock states
1975** are inserted in between. The locking might fail on one of the later
1976** transitions leaving the lock state different from what it started but
1977** still short of its goal. The following chart shows the allowed
1978** transitions and the inserted intermediate states:
1979**
1980** UNLOCKED -> SHARED
1981** SHARED -> RESERVED
1982** SHARED -> (PENDING) -> EXCLUSIVE
1983** RESERVED -> (PENDING) -> EXCLUSIVE
1984** PENDING -> EXCLUSIVE
1985**
1986** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
1987** lock states in the sqlite3_file structure, but all locks SHARED or
1988** above are really EXCLUSIVE locks and exclude all other processes from
1989** access the file.
1990**
1991** This routine will only increase a lock. Use the sqlite3OsUnlock()
1992** routine to lower a locking level.
1993*/
drh308c2a52010-05-14 11:30:18 +00001994static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001995 unixFile *pFile = (unixFile*)id;
1996 int fd;
drh8af6c222010-05-14 12:43:01 +00001997 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001998 int rc = SQLITE_OK;
1999
2000 /* if we already have a lock, it is exclusive.
2001 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002002 if (pFile->eFileLock > NO_LOCK) {
2003 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002004 rc = SQLITE_OK;
2005 goto sem_end_lock;
2006 }
2007
2008 /* lock semaphore now but bail out when already locked. */
2009 if( sem_trywait(pSem)==-1 ){
2010 rc = SQLITE_BUSY;
2011 goto sem_end_lock;
2012 }
2013
2014 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002015 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002016
2017 sem_end_lock:
2018 return rc;
2019}
2020
drh6b9d6dd2008-12-03 19:34:47 +00002021/*
drh308c2a52010-05-14 11:30:18 +00002022** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002023** must be either NO_LOCK or SHARED_LOCK.
2024**
2025** If the locking level of the file descriptor is already at or below
2026** the requested locking level, this routine is a no-op.
2027*/
drh308c2a52010-05-14 11:30:18 +00002028static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002029 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002030 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002031
2032 assert( pFile );
2033 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002034 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2035 pFile->eFileLock, getpid()));
2036 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002037
2038 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002039 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002040 return SQLITE_OK;
2041 }
2042
2043 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002044 if (eFileLock==SHARED_LOCK) {
2045 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002046 return SQLITE_OK;
2047 }
2048
2049 /* no, really unlock. */
2050 if ( sem_post(pSem)==-1 ) {
2051 int rc, tErrno = errno;
2052 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2053 if( IS_LOCK_ERROR(rc) ){
2054 pFile->lastErrno = tErrno;
2055 }
2056 return rc;
2057 }
drh308c2a52010-05-14 11:30:18 +00002058 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002059 return SQLITE_OK;
2060}
2061
2062/*
2063 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002064 */
drh734c9862008-11-28 15:37:20 +00002065static int semClose(sqlite3_file *id) {
2066 if( id ){
2067 unixFile *pFile = (unixFile*)id;
2068 semUnlock(id, NO_LOCK);
2069 assert( pFile );
2070 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002071 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002072 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002073 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002074 }
2075 return SQLITE_OK;
2076}
2077
2078#endif /* OS_VXWORKS */
2079/*
2080** Named semaphore locking is only available on VxWorks.
2081**
2082*************** End of the named semaphore lock implementation ****************
2083******************************************************************************/
2084
2085
2086/******************************************************************************
2087*************************** Begin AFP Locking *********************************
2088**
2089** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2090** on Apple Macintosh computers - both OS9 and OSX.
2091**
2092** Third-party implementations of AFP are available. But this code here
2093** only works on OSX.
2094*/
2095
drhd2cb50b2009-01-09 21:41:17 +00002096#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002097/*
2098** The afpLockingContext structure contains all afp lock specific state
2099*/
drhbfe66312006-10-03 17:40:40 +00002100typedef struct afpLockingContext afpLockingContext;
2101struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002102 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002103 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002104};
2105
2106struct ByteRangeLockPB2
2107{
2108 unsigned long long offset; /* offset to first byte to lock */
2109 unsigned long long length; /* nbr of bytes to lock */
2110 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2111 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2112 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2113 int fd; /* file desc to assoc this lock with */
2114};
2115
drhfd131da2007-08-07 17:13:03 +00002116#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002117
drh6b9d6dd2008-12-03 19:34:47 +00002118/*
2119** This is a utility for setting or clearing a bit-range lock on an
2120** AFP filesystem.
2121**
2122** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2123*/
2124static int afpSetLock(
2125 const char *path, /* Name of the file to be locked or unlocked */
2126 unixFile *pFile, /* Open file descriptor on path */
2127 unsigned long long offset, /* First byte to be locked */
2128 unsigned long long length, /* Number of bytes to lock */
2129 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002130){
drh6b9d6dd2008-12-03 19:34:47 +00002131 struct ByteRangeLockPB2 pb;
2132 int err;
drhbfe66312006-10-03 17:40:40 +00002133
2134 pb.unLockFlag = setLockFlag ? 0 : 1;
2135 pb.startEndFlag = 0;
2136 pb.offset = offset;
2137 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002138 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002139
drh308c2a52010-05-14 11:30:18 +00002140 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002141 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002142 offset, length));
drhbfe66312006-10-03 17:40:40 +00002143 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2144 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002145 int rc;
2146 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002147 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2148 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002149#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2150 rc = SQLITE_BUSY;
2151#else
drh734c9862008-11-28 15:37:20 +00002152 rc = sqliteErrorFromPosixError(tErrno,
2153 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002154#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002155 if( IS_LOCK_ERROR(rc) ){
2156 pFile->lastErrno = tErrno;
2157 }
2158 return rc;
drhbfe66312006-10-03 17:40:40 +00002159 } else {
aswift5b1a2562008-08-22 00:22:35 +00002160 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002161 }
2162}
2163
drh6b9d6dd2008-12-03 19:34:47 +00002164/*
2165** This routine checks if there is a RESERVED lock held on the specified
2166** file by this or any other process. If such a lock is held, set *pResOut
2167** to a non-zero value otherwise *pResOut is set to zero. The return value
2168** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2169*/
danielk1977e339d652008-06-28 11:23:00 +00002170static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002171 int rc = SQLITE_OK;
2172 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002173 unixFile *pFile = (unixFile*)id;
2174
aswift5b1a2562008-08-22 00:22:35 +00002175 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2176
2177 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002178 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002179 if( context->reserved ){
2180 *pResOut = 1;
2181 return SQLITE_OK;
2182 }
drh8af6c222010-05-14 12:43:01 +00002183 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002184
2185 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002186 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002187 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002188 }
2189
2190 /* Otherwise see if some other process holds it.
2191 */
aswift5b1a2562008-08-22 00:22:35 +00002192 if( !reserved ){
2193 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002194 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002195 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002196 /* if we succeeded in taking the reserved lock, unlock it to restore
2197 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002198 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002199 } else {
2200 /* if we failed to get the lock then someone else must have it */
2201 reserved = 1;
2202 }
2203 if( IS_LOCK_ERROR(lrc) ){
2204 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002205 }
2206 }
drhbfe66312006-10-03 17:40:40 +00002207
drh7ed97b92010-01-20 13:07:21 +00002208 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002209 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002210
2211 *pResOut = reserved;
2212 return rc;
drhbfe66312006-10-03 17:40:40 +00002213}
2214
drh6b9d6dd2008-12-03 19:34:47 +00002215/*
drh308c2a52010-05-14 11:30:18 +00002216** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002217** of the following:
2218**
2219** (1) SHARED_LOCK
2220** (2) RESERVED_LOCK
2221** (3) PENDING_LOCK
2222** (4) EXCLUSIVE_LOCK
2223**
2224** Sometimes when requesting one lock state, additional lock states
2225** are inserted in between. The locking might fail on one of the later
2226** transitions leaving the lock state different from what it started but
2227** still short of its goal. The following chart shows the allowed
2228** transitions and the inserted intermediate states:
2229**
2230** UNLOCKED -> SHARED
2231** SHARED -> RESERVED
2232** SHARED -> (PENDING) -> EXCLUSIVE
2233** RESERVED -> (PENDING) -> EXCLUSIVE
2234** PENDING -> EXCLUSIVE
2235**
2236** This routine will only increase a lock. Use the sqlite3OsUnlock()
2237** routine to lower a locking level.
2238*/
drh308c2a52010-05-14 11:30:18 +00002239static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002240 int rc = SQLITE_OK;
2241 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002242 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002243 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002244
2245 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002246 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2247 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002248 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002249
drhbfe66312006-10-03 17:40:40 +00002250 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002251 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002252 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002253 */
drh308c2a52010-05-14 11:30:18 +00002254 if( pFile->eFileLock>=eFileLock ){
2255 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2256 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002257 return SQLITE_OK;
2258 }
2259
2260 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002261 ** (1) We never move from unlocked to anything higher than shared lock.
2262 ** (2) SQLite never explicitly requests a pendig lock.
2263 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002264 */
drh308c2a52010-05-14 11:30:18 +00002265 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2266 assert( eFileLock!=PENDING_LOCK );
2267 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002268
drh8af6c222010-05-14 12:43:01 +00002269 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002270 */
drh6c7d5c52008-11-21 20:32:33 +00002271 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002272 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002273
2274 /* If some thread using this PID has a lock via a different unixFile*
2275 ** handle that precludes the requested lock, return BUSY.
2276 */
drh8af6c222010-05-14 12:43:01 +00002277 if( (pFile->eFileLock!=pInode->eFileLock &&
2278 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002279 ){
2280 rc = SQLITE_BUSY;
2281 goto afp_end_lock;
2282 }
2283
2284 /* If a SHARED lock is requested, and some thread using this PID already
2285 ** has a SHARED or RESERVED lock, then increment reference counts and
2286 ** return SQLITE_OK.
2287 */
drh308c2a52010-05-14 11:30:18 +00002288 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002289 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002290 assert( eFileLock==SHARED_LOCK );
2291 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002292 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002293 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002294 pInode->nShared++;
2295 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002296 goto afp_end_lock;
2297 }
drhbfe66312006-10-03 17:40:40 +00002298
2299 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002300 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2301 ** be released.
2302 */
drh308c2a52010-05-14 11:30:18 +00002303 if( eFileLock==SHARED_LOCK
2304 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002305 ){
2306 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002307 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002308 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002309 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002310 goto afp_end_lock;
2311 }
2312 }
2313
2314 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002315 ** operating system calls for the specified lock.
2316 */
drh308c2a52010-05-14 11:30:18 +00002317 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002318 int lrc1, lrc2, lrc1Errno;
2319 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002320
drh8af6c222010-05-14 12:43:01 +00002321 assert( pInode->nShared==0 );
2322 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002323
2324 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002325 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002326 /* note that the quality of the randomness doesn't matter that much */
2327 lk = random();
drh8af6c222010-05-14 12:43:01 +00002328 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002329 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002330 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002331 if( IS_LOCK_ERROR(lrc1) ){
2332 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002333 }
aswift5b1a2562008-08-22 00:22:35 +00002334 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002335 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002336
aswift5b1a2562008-08-22 00:22:35 +00002337 if( IS_LOCK_ERROR(lrc1) ) {
2338 pFile->lastErrno = lrc1Errno;
2339 rc = lrc1;
2340 goto afp_end_lock;
2341 } else if( IS_LOCK_ERROR(lrc2) ){
2342 rc = lrc2;
2343 goto afp_end_lock;
2344 } else if( lrc1 != SQLITE_OK ) {
2345 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002346 } else {
drh308c2a52010-05-14 11:30:18 +00002347 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002348 pInode->nLock++;
2349 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002350 }
drh8af6c222010-05-14 12:43:01 +00002351 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002352 /* We are trying for an exclusive lock but another thread in this
2353 ** same process is still holding a shared lock. */
2354 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002355 }else{
2356 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2357 ** assumed that there is a SHARED or greater lock on the file
2358 ** already.
2359 */
2360 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002361 assert( 0!=pFile->eFileLock );
2362 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002363 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002364 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002365 if( !failed ){
2366 context->reserved = 1;
2367 }
drhbfe66312006-10-03 17:40:40 +00002368 }
drh308c2a52010-05-14 11:30:18 +00002369 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002370 /* Acquire an EXCLUSIVE lock */
2371
2372 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002373 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002374 */
drh6b9d6dd2008-12-03 19:34:47 +00002375 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002376 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002377 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002378 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002379 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002380 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002381 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002382 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002383 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2384 ** a critical I/O error
2385 */
2386 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2387 SQLITE_IOERR_LOCK;
2388 goto afp_end_lock;
2389 }
2390 }else{
aswift5b1a2562008-08-22 00:22:35 +00002391 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002392 }
2393 }
aswift5b1a2562008-08-22 00:22:35 +00002394 if( failed ){
2395 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002396 }
2397 }
2398
2399 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002400 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002401 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002402 }else if( eFileLock==EXCLUSIVE_LOCK ){
2403 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002404 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002405 }
2406
2407afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002408 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002409 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2410 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002411 return rc;
2412}
2413
2414/*
drh308c2a52010-05-14 11:30:18 +00002415** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002416** must be either NO_LOCK or SHARED_LOCK.
2417**
2418** If the locking level of the file descriptor is already at or below
2419** the requested locking level, this routine is a no-op.
2420*/
drh308c2a52010-05-14 11:30:18 +00002421static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002422 int rc = SQLITE_OK;
2423 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002424 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002425 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2426 int skipShared = 0;
2427#ifdef SQLITE_TEST
2428 int h = pFile->h;
2429#endif
drhbfe66312006-10-03 17:40:40 +00002430
2431 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002432 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002433 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002434 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002435
drh308c2a52010-05-14 11:30:18 +00002436 assert( eFileLock<=SHARED_LOCK );
2437 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002438 return SQLITE_OK;
2439 }
drh6c7d5c52008-11-21 20:32:33 +00002440 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002441 pInode = pFile->pInode;
2442 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002443 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002444 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002445 SimulateIOErrorBenign(1);
2446 SimulateIOError( h=(-1) )
2447 SimulateIOErrorBenign(0);
2448
2449#ifndef NDEBUG
2450 /* When reducing a lock such that other processes can start
2451 ** reading the database file again, make sure that the
2452 ** transaction counter was updated if any part of the database
2453 ** file changed. If the transaction counter is not updated,
2454 ** other connections to the same file might not realize that
2455 ** the file has changed and hence might not know to flush their
2456 ** cache. The use of a stale cache can lead to database corruption.
2457 */
2458 assert( pFile->inNormalWrite==0
2459 || pFile->dbUpdate==0
2460 || pFile->transCntrChng==1 );
2461 pFile->inNormalWrite = 0;
2462#endif
aswiftaebf4132008-11-21 00:10:35 +00002463
drh308c2a52010-05-14 11:30:18 +00002464 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002465 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002466 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002467 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002468 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002469 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2470 } else {
2471 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002472 }
2473 }
drh308c2a52010-05-14 11:30:18 +00002474 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002475 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002476 }
drh308c2a52010-05-14 11:30:18 +00002477 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002478 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2479 if( !rc ){
2480 context->reserved = 0;
2481 }
aswiftaebf4132008-11-21 00:10:35 +00002482 }
drh8af6c222010-05-14 12:43:01 +00002483 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2484 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002485 }
aswiftaebf4132008-11-21 00:10:35 +00002486 }
drh308c2a52010-05-14 11:30:18 +00002487 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002488
drh7ed97b92010-01-20 13:07:21 +00002489 /* Decrement the shared lock counter. Release the lock using an
2490 ** OS call only when all threads in this same process have released
2491 ** the lock.
2492 */
drh8af6c222010-05-14 12:43:01 +00002493 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2494 pInode->nShared--;
2495 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002496 SimulateIOErrorBenign(1);
2497 SimulateIOError( h=(-1) )
2498 SimulateIOErrorBenign(0);
2499 if( !skipShared ){
2500 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2501 }
2502 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002503 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002504 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002505 }
2506 }
2507 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002508 pInode->nLock--;
2509 assert( pInode->nLock>=0 );
2510 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002511 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002512 }
2513 }
drhbfe66312006-10-03 17:40:40 +00002514 }
drh7ed97b92010-01-20 13:07:21 +00002515
drh6c7d5c52008-11-21 20:32:33 +00002516 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002517 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002518 return rc;
2519}
2520
2521/*
drh339eb0b2008-03-07 15:34:11 +00002522** Close a file & cleanup AFP specific locking context
2523*/
danielk1977e339d652008-06-28 11:23:00 +00002524static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002525 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002526 if( id ){
2527 unixFile *pFile = (unixFile*)id;
2528 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002529 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002530 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002531 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002532 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002533 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002534 ** the last lock is cleared.
2535 */
dan08da86a2009-08-21 17:18:03 +00002536 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002537 }
danb0ac3e32010-06-16 10:55:42 +00002538 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002539 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002540 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002541 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002542 }
drh7ed97b92010-01-20 13:07:21 +00002543 return rc;
drhbfe66312006-10-03 17:40:40 +00002544}
2545
drhd2cb50b2009-01-09 21:41:17 +00002546#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002547/*
2548** The code above is the AFP lock implementation. The code is specific
2549** to MacOSX and does not work on other unix platforms. No alternative
2550** is available. If you don't compile for a mac, then the "unix-afp"
2551** VFS is not available.
2552**
2553********************* End of the AFP lock implementation **********************
2554******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002555
drh7ed97b92010-01-20 13:07:21 +00002556/******************************************************************************
2557*************************** Begin NFS Locking ********************************/
2558
2559#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2560/*
drh308c2a52010-05-14 11:30:18 +00002561 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002562 ** must be either NO_LOCK or SHARED_LOCK.
2563 **
2564 ** If the locking level of the file descriptor is already at or below
2565 ** the requested locking level, this routine is a no-op.
2566 */
drh308c2a52010-05-14 11:30:18 +00002567static int nfsUnlock(sqlite3_file *id, int eFileLock){
2568 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002569}
2570
2571#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2572/*
2573** The code above is the NFS lock implementation. The code is specific
2574** to MacOSX and does not work on other unix platforms. No alternative
2575** is available.
2576**
2577********************* End of the NFS lock implementation **********************
2578******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002579
2580/******************************************************************************
2581**************** Non-locking sqlite3_file methods *****************************
2582**
2583** The next division contains implementations for all methods of the
2584** sqlite3_file object other than the locking methods. The locking
2585** methods were defined in divisions above (one locking method per
2586** division). Those methods that are common to all locking modes
2587** are gather together into this division.
2588*/
drhbfe66312006-10-03 17:40:40 +00002589
2590/*
drh734c9862008-11-28 15:37:20 +00002591** Seek to the offset passed as the second argument, then read cnt
2592** bytes into pBuf. Return the number of bytes actually read.
2593**
2594** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2595** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2596** one system to another. Since SQLite does not define USE_PREAD
2597** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2598** See tickets #2741 and #2681.
2599**
2600** To avoid stomping the errno value on a failed read the lastErrno value
2601** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002602*/
drh734c9862008-11-28 15:37:20 +00002603static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2604 int got;
drh7ed97b92010-01-20 13:07:21 +00002605#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002606 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002607#endif
drh734c9862008-11-28 15:37:20 +00002608 TIMER_START;
2609#if defined(USE_PREAD)
2610 got = pread(id->h, pBuf, cnt, offset);
2611 SimulateIOError( got = -1 );
2612#elif defined(USE_PREAD64)
2613 got = pread64(id->h, pBuf, cnt, offset);
2614 SimulateIOError( got = -1 );
2615#else
2616 newOffset = lseek(id->h, offset, SEEK_SET);
2617 SimulateIOError( newOffset-- );
2618 if( newOffset!=offset ){
2619 if( newOffset == -1 ){
2620 ((unixFile*)id)->lastErrno = errno;
2621 }else{
2622 ((unixFile*)id)->lastErrno = 0;
2623 }
2624 return -1;
2625 }
2626 got = read(id->h, pBuf, cnt);
2627#endif
2628 TIMER_END;
2629 if( got<0 ){
2630 ((unixFile*)id)->lastErrno = errno;
2631 }
drh308c2a52010-05-14 11:30:18 +00002632 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002633 return got;
drhbfe66312006-10-03 17:40:40 +00002634}
2635
2636/*
drh734c9862008-11-28 15:37:20 +00002637** Read data from a file into a buffer. Return SQLITE_OK if all
2638** bytes were read successfully and SQLITE_IOERR if anything goes
2639** wrong.
drh339eb0b2008-03-07 15:34:11 +00002640*/
drh734c9862008-11-28 15:37:20 +00002641static int unixRead(
2642 sqlite3_file *id,
2643 void *pBuf,
2644 int amt,
2645 sqlite3_int64 offset
2646){
dan08da86a2009-08-21 17:18:03 +00002647 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002648 int got;
2649 assert( id );
drh08c6d442009-02-09 17:34:07 +00002650
dan08da86a2009-08-21 17:18:03 +00002651 /* If this is a database file (not a journal, master-journal or temp
2652 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002653#if 0
dane946c392009-08-22 11:39:46 +00002654 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002655 || offset>=PENDING_BYTE+512
2656 || offset+amt<=PENDING_BYTE
2657 );
dan7c246102010-04-12 19:00:29 +00002658#endif
drh08c6d442009-02-09 17:34:07 +00002659
dan08da86a2009-08-21 17:18:03 +00002660 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002661 if( got==amt ){
2662 return SQLITE_OK;
2663 }else if( got<0 ){
2664 /* lastErrno set by seekAndRead */
2665 return SQLITE_IOERR_READ;
2666 }else{
dan08da86a2009-08-21 17:18:03 +00002667 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002668 /* Unread parts of the buffer must be zero-filled */
2669 memset(&((char*)pBuf)[got], 0, amt-got);
2670 return SQLITE_IOERR_SHORT_READ;
2671 }
2672}
2673
2674/*
2675** Seek to the offset in id->offset then read cnt bytes into pBuf.
2676** Return the number of bytes actually read. Update the offset.
2677**
2678** To avoid stomping the errno value on a failed write the lastErrno value
2679** is set before returning.
2680*/
2681static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2682 int got;
drh7ed97b92010-01-20 13:07:21 +00002683#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002684 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002685#endif
drh734c9862008-11-28 15:37:20 +00002686 TIMER_START;
2687#if defined(USE_PREAD)
2688 got = pwrite(id->h, pBuf, cnt, offset);
2689#elif defined(USE_PREAD64)
2690 got = pwrite64(id->h, pBuf, cnt, offset);
2691#else
2692 newOffset = lseek(id->h, offset, SEEK_SET);
2693 if( newOffset!=offset ){
2694 if( newOffset == -1 ){
2695 ((unixFile*)id)->lastErrno = errno;
2696 }else{
2697 ((unixFile*)id)->lastErrno = 0;
2698 }
2699 return -1;
2700 }
2701 got = write(id->h, pBuf, cnt);
2702#endif
2703 TIMER_END;
2704 if( got<0 ){
2705 ((unixFile*)id)->lastErrno = errno;
2706 }
2707
drh308c2a52010-05-14 11:30:18 +00002708 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002709 return got;
2710}
2711
2712
2713/*
2714** Write data from a buffer into a file. Return SQLITE_OK on success
2715** or some other error code on failure.
2716*/
2717static int unixWrite(
2718 sqlite3_file *id,
2719 const void *pBuf,
2720 int amt,
2721 sqlite3_int64 offset
2722){
dan08da86a2009-08-21 17:18:03 +00002723 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002724 int wrote = 0;
2725 assert( id );
2726 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002727
dan08da86a2009-08-21 17:18:03 +00002728 /* If this is a database file (not a journal, master-journal or temp
2729 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002730#if 0
dane946c392009-08-22 11:39:46 +00002731 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002732 || offset>=PENDING_BYTE+512
2733 || offset+amt<=PENDING_BYTE
2734 );
dan7c246102010-04-12 19:00:29 +00002735#endif
drh08c6d442009-02-09 17:34:07 +00002736
drh8f941bc2009-01-14 23:03:40 +00002737#ifndef NDEBUG
2738 /* If we are doing a normal write to a database file (as opposed to
2739 ** doing a hot-journal rollback or a write to some file other than a
2740 ** normal database file) then record the fact that the database
2741 ** has changed. If the transaction counter is modified, record that
2742 ** fact too.
2743 */
dan08da86a2009-08-21 17:18:03 +00002744 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002745 pFile->dbUpdate = 1; /* The database has been modified */
2746 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002747 int rc;
drh8f941bc2009-01-14 23:03:40 +00002748 char oldCntr[4];
2749 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002750 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002751 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002752 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002753 pFile->transCntrChng = 1; /* The transaction counter has changed */
2754 }
2755 }
2756 }
2757#endif
2758
dan08da86a2009-08-21 17:18:03 +00002759 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002760 amt -= wrote;
2761 offset += wrote;
2762 pBuf = &((char*)pBuf)[wrote];
2763 }
2764 SimulateIOError(( wrote=(-1), amt=1 ));
2765 SimulateDiskfullError(( wrote=0, amt=1 ));
2766 if( amt>0 ){
2767 if( wrote<0 ){
2768 /* lastErrno set by seekAndWrite */
2769 return SQLITE_IOERR_WRITE;
2770 }else{
dan08da86a2009-08-21 17:18:03 +00002771 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002772 return SQLITE_FULL;
2773 }
2774 }
2775 return SQLITE_OK;
2776}
2777
2778#ifdef SQLITE_TEST
2779/*
2780** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002781** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002782*/
2783int sqlite3_sync_count = 0;
2784int sqlite3_fullsync_count = 0;
2785#endif
2786
2787/*
drh89240432009-03-25 01:06:01 +00002788** We do not trust systems to provide a working fdatasync(). Some do.
2789** Others do no. To be safe, we will stick with the (slower) fsync().
2790** If you know that your system does support fdatasync() correctly,
2791** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002792*/
drh89240432009-03-25 01:06:01 +00002793#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002794# define fdatasync fsync
2795#endif
2796
2797/*
2798** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2799** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2800** only available on Mac OS X. But that could change.
2801*/
2802#ifdef F_FULLFSYNC
2803# define HAVE_FULLFSYNC 1
2804#else
2805# define HAVE_FULLFSYNC 0
2806#endif
2807
2808
2809/*
2810** The fsync() system call does not work as advertised on many
2811** unix systems. The following procedure is an attempt to make
2812** it work better.
2813**
2814** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2815** for testing when we want to run through the test suite quickly.
2816** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2817** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2818** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002819**
2820** SQLite sets the dataOnly flag if the size of the file is unchanged.
2821** The idea behind dataOnly is that it should only write the file content
2822** to disk, not the inode. We only set dataOnly if the file size is
2823** unchanged since the file size is part of the inode. However,
2824** Ted Ts'o tells us that fdatasync() will also write the inode if the
2825** file size has changed. The only real difference between fdatasync()
2826** and fsync(), Ted tells us, is that fdatasync() will not flush the
2827** inode if the mtime or owner or other inode attributes have changed.
2828** We only care about the file size, not the other file attributes, so
2829** as far as SQLite is concerned, an fdatasync() is always adequate.
2830** So, we always use fdatasync() if it is available, regardless of
2831** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002832*/
2833static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002834 int rc;
drh734c9862008-11-28 15:37:20 +00002835
2836 /* The following "ifdef/elif/else/" block has the same structure as
2837 ** the one below. It is replicated here solely to avoid cluttering
2838 ** up the real code with the UNUSED_PARAMETER() macros.
2839 */
2840#ifdef SQLITE_NO_SYNC
2841 UNUSED_PARAMETER(fd);
2842 UNUSED_PARAMETER(fullSync);
2843 UNUSED_PARAMETER(dataOnly);
2844#elif HAVE_FULLFSYNC
2845 UNUSED_PARAMETER(dataOnly);
2846#else
2847 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002848 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002849#endif
2850
2851 /* Record the number of times that we do a normal fsync() and
2852 ** FULLSYNC. This is used during testing to verify that this procedure
2853 ** gets called with the correct arguments.
2854 */
2855#ifdef SQLITE_TEST
2856 if( fullSync ) sqlite3_fullsync_count++;
2857 sqlite3_sync_count++;
2858#endif
2859
2860 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2861 ** no-op
2862 */
2863#ifdef SQLITE_NO_SYNC
2864 rc = SQLITE_OK;
2865#elif HAVE_FULLFSYNC
2866 if( fullSync ){
2867 rc = fcntl(fd, F_FULLFSYNC, 0);
2868 }else{
2869 rc = 1;
2870 }
2871 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002872 ** It shouldn't be possible for fullfsync to fail on the local
2873 ** file system (on OSX), so failure indicates that FULLFSYNC
2874 ** isn't supported for this file system. So, attempt an fsync
2875 ** and (for now) ignore the overhead of a superfluous fcntl call.
2876 ** It'd be better to detect fullfsync support once and avoid
2877 ** the fcntl call every time sync is called.
2878 */
drh734c9862008-11-28 15:37:20 +00002879 if( rc ) rc = fsync(fd);
2880
drh7ed97b92010-01-20 13:07:21 +00002881#elif defined(__APPLE__)
2882 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2883 ** so currently we default to the macro that redefines fdatasync to fsync
2884 */
2885 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002886#else
drh0b647ff2009-03-21 14:41:04 +00002887 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002888#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002889 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002890 rc = fsync(fd);
2891 }
drh0b647ff2009-03-21 14:41:04 +00002892#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002893#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2894
2895 if( OS_VXWORKS && rc!= -1 ){
2896 rc = 0;
2897 }
chw97185482008-11-17 08:05:31 +00002898 return rc;
drhbfe66312006-10-03 17:40:40 +00002899}
2900
drh734c9862008-11-28 15:37:20 +00002901/*
2902** Make sure all writes to a particular file are committed to disk.
2903**
2904** If dataOnly==0 then both the file itself and its metadata (file
2905** size, access time, etc) are synced. If dataOnly!=0 then only the
2906** file data is synced.
2907**
2908** Under Unix, also make sure that the directory entry for the file
2909** has been created by fsync-ing the directory that contains the file.
2910** If we do not do this and we encounter a power failure, the directory
2911** entry for the journal might not exist after we reboot. The next
2912** SQLite to access the file will not know that the journal exists (because
2913** the directory entry for the journal was never created) and the transaction
2914** will not roll back - possibly leading to database corruption.
2915*/
2916static int unixSync(sqlite3_file *id, int flags){
2917 int rc;
2918 unixFile *pFile = (unixFile*)id;
2919
2920 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2921 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2922
2923 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2924 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2925 || (flags&0x0F)==SQLITE_SYNC_FULL
2926 );
2927
2928 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2929 ** line is to test that doing so does not cause any problems.
2930 */
2931 SimulateDiskfullError( return SQLITE_FULL );
2932
2933 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002934 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00002935 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2936 SimulateIOError( rc=1 );
2937 if( rc ){
2938 pFile->lastErrno = errno;
2939 return SQLITE_IOERR_FSYNC;
2940 }
2941 if( pFile->dirfd>=0 ){
2942 int err;
drh308c2a52010-05-14 11:30:18 +00002943 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2944 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00002945#ifndef SQLITE_DISABLE_DIRSYNC
2946 /* The directory sync is only attempted if full_fsync is
2947 ** turned off or unavailable. If a full_fsync occurred above,
2948 ** then the directory sync is superfluous.
2949 */
2950 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2951 /*
2952 ** We have received multiple reports of fsync() returning
2953 ** errors when applied to directories on certain file systems.
2954 ** A failed directory sync is not a big deal. So it seems
2955 ** better to ignore the error. Ticket #1657
2956 */
2957 /* pFile->lastErrno = errno; */
2958 /* return SQLITE_IOERR; */
2959 }
2960#endif
2961 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2962 if( err==0 ){ /* directory when we are done */
2963 pFile->dirfd = -1;
2964 }else{
2965 pFile->lastErrno = errno;
2966 rc = SQLITE_IOERR_DIR_CLOSE;
2967 }
2968 }
2969 return rc;
2970}
2971
2972/*
2973** Truncate an open file to a specified size
2974*/
2975static int unixTruncate(sqlite3_file *id, i64 nByte){
2976 int rc;
2977 assert( id );
2978 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2979 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2980 if( rc ){
2981 ((unixFile*)id)->lastErrno = errno;
2982 return SQLITE_IOERR_TRUNCATE;
2983 }else{
drh3313b142009-11-06 04:13:18 +00002984#ifndef NDEBUG
2985 /* If we are doing a normal write to a database file (as opposed to
2986 ** doing a hot-journal rollback or a write to some file other than a
2987 ** normal database file) and we truncate the file to zero length,
2988 ** that effectively updates the change counter. This might happen
2989 ** when restoring a database using the backup API from a zero-length
2990 ** source.
2991 */
2992 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
2993 ((unixFile*)id)->transCntrChng = 1;
2994 }
2995#endif
2996
drh734c9862008-11-28 15:37:20 +00002997 return SQLITE_OK;
2998 }
2999}
3000
3001/*
3002** Determine the current size of a file in bytes
3003*/
3004static int unixFileSize(sqlite3_file *id, i64 *pSize){
3005 int rc;
3006 struct stat buf;
3007 assert( id );
3008 rc = fstat(((unixFile*)id)->h, &buf);
3009 SimulateIOError( rc=1 );
3010 if( rc!=0 ){
3011 ((unixFile*)id)->lastErrno = errno;
3012 return SQLITE_IOERR_FSTAT;
3013 }
3014 *pSize = buf.st_size;
3015
drh8af6c222010-05-14 12:43:01 +00003016 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003017 ** writes a single byte into that file in order to work around a bug
3018 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3019 ** layers, we need to report this file size as zero even though it is
3020 ** really 1. Ticket #3260.
3021 */
3022 if( *pSize==1 ) *pSize = 0;
3023
3024
3025 return SQLITE_OK;
3026}
3027
drhd2cb50b2009-01-09 21:41:17 +00003028#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003029/*
3030** Handler for proxy-locking file-control verbs. Defined below in the
3031** proxying locking division.
3032*/
3033static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003034#endif
drh715ff302008-12-03 22:32:44 +00003035
danielk1977ad94b582007-08-20 06:44:22 +00003036
danielk1977e3026632004-06-22 11:29:02 +00003037/*
drh9e33c2c2007-08-31 18:34:59 +00003038** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003039*/
drhcc6bb3e2007-08-31 16:11:35 +00003040static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003041 switch( op ){
3042 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003043 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003044 return SQLITE_OK;
3045 }
drh7708e972008-11-29 00:56:52 +00003046 case SQLITE_LAST_ERRNO: {
3047 *(int*)pArg = ((unixFile*)id)->lastErrno;
3048 return SQLITE_OK;
3049 }
drh9ff27ec2010-05-19 19:26:05 +00003050 case SQLITE_FCNTL_SIZE_HINT: {
drhc5276692010-05-21 18:24:06 +00003051#if 0 /* No performance advantage seen on Linux */
drh9ff27ec2010-05-19 19:26:05 +00003052 sqlite3_int64 szFile = *(sqlite3_int64*)pArg;
3053 unixFile *pFile = (unixFile*)id;
3054 ftruncate(pFile->h, szFile);
drhc5276692010-05-21 18:24:06 +00003055#endif
drh9ff27ec2010-05-19 19:26:05 +00003056 return SQLITE_OK;
3057 }
drh8f941bc2009-01-14 23:03:40 +00003058#ifndef NDEBUG
3059 /* The pager calls this method to signal that it has done
3060 ** a rollback and that the database is therefore unchanged and
3061 ** it hence it is OK for the transaction change counter to be
3062 ** unchanged.
3063 */
3064 case SQLITE_FCNTL_DB_UNCHANGED: {
3065 ((unixFile*)id)->dbUpdate = 0;
3066 return SQLITE_OK;
3067 }
3068#endif
drhd2cb50b2009-01-09 21:41:17 +00003069#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003070 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003071 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003072 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003073 }
drhd2cb50b2009-01-09 21:41:17 +00003074#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003075 }
drhcc6bb3e2007-08-31 16:11:35 +00003076 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003077}
3078
3079/*
danielk1977a3d4c882007-03-23 10:08:38 +00003080** Return the sector size in bytes of the underlying block device for
3081** the specified file. This is almost always 512 bytes, but may be
3082** larger for some devices.
3083**
3084** SQLite code assumes this function cannot fail. It also assumes that
3085** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003086** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003087** same for both.
3088*/
danielk1977397d65f2008-11-19 11:35:39 +00003089static int unixSectorSize(sqlite3_file *NotUsed){
3090 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003091 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003092}
3093
danielk197790949c22007-08-17 16:50:38 +00003094/*
danielk1977397d65f2008-11-19 11:35:39 +00003095** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003096*/
danielk1977397d65f2008-11-19 11:35:39 +00003097static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3098 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003099 return 0;
3100}
3101
drhd9e5c4f2010-05-12 18:01:39 +00003102#ifndef SQLITE_OMIT_WAL
3103
3104
3105/*
drhd91c68f2010-05-14 14:52:25 +00003106** Object used to represent an shared memory buffer.
3107**
3108** When multiple threads all reference the same wal-index, each thread
3109** has its own unixShm object, but they all point to a single instance
3110** of this unixShmNode object. In other words, each wal-index is opened
3111** only once per process.
3112**
3113** Each unixShmNode object is connected to a single unixInodeInfo object.
3114** We could coalesce this object into unixInodeInfo, but that would mean
3115** every open file that does not use shared memory (in other words, most
3116** open files) would have to carry around this extra information. So
3117** the unixInodeInfo object contains a pointer to this unixShmNode object
3118** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003119**
3120** unixMutexHeld() must be true when creating or destroying
3121** this object or while reading or writing the following fields:
3122**
3123** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003124**
3125** The following fields are read-only after the object is created:
3126**
3127** fid
3128** zFilename
3129**
drhd91c68f2010-05-14 14:52:25 +00003130** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003131** unixMutexHeld() is true when reading or writing any other field
3132** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003133*/
drhd91c68f2010-05-14 14:52:25 +00003134struct unixShmNode {
3135 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003136 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003137 char *zFilename; /* Name of the mmapped file */
3138 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003139 int szRegion; /* Size of shared-memory regions */
3140 int nRegion; /* Size of array apRegion */
3141 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003142 int nRef; /* Number of unixShm objects pointing to this */
3143 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003144#ifdef SQLITE_DEBUG
3145 u8 exclMask; /* Mask of exclusive locks held */
3146 u8 sharedMask; /* Mask of shared locks held */
3147 u8 nextShmId; /* Next available unixShm.id value */
3148#endif
3149};
3150
3151/*
drhd9e5c4f2010-05-12 18:01:39 +00003152** Structure used internally by this VFS to record the state of an
3153** open shared memory connection.
3154**
drhd91c68f2010-05-14 14:52:25 +00003155** The following fields are initialized when this object is created and
3156** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003157**
drhd91c68f2010-05-14 14:52:25 +00003158** unixShm.pFile
3159** unixShm.id
3160**
3161** All other fields are read/write. The unixShm.pFile->mutex must be held
3162** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003163*/
3164struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003165 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3166 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003167 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003168 u16 sharedMask; /* Mask of shared locks held */
3169 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003170#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003171 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003172#endif
3173};
3174
3175/*
drhd9e5c4f2010-05-12 18:01:39 +00003176** Constants used for locking
3177*/
drh42224412010-05-31 14:28:25 +00003178#define UNIX_SHM_BASE ((18+SQLITE_SHM_NLOCK)*4) /* first lock byte */
3179#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003180
drhd9e5c4f2010-05-12 18:01:39 +00003181/*
drh73b64e42010-05-30 19:55:15 +00003182** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003183**
3184** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3185** otherwise.
3186*/
3187static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003188 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3189 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003190 int ofst, /* First byte of the locking range */
3191 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003192){
3193 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003194 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003195
drhd91c68f2010-05-14 14:52:25 +00003196 /* Access to the unixShmNode object is serialized by the caller */
3197 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003198
drh73b64e42010-05-30 19:55:15 +00003199 /* Shared locks never span more than one byte */
3200 assert( n==1 || lockType!=F_RDLCK );
3201
3202 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003203 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003204
drhd9e5c4f2010-05-12 18:01:39 +00003205 /* Initialize the locking parameters */
3206 memset(&f, 0, sizeof(f));
3207 f.l_type = lockType;
3208 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003209 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003210 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003211
drh73b64e42010-05-30 19:55:15 +00003212 rc = fcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003213 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3214
3215 /* Update the global lock state and do debug tracing */
3216#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003217 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003218 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003219 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003220 if( rc==SQLITE_OK ){
3221 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003222 OSTRACE(("unlock %d ok", ofst));
3223 pShmNode->exclMask &= ~mask;
3224 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003225 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003226 OSTRACE(("read-lock %d ok", ofst));
3227 pShmNode->exclMask &= ~mask;
3228 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003229 }else{
3230 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003231 OSTRACE(("write-lock %d ok", ofst));
3232 pShmNode->exclMask |= mask;
3233 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003234 }
3235 }else{
3236 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003237 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003238 }else if( lockType==F_RDLCK ){
3239 OSTRACE(("read-lock failed"));
3240 }else{
3241 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003242 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003243 }
3244 }
drh20e1f082010-05-31 16:10:12 +00003245 OSTRACE((" - afterwards %03x,%03x\n",
3246 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003247 }
drhd9e5c4f2010-05-12 18:01:39 +00003248#endif
3249
3250 return rc;
3251}
3252
drhd9e5c4f2010-05-12 18:01:39 +00003253
3254/*
drhd91c68f2010-05-14 14:52:25 +00003255** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003256**
3257** This is not a VFS shared-memory method; it is a utility function called
3258** by VFS shared-memory methods.
3259*/
drhd91c68f2010-05-14 14:52:25 +00003260static void unixShmPurge(unixFile *pFd){
3261 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003262 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003263 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003264 int i;
drhd91c68f2010-05-14 14:52:25 +00003265 assert( p->pInode==pFd->pInode );
3266 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003267 for(i=0; i<p->nRegion; i++){
3268 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003269 }
dan18801912010-06-14 14:07:50 +00003270 sqlite3_free(p->apRegion);
drhd91c68f2010-05-14 14:52:25 +00003271 if( p->h>=0 ) close(p->h);
3272 p->pInode->pShmNode = 0;
3273 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003274 }
3275}
3276
drh8b3cf822010-06-01 21:02:51 +00003277/* Forward reference */
3278static const char *unixTempFileDir(int);
3279
drhd9e5c4f2010-05-12 18:01:39 +00003280/*
3281** Open a shared-memory area. This particular implementation uses
3282** mmapped files.
3283**
3284** zName is a filename used to identify the shared-memory area. The
3285** implementation does not (and perhaps should not) use this name
3286** directly, but rather use it as a template for finding an appropriate
3287** name for the shared-memory storage. In this implementation, the
3288** string "-index" is appended to zName and used as the name of the
3289** mmapped file.
3290**
3291** When opening a new shared-memory file, if no other instances of that
3292** file are currently open, in this process or in other processes, then
3293** the file must be truncated to zero length or have its header cleared.
3294*/
3295static int unixShmOpen(
3296 sqlite3_file *fd /* The file descriptor of the associated database */
3297){
3298 struct unixShm *p = 0; /* The connection to be opened */
drhd91c68f2010-05-14 14:52:25 +00003299 struct unixShmNode *pShmNode = 0; /* The underlying mmapped file */
drhd9e5c4f2010-05-12 18:01:39 +00003300 int rc; /* Result code */
drhd9e5c4f2010-05-12 18:01:39 +00003301 struct unixFile *pDbFd; /* Underlying database file */
drh8b3cf822010-06-01 21:02:51 +00003302 unixInodeInfo *pInode; /* The inode of fd */
3303 const char *zTempDir; /* Directory for temporary files */
3304 int nTempDir; /* Size of the zTempDir string */
drhd9e5c4f2010-05-12 18:01:39 +00003305
drhd91c68f2010-05-14 14:52:25 +00003306 /* Allocate space for the new sqlite3_shm object.
drhd9e5c4f2010-05-12 18:01:39 +00003307 */
3308 p = sqlite3_malloc( sizeof(*p) );
3309 if( p==0 ) return SQLITE_NOMEM;
3310 memset(p, 0, sizeof(*p));
3311 pDbFd = (struct unixFile*)fd;
3312 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003313
drhd91c68f2010-05-14 14:52:25 +00003314 /* Check to see if a unixShmNode object already exists. Reuse an existing
3315 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003316 */
3317 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003318 pInode = pDbFd->pInode;
3319 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003320 if( pShmNode==0 ){
drh8b3cf822010-06-01 21:02:51 +00003321 zTempDir = unixTempFileDir(1);
3322 if( zTempDir==0 ){
3323 unixLeaveMutex();
3324 sqlite3_free(p);
3325 return SQLITE_CANTOPEN_NOTEMPDIR;
3326 }
3327 nTempDir = strlen(zTempDir);
3328 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nTempDir + 50 );
drhd91c68f2010-05-14 14:52:25 +00003329 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003330 rc = SQLITE_NOMEM;
3331 goto shm_open_err;
3332 }
drhd91c68f2010-05-14 14:52:25 +00003333 memset(pShmNode, 0, sizeof(*pShmNode));
3334 pShmNode->zFilename = (char*)&pShmNode[1];
drh8b3cf822010-06-01 21:02:51 +00003335 sqlite3_snprintf(nTempDir+50, pShmNode->zFilename,
3336 "%s/sqlite-wi-%x-%x", zTempDir,
3337 (u32)pInode->fileId.dev, (u32)pInode->fileId.ino);
drhd91c68f2010-05-14 14:52:25 +00003338 pShmNode->h = -1;
3339 pDbFd->pInode->pShmNode = pShmNode;
3340 pShmNode->pInode = pDbFd->pInode;
3341 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3342 if( pShmNode->mutex==0 ){
3343 rc = SQLITE_NOMEM;
3344 goto shm_open_err;
3345 }
drhd9e5c4f2010-05-12 18:01:39 +00003346
drhd91c68f2010-05-14 14:52:25 +00003347 pShmNode->h = open(pShmNode->zFilename, O_RDWR|O_CREAT, 0664);
3348 if( pShmNode->h<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003349 rc = SQLITE_CANTOPEN_BKPT;
3350 goto shm_open_err;
3351 }
3352
drhd9e5c4f2010-05-12 18:01:39 +00003353 /* Check to see if another process is holding the dead-man switch.
3354 ** If not, truncate the file to zero length.
3355 */
drhd91c68f2010-05-14 14:52:25 +00003356 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003357 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhd91c68f2010-05-14 14:52:25 +00003358 if( ftruncate(pShmNode->h, 0) ){
drhaab4c022010-06-02 14:45:51 +00003359 rc = SQLITE_IOERR_SHMOPEN;
drhd9e5c4f2010-05-12 18:01:39 +00003360 }
3361 }
3362 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003363 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003364 }
3365 if( rc ) goto shm_open_err;
3366 }
3367
drhd91c68f2010-05-14 14:52:25 +00003368 /* Make the new connection a child of the unixShmNode */
3369 p->pShmNode = pShmNode;
3370 p->pNext = pShmNode->pFirst;
drhd9e5c4f2010-05-12 18:01:39 +00003371#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003372 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003373#endif
drhd91c68f2010-05-14 14:52:25 +00003374 pShmNode->pFirst = p;
3375 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003376 pDbFd->pShm = p;
3377 unixLeaveMutex();
3378 return SQLITE_OK;
3379
3380 /* Jump here on any error */
3381shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003382 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003383 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003384 unixLeaveMutex();
3385 return rc;
3386}
3387
3388/*
3389** Close a connection to shared-memory. Delete the underlying
3390** storage if deleteFlag is true.
3391*/
3392static int unixShmClose(
3393 sqlite3_file *fd, /* The underlying database file */
3394 int deleteFlag /* Delete shared-memory if true */
3395){
3396 unixShm *p; /* The connection to be closed */
drhd91c68f2010-05-14 14:52:25 +00003397 unixShmNode *pShmNode; /* The underlying shared-memory file */
drhd9e5c4f2010-05-12 18:01:39 +00003398 unixShm **pp; /* For looping over sibling connections */
3399 unixFile *pDbFd; /* The underlying database file */
3400
3401 pDbFd = (unixFile*)fd;
3402 p = pDbFd->pShm;
3403 if( p==0 ) return SQLITE_OK;
drhd91c68f2010-05-14 14:52:25 +00003404 pShmNode = p->pShmNode;
3405
3406 assert( pShmNode==pDbFd->pInode->pShmNode );
3407 assert( pShmNode->pInode==pDbFd->pInode );
drhd9e5c4f2010-05-12 18:01:39 +00003408
drhd91c68f2010-05-14 14:52:25 +00003409 /* Remove connection p from the set of connections associated
3410 ** with pShmNode */
3411 sqlite3_mutex_enter(pShmNode->mutex);
3412 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
drhd9e5c4f2010-05-12 18:01:39 +00003413 *pp = p->pNext;
3414
3415 /* Free the connection p */
3416 sqlite3_free(p);
3417 pDbFd->pShm = 0;
drhd91c68f2010-05-14 14:52:25 +00003418 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003419
drhd91c68f2010-05-14 14:52:25 +00003420 /* If pShmNode->nRef has reached 0, then close the underlying
drhd9e5c4f2010-05-12 18:01:39 +00003421 ** shared-memory file, too */
3422 unixEnterMutex();
drhd91c68f2010-05-14 14:52:25 +00003423 assert( pShmNode->nRef>0 );
3424 pShmNode->nRef--;
3425 if( pShmNode->nRef==0 ){
3426 if( deleteFlag ) unlink(pShmNode->zFilename);
3427 unixShmPurge(pDbFd);
drhd9e5c4f2010-05-12 18:01:39 +00003428 }
3429 unixLeaveMutex();
3430
3431 return SQLITE_OK;
3432}
3433
3434/*
drhd9e5c4f2010-05-12 18:01:39 +00003435** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003436**
3437** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3438** different here than in posix. In xShmLock(), one can go from unlocked
3439** to shared and back or from unlocked to exclusive and back. But one may
3440** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003441*/
3442static int unixShmLock(
3443 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003444 int ofst, /* First lock to acquire or release */
3445 int n, /* Number of locks to acquire or release */
3446 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003447){
drh73b64e42010-05-30 19:55:15 +00003448 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3449 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3450 unixShm *pX; /* For looping over all siblings */
3451 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3452 int rc = SQLITE_OK; /* Result code */
3453 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003454
drhd91c68f2010-05-14 14:52:25 +00003455 assert( pShmNode==pDbFd->pInode->pShmNode );
3456 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003457 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003458 assert( n>=1 );
3459 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3460 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3461 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3462 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3463 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003464
drhc99597c2010-05-31 01:41:15 +00003465 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003466 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003467 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003468 if( flags & SQLITE_SHM_UNLOCK ){
3469 u16 allMask = 0; /* Mask of locks held by siblings */
3470
3471 /* See if any siblings hold this same lock */
3472 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3473 if( pX==p ) continue;
3474 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3475 allMask |= pX->sharedMask;
3476 }
3477
3478 /* Unlock the system-level locks */
3479 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003480 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003481 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003482 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003483 }
drh73b64e42010-05-30 19:55:15 +00003484
3485 /* Undo the local locks */
3486 if( rc==SQLITE_OK ){
3487 p->exclMask &= ~mask;
3488 p->sharedMask &= ~mask;
3489 }
3490 }else if( flags & SQLITE_SHM_SHARED ){
3491 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3492
3493 /* Find out which shared locks are already held by sibling connections.
3494 ** If any sibling already holds an exclusive lock, go ahead and return
3495 ** SQLITE_BUSY.
3496 */
3497 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003498 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003499 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003500 break;
3501 }
3502 allShared |= pX->sharedMask;
3503 }
3504
3505 /* Get shared locks at the system level, if necessary */
3506 if( rc==SQLITE_OK ){
3507 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003508 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003509 }else{
drh73b64e42010-05-30 19:55:15 +00003510 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003511 }
drhd9e5c4f2010-05-12 18:01:39 +00003512 }
drh73b64e42010-05-30 19:55:15 +00003513
3514 /* Get the local shared locks */
3515 if( rc==SQLITE_OK ){
3516 p->sharedMask |= mask;
3517 }
3518 }else{
3519 /* Make sure no sibling connections hold locks that will block this
3520 ** lock. If any do, return SQLITE_BUSY right away.
3521 */
3522 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003523 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3524 rc = SQLITE_BUSY;
3525 break;
3526 }
3527 }
3528
3529 /* Get the exclusive locks at the system level. Then if successful
3530 ** also mark the local connection as being locked.
3531 */
3532 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003533 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003534 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003535 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003536 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003537 }
drhd9e5c4f2010-05-12 18:01:39 +00003538 }
3539 }
drhd91c68f2010-05-14 14:52:25 +00003540 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003541 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3542 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003543 return rc;
3544}
3545
drh286a2882010-05-20 23:51:06 +00003546/*
3547** Implement a memory barrier or memory fence on shared memory.
3548**
3549** All loads and stores begun before the barrier must complete before
3550** any load or store begun after the barrier.
3551*/
3552static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003553 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003554){
drhb29ad852010-06-01 00:03:57 +00003555 unixEnterMutex();
3556 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003557}
3558
dan18801912010-06-14 14:07:50 +00003559/*
3560** This function is called to obtain a pointer to region iRegion of the
3561** shared-memory associated with the database file fd. Shared-memory regions
3562** are numbered starting from zero. Each shared-memory region is szRegion
3563** bytes in size.
3564**
3565** If an error occurs, an error code is returned and *pp is set to NULL.
3566**
3567** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
3568** region has not been allocated (by any client, including one running in a
3569** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3570** isWrite is non-zero and the requested shared-memory region has not yet
3571** been allocated, it is allocated by this function.
3572**
3573** If the shared-memory region has already been allocated or is allocated by
3574** this call as described above, then it is mapped into this processes
3575** address space (if it is not already), *pp is set to point to the mapped
3576** memory and SQLITE_OK returned.
3577*/
dan9785fc92010-06-14 16:16:33 +00003578static int unixShmMap(
dan13a3cb82010-06-11 19:04:21 +00003579 sqlite3_file *fd, /* Handle open on database file */
dan18801912010-06-14 14:07:50 +00003580 int iRegion, /* Region to retrieve */
3581 int szRegion, /* Size of regions */
dan13a3cb82010-06-11 19:04:21 +00003582 int isWrite, /* True to extend file if necessary */
3583 void volatile **pp /* OUT: Mapped memory */
3584){
3585 unixFile *pDbFd = (unixFile*)fd;
3586 unixShm *p = pDbFd->pShm;
3587 unixShmNode *pShmNode = p->pShmNode;
3588 int rc = SQLITE_OK;
3589
dan18801912010-06-14 14:07:50 +00003590 sqlite3_mutex_enter(pShmNode->mutex);
3591 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
dan13a3cb82010-06-11 19:04:21 +00003592
dan18801912010-06-14 14:07:50 +00003593 if( pShmNode->nRegion<=iRegion ){
3594 char **apNew; /* New apRegion[] array */
3595 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3596 struct stat sStat; /* Used by fstat() */
dan13a3cb82010-06-11 19:04:21 +00003597
dan18801912010-06-14 14:07:50 +00003598 pShmNode->szRegion = szRegion;
dan13a3cb82010-06-11 19:04:21 +00003599
dan18801912010-06-14 14:07:50 +00003600 /* The requested region is not mapped into this processes address space.
3601 ** Check to see if it has been allocated (i.e. if the wal-index file is
3602 ** large enough to contain the requested region).
3603 */
dan13a3cb82010-06-11 19:04:21 +00003604 if( fstat(pShmNode->h, &sStat) ){
3605 rc = SQLITE_IOERR_SHMSIZE;
3606 goto shmpage_out;
dan18801912010-06-14 14:07:50 +00003607 }
3608
3609 if( sStat.st_size<nByte ){
3610 /* The requested memory region does not exist. If isWrite is set to
3611 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
3612 **
3613 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
3614 ** the requested memory region.
3615 */
dan13a3cb82010-06-11 19:04:21 +00003616 if( !isWrite ) goto shmpage_out;
3617 if( ftruncate(pShmNode->h, nByte) ){
3618 rc = SQLITE_IOERR_SHMSIZE;
3619 goto shmpage_out;
3620 }
3621 }
3622
dan18801912010-06-14 14:07:50 +00003623 /* Map the requested memory region into this processes address space. */
3624 apNew = (char **)sqlite3_realloc(
3625 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3626 );
dan13a3cb82010-06-11 19:04:21 +00003627 if( !apNew ){
3628 rc = SQLITE_IOERR_NOMEM;
3629 goto shmpage_out;
3630 }
dan18801912010-06-14 14:07:50 +00003631 pShmNode->apRegion = apNew;
3632 while(pShmNode->nRegion<=iRegion){
3633 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3634 MAP_SHARED, pShmNode->h, iRegion*szRegion
dan13a3cb82010-06-11 19:04:21 +00003635 );
3636 if( pMem==MAP_FAILED ){
dan13a3cb82010-06-11 19:04:21 +00003637 rc = SQLITE_IOERR;
3638 goto shmpage_out;
3639 }
dan18801912010-06-14 14:07:50 +00003640 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3641 pShmNode->nRegion++;
dan13a3cb82010-06-11 19:04:21 +00003642 }
3643 }
3644
3645shmpage_out:
dan18801912010-06-14 14:07:50 +00003646 if( pShmNode->nRegion>iRegion ){
3647 *pp = pShmNode->apRegion[iRegion];
dan13a3cb82010-06-11 19:04:21 +00003648 }else{
3649 *pp = 0;
3650 }
dan18801912010-06-14 14:07:50 +00003651 sqlite3_mutex_leave(pShmNode->mutex);
dan13a3cb82010-06-11 19:04:21 +00003652 return rc;
3653}
drh286a2882010-05-20 23:51:06 +00003654
drhd9e5c4f2010-05-12 18:01:39 +00003655#else
3656# define unixShmOpen 0
drhd9e5c4f2010-05-12 18:01:39 +00003657# define unixShmLock 0
drh6b017cc2010-06-14 18:01:46 +00003658# define unixShmMap 0
drh286a2882010-05-20 23:51:06 +00003659# define unixShmBarrier 0
drhd9e5c4f2010-05-12 18:01:39 +00003660# define unixShmClose 0
3661#endif /* #ifndef SQLITE_OMIT_WAL */
3662
drh734c9862008-11-28 15:37:20 +00003663/*
3664** Here ends the implementation of all sqlite3_file methods.
3665**
3666********************** End sqlite3_file Methods *******************************
3667******************************************************************************/
3668
3669/*
drh6b9d6dd2008-12-03 19:34:47 +00003670** This division contains definitions of sqlite3_io_methods objects that
3671** implement various file locking strategies. It also contains definitions
3672** of "finder" functions. A finder-function is used to locate the appropriate
3673** sqlite3_io_methods object for a particular database file. The pAppData
3674** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3675** the correct finder-function for that VFS.
3676**
3677** Most finder functions return a pointer to a fixed sqlite3_io_methods
3678** object. The only interesting finder-function is autolockIoFinder, which
3679** looks at the filesystem type and tries to guess the best locking
3680** strategy from that.
3681**
drh1875f7a2008-12-08 18:19:17 +00003682** For finder-funtion F, two objects are created:
3683**
3684** (1) The real finder-function named "FImpt()".
3685**
dane946c392009-08-22 11:39:46 +00003686** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003687**
3688**
3689** A pointer to the F pointer is used as the pAppData value for VFS
3690** objects. We have to do this instead of letting pAppData point
3691** directly at the finder-function since C90 rules prevent a void*
3692** from be cast into a function pointer.
3693**
drh6b9d6dd2008-12-03 19:34:47 +00003694**
drh7708e972008-11-29 00:56:52 +00003695** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003696**
drh7708e972008-11-29 00:56:52 +00003697** * A constant sqlite3_io_methods object call METHOD that has locking
3698** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3699**
3700** * An I/O method finder function called FINDER that returns a pointer
3701** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003702*/
drhd9e5c4f2010-05-12 18:01:39 +00003703#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003704static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003705 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003706 CLOSE, /* xClose */ \
3707 unixRead, /* xRead */ \
3708 unixWrite, /* xWrite */ \
3709 unixTruncate, /* xTruncate */ \
3710 unixSync, /* xSync */ \
3711 unixFileSize, /* xFileSize */ \
3712 LOCK, /* xLock */ \
3713 UNLOCK, /* xUnlock */ \
3714 CKLOCK, /* xCheckReservedLock */ \
3715 unixFileControl, /* xFileControl */ \
3716 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003717 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
3718 unixShmOpen, /* xShmOpen */ \
drhd9e5c4f2010-05-12 18:01:39 +00003719 unixShmLock, /* xShmLock */ \
drh6b017cc2010-06-14 18:01:46 +00003720 unixShmMap, /* xShmMap */ \
drh286a2882010-05-20 23:51:06 +00003721 unixShmBarrier, /* xShmBarrier */ \
drh6b017cc2010-06-14 18:01:46 +00003722 unixShmClose /* xShmClose */ \
drh7708e972008-11-29 00:56:52 +00003723}; \
drh0c2694b2009-09-03 16:23:44 +00003724static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3725 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003726 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003727} \
drh0c2694b2009-09-03 16:23:44 +00003728static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003729 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003730
3731/*
3732** Here are all of the sqlite3_io_methods objects for each of the
3733** locking strategies. Functions that return pointers to these methods
3734** are also created.
3735*/
3736IOMETHODS(
3737 posixIoFinder, /* Finder function name */
3738 posixIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003739 2, /* ShmOpen is enabled */
drh7708e972008-11-29 00:56:52 +00003740 unixClose, /* xClose method */
3741 unixLock, /* xLock method */
3742 unixUnlock, /* xUnlock method */
3743 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003744)
drh7708e972008-11-29 00:56:52 +00003745IOMETHODS(
3746 nolockIoFinder, /* Finder function name */
3747 nolockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003748 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003749 nolockClose, /* xClose method */
3750 nolockLock, /* xLock method */
3751 nolockUnlock, /* xUnlock method */
3752 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003753)
drh7708e972008-11-29 00:56:52 +00003754IOMETHODS(
3755 dotlockIoFinder, /* Finder function name */
3756 dotlockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003757 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003758 dotlockClose, /* xClose method */
3759 dotlockLock, /* xLock method */
3760 dotlockUnlock, /* xUnlock method */
3761 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003762)
drh7708e972008-11-29 00:56:52 +00003763
chw78a13182009-04-07 05:35:03 +00003764#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003765IOMETHODS(
3766 flockIoFinder, /* Finder function name */
3767 flockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003768 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003769 flockClose, /* xClose method */
3770 flockLock, /* xLock method */
3771 flockUnlock, /* xUnlock method */
3772 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003773)
drh7708e972008-11-29 00:56:52 +00003774#endif
3775
drh6c7d5c52008-11-21 20:32:33 +00003776#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003777IOMETHODS(
3778 semIoFinder, /* Finder function name */
3779 semIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003780 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003781 semClose, /* xClose method */
3782 semLock, /* xLock method */
3783 semUnlock, /* xUnlock method */
3784 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003785)
aswiftaebf4132008-11-21 00:10:35 +00003786#endif
drh7708e972008-11-29 00:56:52 +00003787
drhd2cb50b2009-01-09 21:41:17 +00003788#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003789IOMETHODS(
3790 afpIoFinder, /* Finder function name */
3791 afpIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003792 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003793 afpClose, /* xClose method */
3794 afpLock, /* xLock method */
3795 afpUnlock, /* xUnlock method */
3796 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003797)
drh715ff302008-12-03 22:32:44 +00003798#endif
3799
3800/*
3801** The proxy locking method is a "super-method" in the sense that it
3802** opens secondary file descriptors for the conch and lock files and
3803** it uses proxy, dot-file, AFP, and flock() locking methods on those
3804** secondary files. For this reason, the division that implements
3805** proxy locking is located much further down in the file. But we need
3806** to go ahead and define the sqlite3_io_methods and finder function
3807** for proxy locking here. So we forward declare the I/O methods.
3808*/
drhd2cb50b2009-01-09 21:41:17 +00003809#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003810static int proxyClose(sqlite3_file*);
3811static int proxyLock(sqlite3_file*, int);
3812static int proxyUnlock(sqlite3_file*, int);
3813static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003814IOMETHODS(
3815 proxyIoFinder, /* Finder function name */
3816 proxyIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003817 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003818 proxyClose, /* xClose method */
3819 proxyLock, /* xLock method */
3820 proxyUnlock, /* xUnlock method */
3821 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003822)
aswiftaebf4132008-11-21 00:10:35 +00003823#endif
drh7708e972008-11-29 00:56:52 +00003824
drh7ed97b92010-01-20 13:07:21 +00003825/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3826#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3827IOMETHODS(
3828 nfsIoFinder, /* Finder function name */
3829 nfsIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003830 1, /* ShmOpen is disabled */
drh7ed97b92010-01-20 13:07:21 +00003831 unixClose, /* xClose method */
3832 unixLock, /* xLock method */
3833 nfsUnlock, /* xUnlock method */
3834 unixCheckReservedLock /* xCheckReservedLock method */
3835)
3836#endif
drh7708e972008-11-29 00:56:52 +00003837
drhd2cb50b2009-01-09 21:41:17 +00003838#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003839/*
drh6b9d6dd2008-12-03 19:34:47 +00003840** This "finder" function attempts to determine the best locking strategy
3841** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003842** object that implements that strategy.
3843**
3844** This is for MacOSX only.
3845*/
drh1875f7a2008-12-08 18:19:17 +00003846static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003847 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003848 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003849){
3850 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003851 const char *zFilesystem; /* Filesystem type name */
3852 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003853 } aMap[] = {
3854 { "hfs", &posixIoMethods },
3855 { "ufs", &posixIoMethods },
3856 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003857 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003858 { "webdav", &nolockIoMethods },
3859 { 0, 0 }
3860 };
3861 int i;
3862 struct statfs fsInfo;
3863 struct flock lockInfo;
3864
3865 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003866 /* If filePath==NULL that means we are dealing with a transient file
3867 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003868 return &nolockIoMethods;
3869 }
3870 if( statfs(filePath, &fsInfo) != -1 ){
3871 if( fsInfo.f_flags & MNT_RDONLY ){
3872 return &nolockIoMethods;
3873 }
3874 for(i=0; aMap[i].zFilesystem; i++){
3875 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3876 return aMap[i].pMethods;
3877 }
3878 }
3879 }
3880
3881 /* Default case. Handles, amongst others, "nfs".
3882 ** Test byte-range lock using fcntl(). If the call succeeds,
3883 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003884 */
drh7708e972008-11-29 00:56:52 +00003885 lockInfo.l_len = 1;
3886 lockInfo.l_start = 0;
3887 lockInfo.l_whence = SEEK_SET;
3888 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003889 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003890 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3891 return &nfsIoMethods;
3892 } else {
3893 return &posixIoMethods;
3894 }
drh7708e972008-11-29 00:56:52 +00003895 }else{
3896 return &dotlockIoMethods;
3897 }
3898}
drh0c2694b2009-09-03 16:23:44 +00003899static const sqlite3_io_methods
3900 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003901
drhd2cb50b2009-01-09 21:41:17 +00003902#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003903
chw78a13182009-04-07 05:35:03 +00003904#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3905/*
3906** This "finder" function attempts to determine the best locking strategy
3907** for the database file "filePath". It then returns the sqlite3_io_methods
3908** object that implements that strategy.
3909**
3910** This is for VXWorks only.
3911*/
3912static const sqlite3_io_methods *autolockIoFinderImpl(
3913 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003914 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003915){
3916 struct flock lockInfo;
3917
3918 if( !filePath ){
3919 /* If filePath==NULL that means we are dealing with a transient file
3920 ** that does not need to be locked. */
3921 return &nolockIoMethods;
3922 }
3923
3924 /* Test if fcntl() is supported and use POSIX style locks.
3925 ** Otherwise fall back to the named semaphore method.
3926 */
3927 lockInfo.l_len = 1;
3928 lockInfo.l_start = 0;
3929 lockInfo.l_whence = SEEK_SET;
3930 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003931 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003932 return &posixIoMethods;
3933 }else{
3934 return &semIoMethods;
3935 }
3936}
drh0c2694b2009-09-03 16:23:44 +00003937static const sqlite3_io_methods
3938 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003939
3940#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3941
drh7708e972008-11-29 00:56:52 +00003942/*
3943** An abstract type for a pointer to a IO method finder function:
3944*/
drh0c2694b2009-09-03 16:23:44 +00003945typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003946
aswiftaebf4132008-11-21 00:10:35 +00003947
drh734c9862008-11-28 15:37:20 +00003948/****************************************************************************
3949**************************** sqlite3_vfs methods ****************************
3950**
3951** This division contains the implementation of methods on the
3952** sqlite3_vfs object.
3953*/
3954
danielk1977a3d4c882007-03-23 10:08:38 +00003955/*
danielk1977e339d652008-06-28 11:23:00 +00003956** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003957*/
3958static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003959 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003960 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003961 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003962 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003963 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003964 int noLock, /* Omit locking if true */
3965 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003966){
drh7708e972008-11-29 00:56:52 +00003967 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003968 unixFile *pNew = (unixFile *)pId;
3969 int rc = SQLITE_OK;
3970
drh8af6c222010-05-14 12:43:01 +00003971 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00003972
dane946c392009-08-22 11:39:46 +00003973 /* Parameter isDelete is only used on vxworks. Express this explicitly
3974 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003975 */
drh7708e972008-11-29 00:56:52 +00003976 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003977
drh308c2a52010-05-14 11:30:18 +00003978 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00003979 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003980 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00003981 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00003982 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
3983 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00003984
drh6c7d5c52008-11-21 20:32:33 +00003985#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003986 pNew->pId = vxworksFindFileId(zFilename);
3987 if( pNew->pId==0 ){
3988 noLock = 1;
3989 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003990 }
3991#endif
3992
drhda0e7682008-07-30 15:27:54 +00003993 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003994 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003995 }else{
drh0c2694b2009-09-03 16:23:44 +00003996 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003997#if SQLITE_ENABLE_LOCKING_STYLE
3998 /* Cache zFilename in the locking context (AFP and dotlock override) for
3999 ** proxyLock activation is possible (remote proxy is based on db name)
4000 ** zFilename remains valid until file is closed, to support */
4001 pNew->lockingContext = (void*)zFilename;
4002#endif
drhda0e7682008-07-30 15:27:54 +00004003 }
danielk1977e339d652008-06-28 11:23:00 +00004004
drh7ed97b92010-01-20 13:07:21 +00004005 if( pLockingStyle == &posixIoMethods
4006#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4007 || pLockingStyle == &nfsIoMethods
4008#endif
4009 ){
drh7708e972008-11-29 00:56:52 +00004010 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004011 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004012 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004013 /* If an error occured in findInodeInfo(), close the file descriptor
4014 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004015 ** in two scenarios:
4016 **
4017 ** (a) A call to fstat() failed.
4018 ** (b) A malloc failed.
4019 **
4020 ** Scenario (b) may only occur if the process is holding no other
4021 ** file descriptors open on the same file. If there were other file
4022 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004023 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004024 ** handle h - as it is guaranteed that no posix locks will be released
4025 ** by doing so.
4026 **
4027 ** If scenario (a) caused the error then things are not so safe. The
4028 ** implicit assumption here is that if fstat() fails, things are in
4029 ** such bad shape that dropping a lock or two doesn't matter much.
4030 */
4031 close(h);
4032 h = -1;
4033 }
drh7708e972008-11-29 00:56:52 +00004034 unixLeaveMutex();
4035 }
danielk1977e339d652008-06-28 11:23:00 +00004036
drhd2cb50b2009-01-09 21:41:17 +00004037#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004038 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004039 /* AFP locking uses the file path so it needs to be included in
4040 ** the afpLockingContext.
4041 */
4042 afpLockingContext *pCtx;
4043 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4044 if( pCtx==0 ){
4045 rc = SQLITE_NOMEM;
4046 }else{
4047 /* NB: zFilename exists and remains valid until the file is closed
4048 ** according to requirement F11141. So we do not need to make a
4049 ** copy of the filename. */
4050 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004051 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004052 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004053 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004054 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004055 if( rc!=SQLITE_OK ){
4056 sqlite3_free(pNew->lockingContext);
4057 close(h);
4058 h = -1;
4059 }
drh7708e972008-11-29 00:56:52 +00004060 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004061 }
drh7708e972008-11-29 00:56:52 +00004062 }
4063#endif
danielk1977e339d652008-06-28 11:23:00 +00004064
drh7708e972008-11-29 00:56:52 +00004065 else if( pLockingStyle == &dotlockIoMethods ){
4066 /* Dotfile locking uses the file path so it needs to be included in
4067 ** the dotlockLockingContext
4068 */
4069 char *zLockFile;
4070 int nFilename;
drhea678832008-12-10 19:26:22 +00004071 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004072 zLockFile = (char *)sqlite3_malloc(nFilename);
4073 if( zLockFile==0 ){
4074 rc = SQLITE_NOMEM;
4075 }else{
4076 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004077 }
drh7708e972008-11-29 00:56:52 +00004078 pNew->lockingContext = zLockFile;
4079 }
danielk1977e339d652008-06-28 11:23:00 +00004080
drh6c7d5c52008-11-21 20:32:33 +00004081#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004082 else if( pLockingStyle == &semIoMethods ){
4083 /* Named semaphore locking uses the file path so it needs to be
4084 ** included in the semLockingContext
4085 */
4086 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004087 rc = findInodeInfo(pNew, &pNew->pInode);
4088 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4089 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004090 int n;
drh2238dcc2009-08-27 17:56:20 +00004091 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004092 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004093 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004094 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004095 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4096 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004097 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004098 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004099 }
chw97185482008-11-17 08:05:31 +00004100 }
drh7708e972008-11-29 00:56:52 +00004101 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004102 }
drh7708e972008-11-29 00:56:52 +00004103#endif
aswift5b1a2562008-08-22 00:22:35 +00004104
4105 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004106#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004107 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004108 if( h>=0 ) close(h);
4109 h = -1;
chw97185482008-11-17 08:05:31 +00004110 unlink(zFilename);
4111 isDelete = 0;
4112 }
4113 pNew->isDelete = isDelete;
4114#endif
danielk1977e339d652008-06-28 11:23:00 +00004115 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004116 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004117 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004118 }else{
drh7708e972008-11-29 00:56:52 +00004119 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004120 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004121 }
danielk1977e339d652008-06-28 11:23:00 +00004122 return rc;
drh054889e2005-11-30 03:20:31 +00004123}
drh9c06c952005-11-26 00:25:00 +00004124
danielk1977ad94b582007-08-20 06:44:22 +00004125/*
4126** Open a file descriptor to the directory containing file zFilename.
4127** If successful, *pFd is set to the opened file descriptor and
4128** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4129** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4130** value.
4131**
4132** If SQLITE_OK is returned, the caller is responsible for closing
4133** the file descriptor *pFd using close().
4134*/
danielk1977fee2d252007-08-18 10:59:19 +00004135static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004136 int ii;
drh777b17a2007-09-20 10:02:54 +00004137 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004138 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004139
drh153c62c2007-08-24 03:51:33 +00004140 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004141 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004142 if( ii>0 ){
4143 zDirname[ii] = '\0';
4144 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004145 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004146#ifdef FD_CLOEXEC
4147 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4148#endif
drh308c2a52010-05-14 11:30:18 +00004149 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004150 }
4151 }
danielk1977fee2d252007-08-18 10:59:19 +00004152 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004153 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004154}
4155
danielk1977b4b47412007-08-17 15:53:36 +00004156/*
drh8b3cf822010-06-01 21:02:51 +00004157** Return the name of a directory in which to put temporary files.
4158** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004159*/
drh8b3cf822010-06-01 21:02:51 +00004160static const char *unixTempFileDir(int allowShm){
danielk197717b90b52008-06-06 11:11:25 +00004161 static const char *azDirs[] = {
4162 0,
aswiftaebf4132008-11-21 00:10:35 +00004163 0,
danielk197717b90b52008-06-06 11:11:25 +00004164 "/var/tmp",
4165 "/usr/tmp",
4166 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004167 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004168 };
drh8b3cf822010-06-01 21:02:51 +00004169 unsigned int i;
4170 struct stat buf;
4171 const char *zDir = 0;
4172
4173 azDirs[0] = sqlite3_temp_directory;
4174 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
4175
4176 if( allowShm ){
4177 zDir = "/dev/shm";
drhc11895b2010-06-02 15:59:05 +00004178 i = 2; /* Skip the app-defined temp locations for shared-memory */
drh8b3cf822010-06-01 21:02:51 +00004179 }else{
4180 zDir = azDirs[0];
4181 i = 1;
4182 }
4183 for(; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
4184 if( zDir==0 ) continue;
4185 if( stat(zDir, &buf) ) continue;
4186 if( !S_ISDIR(buf.st_mode) ) continue;
drhc11895b2010-06-02 15:59:05 +00004187 if( !allowShm && access(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004188 break;
4189 }
4190 return zDir;
4191}
4192
4193/*
4194** Create a temporary file name in zBuf. zBuf must be allocated
4195** by the calling process and must be big enough to hold at least
4196** pVfs->mxPathname bytes.
4197*/
4198static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004199 static const unsigned char zChars[] =
4200 "abcdefghijklmnopqrstuvwxyz"
4201 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4202 "0123456789";
drh41022642008-11-21 00:24:42 +00004203 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004204 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004205
4206 /* It's odd to simulate an io-error here, but really this is just
4207 ** using the io-error infrastructure to test that SQLite handles this
4208 ** function failing.
4209 */
4210 SimulateIOError( return SQLITE_IOERR );
4211
drh8b3cf822010-06-01 21:02:51 +00004212 zDir = unixTempFileDir(0);
4213 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004214
4215 /* Check that the output buffer is large enough for the temporary file
4216 ** name. If it is not, return SQLITE_ERROR.
4217 */
danielk197700e13612008-11-17 19:18:54 +00004218 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004219 return SQLITE_ERROR;
4220 }
4221
4222 do{
4223 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004224 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004225 sqlite3_randomness(15, &zBuf[j]);
4226 for(i=0; i<15; i++, j++){
4227 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4228 }
4229 zBuf[j] = 0;
4230 }while( access(zBuf,0)==0 );
4231 return SQLITE_OK;
4232}
4233
drhd2cb50b2009-01-09 21:41:17 +00004234#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004235/*
4236** Routine to transform a unixFile into a proxy-locking unixFile.
4237** Implementation in the proxy-lock division, but used by unixOpen()
4238** if SQLITE_PREFER_PROXY_LOCKING is defined.
4239*/
4240static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004241#endif
drhc66d5b62008-12-03 22:48:32 +00004242
dan08da86a2009-08-21 17:18:03 +00004243/*
4244** Search for an unused file descriptor that was opened on the database
4245** file (not a journal or master-journal file) identified by pathname
4246** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4247** argument to this function.
4248**
4249** Such a file descriptor may exist if a database connection was closed
4250** but the associated file descriptor could not be closed because some
4251** other file descriptor open on the same file is holding a file-lock.
4252** Refer to comments in the unixClose() function and the lengthy comment
4253** describing "Posix Advisory Locking" at the start of this file for
4254** further details. Also, ticket #4018.
4255**
4256** If a suitable file descriptor is found, then it is returned. If no
4257** such file descriptor is located, -1 is returned.
4258*/
dane946c392009-08-22 11:39:46 +00004259static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4260 UnixUnusedFd *pUnused = 0;
4261
4262 /* Do not search for an unused file descriptor on vxworks. Not because
4263 ** vxworks would not benefit from the change (it might, we're not sure),
4264 ** but because no way to test it is currently available. It is better
4265 ** not to risk breaking vxworks support for the sake of such an obscure
4266 ** feature. */
4267#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004268 struct stat sStat; /* Results of stat() call */
4269
4270 /* A stat() call may fail for various reasons. If this happens, it is
4271 ** almost certain that an open() call on the same path will also fail.
4272 ** For this reason, if an error occurs in the stat() call here, it is
4273 ** ignored and -1 is returned. The caller will try to open a new file
4274 ** descriptor on the same path, fail, and return an error to SQLite.
4275 **
4276 ** Even if a subsequent open() call does succeed, the consequences of
4277 ** not searching for a resusable file descriptor are not dire. */
4278 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004279 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004280
4281 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004282 pInode = inodeList;
4283 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4284 || pInode->fileId.ino!=sStat.st_ino) ){
4285 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004286 }
drh8af6c222010-05-14 12:43:01 +00004287 if( pInode ){
dane946c392009-08-22 11:39:46 +00004288 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004289 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004290 pUnused = *pp;
4291 if( pUnused ){
4292 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004293 }
4294 }
4295 unixLeaveMutex();
4296 }
dane946c392009-08-22 11:39:46 +00004297#endif /* if !OS_VXWORKS */
4298 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004299}
danielk197717b90b52008-06-06 11:11:25 +00004300
4301/*
danielk1977ad94b582007-08-20 06:44:22 +00004302** Open the file zPath.
4303**
danielk1977b4b47412007-08-17 15:53:36 +00004304** Previously, the SQLite OS layer used three functions in place of this
4305** one:
4306**
4307** sqlite3OsOpenReadWrite();
4308** sqlite3OsOpenReadOnly();
4309** sqlite3OsOpenExclusive();
4310**
4311** These calls correspond to the following combinations of flags:
4312**
4313** ReadWrite() -> (READWRITE | CREATE)
4314** ReadOnly() -> (READONLY)
4315** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4316**
4317** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4318** true, the file was configured to be automatically deleted when the
4319** file handle closed. To achieve the same effect using this new
4320** interface, add the DELETEONCLOSE flag to those specified above for
4321** OpenExclusive().
4322*/
4323static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004324 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4325 const char *zPath, /* Pathname of file to be opened */
4326 sqlite3_file *pFile, /* The file descriptor to be filled in */
4327 int flags, /* Input flags to control the opening */
4328 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004329){
dan08da86a2009-08-21 17:18:03 +00004330 unixFile *p = (unixFile *)pFile;
4331 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004332 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004333 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004334 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004335 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004336 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004337
4338 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4339 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4340 int isCreate = (flags & SQLITE_OPEN_CREATE);
4341 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4342 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004343#if SQLITE_ENABLE_LOCKING_STYLE
4344 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4345#endif
danielk1977b4b47412007-08-17 15:53:36 +00004346
danielk1977fee2d252007-08-18 10:59:19 +00004347 /* If creating a master or main-file journal, this function will open
4348 ** a file-descriptor on the directory too. The first time unixSync()
4349 ** is called the directory file descriptor will be fsync()ed and close()d.
4350 */
4351 int isOpenDirectory = (isCreate &&
4352 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4353 );
4354
danielk197717b90b52008-06-06 11:11:25 +00004355 /* If argument zPath is a NULL pointer, this function is required to open
4356 ** a temporary file. Use this buffer to store the file name in.
4357 */
4358 char zTmpname[MAX_PATHNAME+1];
4359 const char *zName = zPath;
4360
danielk1977fee2d252007-08-18 10:59:19 +00004361 /* Check the following statements are true:
4362 **
4363 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4364 ** (b) if CREATE is set, then READWRITE must also be set, and
4365 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004366 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004367 */
danielk1977b4b47412007-08-17 15:53:36 +00004368 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004369 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004370 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004371 assert(isDelete==0 || isCreate);
4372
drh33f4e022007-09-03 15:19:34 +00004373 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004374 ** deleted. Nor are they ever temporary files. */
4375 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4376 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4377 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004378
danielk1977fee2d252007-08-18 10:59:19 +00004379 /* Assert that the upper layer has set one of the "file-type" flags. */
4380 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4381 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4382 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004383 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004384 );
4385
dan08da86a2009-08-21 17:18:03 +00004386 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004387
dan08da86a2009-08-21 17:18:03 +00004388 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004389 UnixUnusedFd *pUnused;
4390 pUnused = findReusableFd(zName, flags);
4391 if( pUnused ){
4392 fd = pUnused->fd;
4393 }else{
dan6aa657f2009-08-24 18:57:58 +00004394 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004395 if( !pUnused ){
4396 return SQLITE_NOMEM;
4397 }
4398 }
4399 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004400 }else if( !zName ){
4401 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004402 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004403 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004404 if( rc!=SQLITE_OK ){
4405 return rc;
4406 }
4407 zName = zTmpname;
4408 }
4409
dan08da86a2009-08-21 17:18:03 +00004410 /* Determine the value of the flags parameter passed to POSIX function
4411 ** open(). These must be calculated even if open() is not called, as
4412 ** they may be stored as part of the file handle and used by the
4413 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004414 if( isReadonly ) openFlags |= O_RDONLY;
4415 if( isReadWrite ) openFlags |= O_RDWR;
4416 if( isCreate ) openFlags |= O_CREAT;
4417 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4418 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004419
danielk1977b4b47412007-08-17 15:53:36 +00004420 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004421 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4422 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004423 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004424 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4425 /* Failed to open the file for read/write access. Try read-only. */
4426 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004427 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004428 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004429 openFlags |= O_RDONLY;
4430 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004431 }
4432 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004433 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004434 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004435 }
danielk1977b4b47412007-08-17 15:53:36 +00004436 }
dan08da86a2009-08-21 17:18:03 +00004437 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004438 if( pOutFlags ){
4439 *pOutFlags = flags;
4440 }
4441
dane946c392009-08-22 11:39:46 +00004442 if( p->pUnused ){
4443 p->pUnused->fd = fd;
4444 p->pUnused->flags = flags;
4445 }
4446
danielk1977b4b47412007-08-17 15:53:36 +00004447 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004448#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004449 zPath = zName;
4450#else
danielk197717b90b52008-06-06 11:11:25 +00004451 unlink(zName);
chw97185482008-11-17 08:05:31 +00004452#endif
danielk1977b4b47412007-08-17 15:53:36 +00004453 }
drh41022642008-11-21 00:24:42 +00004454#if SQLITE_ENABLE_LOCKING_STYLE
4455 else{
dan08da86a2009-08-21 17:18:03 +00004456 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004457 }
4458#endif
4459
danielk1977fee2d252007-08-18 10:59:19 +00004460 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004461 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004462 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004463 /* It is safe to close fd at this point, because it is guaranteed not
4464 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004465 ** it would not be safe to close as this would release any locks held
4466 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004467 assert( eType!=SQLITE_OPEN_MAIN_DB );
4468 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004469 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004470 }
4471 }
danielk1977e339d652008-06-28 11:23:00 +00004472
4473#ifdef FD_CLOEXEC
4474 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4475#endif
4476
drhda0e7682008-07-30 15:27:54 +00004477 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004478
drh7ed97b92010-01-20 13:07:21 +00004479
4480#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4481 struct statfs fsInfo;
4482 if( fstatfs(fd, &fsInfo) == -1 ){
4483 ((unixFile*)pFile)->lastErrno = errno;
4484 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4485 close(fd); /* silently leak if fail, in error */
4486 return SQLITE_IOERR_ACCESS;
4487 }
4488 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4489 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4490 }
4491#endif
4492
4493#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004494#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004495 isAutoProxy = 1;
4496#endif
4497 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004498 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4499 int useProxy = 0;
4500
dan08da86a2009-08-21 17:18:03 +00004501 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4502 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004503 if( envforce!=NULL ){
4504 useProxy = atoi(envforce)>0;
4505 }else{
4506 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004507 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004508 /* In theory, the close(fd) call is sub-optimal. If the file opened
4509 ** with fd is a database file, and there are other connections open
4510 ** on that file that are currently holding advisory locks on it,
4511 ** then the call to close() will cancel those locks. In practice,
4512 ** we're assuming that statfs() doesn't fail very often. At least
4513 ** not while other file descriptors opened by the same process on
4514 ** the same file are working. */
4515 p->lastErrno = errno;
4516 if( dirfd>=0 ){
4517 close(dirfd); /* silently leak if fail, in error */
4518 }
aswiftaebf4132008-11-21 00:10:35 +00004519 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004520 rc = SQLITE_IOERR_ACCESS;
4521 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004522 }
4523 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4524 }
4525 if( useProxy ){
4526 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4527 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004528 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004529 if( rc!=SQLITE_OK ){
4530 /* Use unixClose to clean up the resources added in fillInUnixFile
4531 ** and clear all the structure's references. Specifically,
4532 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4533 */
4534 unixClose(pFile);
4535 return rc;
4536 }
aswiftaebf4132008-11-21 00:10:35 +00004537 }
dane946c392009-08-22 11:39:46 +00004538 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004539 }
4540 }
4541#endif
4542
dane946c392009-08-22 11:39:46 +00004543 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4544open_finished:
4545 if( rc!=SQLITE_OK ){
4546 sqlite3_free(p->pUnused);
4547 }
4548 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004549}
4550
dane946c392009-08-22 11:39:46 +00004551
danielk1977b4b47412007-08-17 15:53:36 +00004552/*
danielk1977fee2d252007-08-18 10:59:19 +00004553** Delete the file at zPath. If the dirSync argument is true, fsync()
4554** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004555*/
drh6b9d6dd2008-12-03 19:34:47 +00004556static int unixDelete(
4557 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4558 const char *zPath, /* Name of file to be deleted */
4559 int dirSync /* If true, fsync() directory after deleting file */
4560){
danielk1977fee2d252007-08-18 10:59:19 +00004561 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004562 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004563 SimulateIOError(return SQLITE_IOERR_DELETE);
4564 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004565#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004566 if( dirSync ){
4567 int fd;
4568 rc = openDirectory(zPath, &fd);
4569 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004570#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004571 if( fsync(fd)==-1 )
4572#else
4573 if( fsync(fd) )
4574#endif
4575 {
danielk1977fee2d252007-08-18 10:59:19 +00004576 rc = SQLITE_IOERR_DIR_FSYNC;
4577 }
aswiftaebf4132008-11-21 00:10:35 +00004578 if( close(fd)&&!rc ){
4579 rc = SQLITE_IOERR_DIR_CLOSE;
4580 }
danielk1977fee2d252007-08-18 10:59:19 +00004581 }
4582 }
danielk1977d138dd82008-10-15 16:02:48 +00004583#endif
danielk1977fee2d252007-08-18 10:59:19 +00004584 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004585}
4586
danielk197790949c22007-08-17 16:50:38 +00004587/*
4588** Test the existance of or access permissions of file zPath. The
4589** test performed depends on the value of flags:
4590**
4591** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4592** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4593** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4594**
4595** Otherwise return 0.
4596*/
danielk1977861f7452008-06-05 11:39:11 +00004597static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004598 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4599 const char *zPath, /* Path of the file to examine */
4600 int flags, /* What do we want to learn about the zPath file? */
4601 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004602){
rse25c0d1a2007-09-20 08:38:14 +00004603 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004604 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004605 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004606 switch( flags ){
4607 case SQLITE_ACCESS_EXISTS:
4608 amode = F_OK;
4609 break;
4610 case SQLITE_ACCESS_READWRITE:
4611 amode = W_OK|R_OK;
4612 break;
drh50d3f902007-08-27 21:10:36 +00004613 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004614 amode = R_OK;
4615 break;
4616
4617 default:
4618 assert(!"Invalid flags argument");
4619 }
danielk1977861f7452008-06-05 11:39:11 +00004620 *pResOut = (access(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004621 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4622 struct stat buf;
4623 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4624 *pResOut = 0;
4625 }
4626 }
danielk1977861f7452008-06-05 11:39:11 +00004627 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004628}
4629
danielk1977b4b47412007-08-17 15:53:36 +00004630
4631/*
4632** Turn a relative pathname into a full pathname. The relative path
4633** is stored as a nul-terminated string in the buffer pointed to by
4634** zPath.
4635**
4636** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4637** (in this case, MAX_PATHNAME bytes). The full-path is written to
4638** this buffer before returning.
4639*/
danielk1977adfb9b02007-09-17 07:02:56 +00004640static int unixFullPathname(
4641 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4642 const char *zPath, /* Possibly relative input path */
4643 int nOut, /* Size of output buffer in bytes */
4644 char *zOut /* Output buffer */
4645){
danielk1977843e65f2007-09-01 16:16:15 +00004646
4647 /* It's odd to simulate an io-error here, but really this is just
4648 ** using the io-error infrastructure to test that SQLite handles this
4649 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004650 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004651 */
4652 SimulateIOError( return SQLITE_ERROR );
4653
drh153c62c2007-08-24 03:51:33 +00004654 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004655 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004656
drh3c7f2dc2007-12-06 13:26:20 +00004657 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004658 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004659 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004660 }else{
4661 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004662 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004663 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004664 }
drhea678832008-12-10 19:26:22 +00004665 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004666 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004667 }
4668 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004669}
4670
drh0ccebe72005-06-07 22:22:50 +00004671
drh761df872006-12-21 01:29:22 +00004672#ifndef SQLITE_OMIT_LOAD_EXTENSION
4673/*
4674** Interfaces for opening a shared library, finding entry points
4675** within the shared library, and closing the shared library.
4676*/
4677#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004678static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4679 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004680 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4681}
danielk197795c8a542007-09-01 06:51:27 +00004682
4683/*
4684** SQLite calls this function immediately after a call to unixDlSym() or
4685** unixDlOpen() fails (returns a null pointer). If a more detailed error
4686** message is available, it is written to zBufOut. If no error message
4687** is available, zBufOut is left unmodified and SQLite uses a default
4688** error message.
4689*/
danielk1977397d65f2008-11-19 11:35:39 +00004690static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004691 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004692 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004693 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004694 zErr = dlerror();
4695 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004696 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004697 }
drh6c7d5c52008-11-21 20:32:33 +00004698 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004699}
drh1875f7a2008-12-08 18:19:17 +00004700static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4701 /*
4702 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4703 ** cast into a pointer to a function. And yet the library dlsym() routine
4704 ** returns a void* which is really a pointer to a function. So how do we
4705 ** use dlsym() with -pedantic-errors?
4706 **
4707 ** Variable x below is defined to be a pointer to a function taking
4708 ** parameters void* and const char* and returning a pointer to a function.
4709 ** We initialize x by assigning it a pointer to the dlsym() function.
4710 ** (That assignment requires a cast.) Then we call the function that
4711 ** x points to.
4712 **
4713 ** This work-around is unlikely to work correctly on any system where
4714 ** you really cannot cast a function pointer into void*. But then, on the
4715 ** other hand, dlsym() will not work on such a system either, so we have
4716 ** not really lost anything.
4717 */
4718 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004719 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004720 x = (void(*(*)(void*,const char*))(void))dlsym;
4721 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004722}
danielk1977397d65f2008-11-19 11:35:39 +00004723static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4724 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004725 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004726}
danielk1977b4b47412007-08-17 15:53:36 +00004727#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4728 #define unixDlOpen 0
4729 #define unixDlError 0
4730 #define unixDlSym 0
4731 #define unixDlClose 0
4732#endif
4733
4734/*
danielk197790949c22007-08-17 16:50:38 +00004735** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004736*/
danielk1977397d65f2008-11-19 11:35:39 +00004737static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4738 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004739 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004740
drhbbd42a62004-05-22 17:41:58 +00004741 /* We have to initialize zBuf to prevent valgrind from reporting
4742 ** errors. The reports issued by valgrind are incorrect - we would
4743 ** prefer that the randomness be increased by making use of the
4744 ** uninitialized space in zBuf - but valgrind errors tend to worry
4745 ** some users. Rather than argue, it seems easier just to initialize
4746 ** the whole array and silence valgrind, even if that means less randomness
4747 ** in the random seed.
4748 **
4749 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004750 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004751 ** tests repeatable.
4752 */
danielk1977b4b47412007-08-17 15:53:36 +00004753 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004754#if !defined(SQLITE_TEST)
4755 {
drh842b8642005-01-21 17:53:17 +00004756 int pid, fd;
4757 fd = open("/dev/urandom", O_RDONLY);
4758 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004759 time_t t;
4760 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004761 memcpy(zBuf, &t, sizeof(t));
4762 pid = getpid();
4763 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004764 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004765 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004766 }else{
drh72cbd072008-10-14 17:58:38 +00004767 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004768 close(fd);
4769 }
drhbbd42a62004-05-22 17:41:58 +00004770 }
4771#endif
drh72cbd072008-10-14 17:58:38 +00004772 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004773}
4774
danielk1977b4b47412007-08-17 15:53:36 +00004775
drhbbd42a62004-05-22 17:41:58 +00004776/*
4777** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004778** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004779** The return value is the number of microseconds of sleep actually
4780** requested from the underlying operating system, a number which
4781** might be greater than or equal to the argument, but not less
4782** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004783*/
danielk1977397d65f2008-11-19 11:35:39 +00004784static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004785#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004786 struct timespec sp;
4787
4788 sp.tv_sec = microseconds / 1000000;
4789 sp.tv_nsec = (microseconds % 1000000) * 1000;
4790 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004791 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004792 return microseconds;
4793#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004794 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004795 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004796 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004797#else
danielk1977b4b47412007-08-17 15:53:36 +00004798 int seconds = (microseconds+999999)/1000000;
4799 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004800 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004801 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004802#endif
drh88f474a2006-01-02 20:00:12 +00004803}
4804
4805/*
drh6b9d6dd2008-12-03 19:34:47 +00004806** The following variable, if set to a non-zero value, is interpreted as
4807** the number of seconds since 1970 and is used to set the result of
4808** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004809*/
4810#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004811int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004812#endif
4813
4814/*
drhb7e8ea22010-05-03 14:32:30 +00004815** Find the current time (in Universal Coordinated Time). Write into *piNow
4816** the current time and date as a Julian Day number times 86_400_000. In
4817** other words, write into *piNow the number of milliseconds since the Julian
4818** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4819** proleptic Gregorian calendar.
4820**
4821** On success, return 0. Return 1 if the time and date cannot be found.
4822*/
4823static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
4824 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
4825#if defined(NO_GETTOD)
4826 time_t t;
4827 time(&t);
4828 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
4829#elif OS_VXWORKS
4830 struct timespec sNow;
4831 clock_gettime(CLOCK_REALTIME, &sNow);
4832 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
4833#else
4834 struct timeval sNow;
4835 gettimeofday(&sNow, 0);
4836 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
4837#endif
4838
4839#ifdef SQLITE_TEST
4840 if( sqlite3_current_time ){
4841 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
4842 }
4843#endif
4844 UNUSED_PARAMETER(NotUsed);
4845 return 0;
4846}
4847
4848/*
drhbbd42a62004-05-22 17:41:58 +00004849** Find the current time (in Universal Coordinated Time). Write the
4850** current time and date as a Julian Day number into *prNow and
4851** return 0. Return 1 if the time and date cannot be found.
4852*/
danielk1977397d65f2008-11-19 11:35:39 +00004853static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00004854 sqlite3_int64 i;
4855 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00004856 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00004857 return 0;
4858}
danielk1977b4b47412007-08-17 15:53:36 +00004859
drh6b9d6dd2008-12-03 19:34:47 +00004860/*
4861** We added the xGetLastError() method with the intention of providing
4862** better low-level error messages when operating-system problems come up
4863** during SQLite operation. But so far, none of that has been implemented
4864** in the core. So this routine is never called. For now, it is merely
4865** a place-holder.
4866*/
danielk1977397d65f2008-11-19 11:35:39 +00004867static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4868 UNUSED_PARAMETER(NotUsed);
4869 UNUSED_PARAMETER(NotUsed2);
4870 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004871 return 0;
4872}
4873
drhf2424c52010-04-26 00:04:55 +00004874
4875/*
drh734c9862008-11-28 15:37:20 +00004876************************ End of sqlite3_vfs methods ***************************
4877******************************************************************************/
4878
drh715ff302008-12-03 22:32:44 +00004879/******************************************************************************
4880************************** Begin Proxy Locking ********************************
4881**
4882** Proxy locking is a "uber-locking-method" in this sense: It uses the
4883** other locking methods on secondary lock files. Proxy locking is a
4884** meta-layer over top of the primitive locking implemented above. For
4885** this reason, the division that implements of proxy locking is deferred
4886** until late in the file (here) after all of the other I/O methods have
4887** been defined - so that the primitive locking methods are available
4888** as services to help with the implementation of proxy locking.
4889**
4890****
4891**
4892** The default locking schemes in SQLite use byte-range locks on the
4893** database file to coordinate safe, concurrent access by multiple readers
4894** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4895** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4896** as POSIX read & write locks over fixed set of locations (via fsctl),
4897** on AFP and SMB only exclusive byte-range locks are available via fsctl
4898** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4899** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4900** address in the shared range is taken for a SHARED lock, the entire
4901** shared range is taken for an EXCLUSIVE lock):
4902**
4903** PENDING_BYTE 0x40000000
4904** RESERVED_BYTE 0x40000001
4905** SHARED_RANGE 0x40000002 -> 0x40000200
4906**
4907** This works well on the local file system, but shows a nearly 100x
4908** slowdown in read performance on AFP because the AFP client disables
4909** the read cache when byte-range locks are present. Enabling the read
4910** cache exposes a cache coherency problem that is present on all OS X
4911** supported network file systems. NFS and AFP both observe the
4912** close-to-open semantics for ensuring cache coherency
4913** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4914** address the requirements for concurrent database access by multiple
4915** readers and writers
4916** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4917**
4918** To address the performance and cache coherency issues, proxy file locking
4919** changes the way database access is controlled by limiting access to a
4920** single host at a time and moving file locks off of the database file
4921** and onto a proxy file on the local file system.
4922**
4923**
4924** Using proxy locks
4925** -----------------
4926**
4927** C APIs
4928**
4929** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4930** <proxy_path> | ":auto:");
4931** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4932**
4933**
4934** SQL pragmas
4935**
4936** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4937** PRAGMA [database.]lock_proxy_file
4938**
4939** Specifying ":auto:" means that if there is a conch file with a matching
4940** host ID in it, the proxy path in the conch file will be used, otherwise
4941** a proxy path based on the user's temp dir
4942** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4943** actual proxy file name is generated from the name and path of the
4944** database file. For example:
4945**
4946** For database path "/Users/me/foo.db"
4947** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4948**
4949** Once a lock proxy is configured for a database connection, it can not
4950** be removed, however it may be switched to a different proxy path via
4951** the above APIs (assuming the conch file is not being held by another
4952** connection or process).
4953**
4954**
4955** How proxy locking works
4956** -----------------------
4957**
4958** Proxy file locking relies primarily on two new supporting files:
4959**
4960** * conch file to limit access to the database file to a single host
4961** at a time
4962**
4963** * proxy file to act as a proxy for the advisory locks normally
4964** taken on the database
4965**
4966** The conch file - to use a proxy file, sqlite must first "hold the conch"
4967** by taking an sqlite-style shared lock on the conch file, reading the
4968** contents and comparing the host's unique host ID (see below) and lock
4969** proxy path against the values stored in the conch. The conch file is
4970** stored in the same directory as the database file and the file name
4971** is patterned after the database file name as ".<databasename>-conch".
4972** If the conch file does not exist, or it's contents do not match the
4973** host ID and/or proxy path, then the lock is escalated to an exclusive
4974** lock and the conch file contents is updated with the host ID and proxy
4975** path and the lock is downgraded to a shared lock again. If the conch
4976** is held by another process (with a shared lock), the exclusive lock
4977** will fail and SQLITE_BUSY is returned.
4978**
4979** The proxy file - a single-byte file used for all advisory file locks
4980** normally taken on the database file. This allows for safe sharing
4981** of the database file for multiple readers and writers on the same
4982** host (the conch ensures that they all use the same local lock file).
4983**
drh715ff302008-12-03 22:32:44 +00004984** Requesting the lock proxy does not immediately take the conch, it is
4985** only taken when the first request to lock database file is made.
4986** This matches the semantics of the traditional locking behavior, where
4987** opening a connection to a database file does not take a lock on it.
4988** The shared lock and an open file descriptor are maintained until
4989** the connection to the database is closed.
4990**
4991** The proxy file and the lock file are never deleted so they only need
4992** to be created the first time they are used.
4993**
4994** Configuration options
4995** ---------------------
4996**
4997** SQLITE_PREFER_PROXY_LOCKING
4998**
4999** Database files accessed on non-local file systems are
5000** automatically configured for proxy locking, lock files are
5001** named automatically using the same logic as
5002** PRAGMA lock_proxy_file=":auto:"
5003**
5004** SQLITE_PROXY_DEBUG
5005**
5006** Enables the logging of error messages during host id file
5007** retrieval and creation
5008**
drh715ff302008-12-03 22:32:44 +00005009** LOCKPROXYDIR
5010**
5011** Overrides the default directory used for lock proxy files that
5012** are named automatically via the ":auto:" setting
5013**
5014** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5015**
5016** Permissions to use when creating a directory for storing the
5017** lock proxy files, only used when LOCKPROXYDIR is not set.
5018**
5019**
5020** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5021** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5022** force proxy locking to be used for every database file opened, and 0
5023** will force automatic proxy locking to be disabled for all database
5024** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5025** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5026*/
5027
5028/*
5029** Proxy locking is only available on MacOSX
5030*/
drhd2cb50b2009-01-09 21:41:17 +00005031#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005032
drh715ff302008-12-03 22:32:44 +00005033/*
5034** The proxyLockingContext has the path and file structures for the remote
5035** and local proxy files in it
5036*/
5037typedef struct proxyLockingContext proxyLockingContext;
5038struct proxyLockingContext {
5039 unixFile *conchFile; /* Open conch file */
5040 char *conchFilePath; /* Name of the conch file */
5041 unixFile *lockProxy; /* Open proxy lock file */
5042 char *lockProxyPath; /* Name of the proxy lock file */
5043 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005044 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005045 void *oldLockingContext; /* Original lockingcontext to restore on close */
5046 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5047};
5048
drh7ed97b92010-01-20 13:07:21 +00005049/*
5050** The proxy lock file path for the database at dbPath is written into lPath,
5051** which must point to valid, writable memory large enough for a maxLen length
5052** file path.
drh715ff302008-12-03 22:32:44 +00005053*/
drh715ff302008-12-03 22:32:44 +00005054static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5055 int len;
5056 int dbLen;
5057 int i;
5058
5059#ifdef LOCKPROXYDIR
5060 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5061#else
5062# ifdef _CS_DARWIN_USER_TEMP_DIR
5063 {
drh7ed97b92010-01-20 13:07:21 +00005064 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005065 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5066 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005067 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005068 }
drh7ed97b92010-01-20 13:07:21 +00005069 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005070 }
5071# else
5072 len = strlcpy(lPath, "/tmp/", maxLen);
5073# endif
5074#endif
5075
5076 if( lPath[len-1]!='/' ){
5077 len = strlcat(lPath, "/", maxLen);
5078 }
5079
5080 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005081 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00005082 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
5083 char c = dbPath[i];
5084 lPath[i+len] = (c=='/')?'_':c;
5085 }
5086 lPath[i+len]='\0';
5087 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005088 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005089 return SQLITE_OK;
5090}
5091
drh7ed97b92010-01-20 13:07:21 +00005092/*
5093 ** Creates the lock file and any missing directories in lockPath
5094 */
5095static int proxyCreateLockPath(const char *lockPath){
5096 int i, len;
5097 char buf[MAXPATHLEN];
5098 int start = 0;
5099
5100 assert(lockPath!=NULL);
5101 /* try to create all the intermediate directories */
5102 len = (int)strlen(lockPath);
5103 buf[0] = lockPath[0];
5104 for( i=1; i<len; i++ ){
5105 if( lockPath[i] == '/' && (i - start > 0) ){
5106 /* only mkdir if leaf dir != "." or "/" or ".." */
5107 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5108 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5109 buf[i]='\0';
5110 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5111 int err=errno;
5112 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005113 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005114 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005115 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005116 return err;
5117 }
5118 }
5119 }
5120 start=i+1;
5121 }
5122 buf[i] = lockPath[i];
5123 }
drh308c2a52010-05-14 11:30:18 +00005124 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005125 return 0;
5126}
5127
drh715ff302008-12-03 22:32:44 +00005128/*
5129** Create a new VFS file descriptor (stored in memory obtained from
5130** sqlite3_malloc) and open the file named "path" in the file descriptor.
5131**
5132** The caller is responsible not only for closing the file descriptor
5133** but also for freeing the memory associated with the file descriptor.
5134*/
drh7ed97b92010-01-20 13:07:21 +00005135static int proxyCreateUnixFile(
5136 const char *path, /* path for the new unixFile */
5137 unixFile **ppFile, /* unixFile created and returned by ref */
5138 int islockfile /* if non zero missing dirs will be created */
5139) {
5140 int fd = -1;
5141 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005142 unixFile *pNew;
5143 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005144 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005145 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005146 int terrno = 0;
5147 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005148
drh7ed97b92010-01-20 13:07:21 +00005149 /* 1. first try to open/create the file
5150 ** 2. if that fails, and this is a lock file (not-conch), try creating
5151 ** the parent directories and then try again.
5152 ** 3. if that fails, try to open the file read-only
5153 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5154 */
5155 pUnused = findReusableFd(path, openFlags);
5156 if( pUnused ){
5157 fd = pUnused->fd;
5158 }else{
5159 pUnused = sqlite3_malloc(sizeof(*pUnused));
5160 if( !pUnused ){
5161 return SQLITE_NOMEM;
5162 }
5163 }
5164 if( fd<0 ){
5165 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5166 terrno = errno;
5167 if( fd<0 && errno==ENOENT && islockfile ){
5168 if( proxyCreateLockPath(path) == SQLITE_OK ){
5169 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5170 }
5171 }
5172 }
5173 if( fd<0 ){
5174 openFlags = O_RDONLY;
5175 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5176 terrno = errno;
5177 }
5178 if( fd<0 ){
5179 if( islockfile ){
5180 return SQLITE_BUSY;
5181 }
5182 switch (terrno) {
5183 case EACCES:
5184 return SQLITE_PERM;
5185 case EIO:
5186 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5187 default:
drh9978c972010-02-23 17:36:32 +00005188 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005189 }
5190 }
5191
5192 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5193 if( pNew==NULL ){
5194 rc = SQLITE_NOMEM;
5195 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005196 }
5197 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005198 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005199 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005200 pUnused->fd = fd;
5201 pUnused->flags = openFlags;
5202 pNew->pUnused = pUnused;
5203
5204 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5205 if( rc==SQLITE_OK ){
5206 *ppFile = pNew;
5207 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005208 }
drh7ed97b92010-01-20 13:07:21 +00005209end_create_proxy:
5210 close(fd); /* silently leak fd if error, we're already in error */
5211 sqlite3_free(pNew);
5212 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005213 return rc;
5214}
5215
drh7ed97b92010-01-20 13:07:21 +00005216#ifdef SQLITE_TEST
5217/* simulate multiple hosts by creating unique hostid file paths */
5218int sqlite3_hostid_num = 0;
5219#endif
5220
5221#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5222
5223/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5224** bytes of writable memory.
5225*/
5226static int proxyGetHostID(unsigned char *pHostID, int *pError){
5227 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5228
5229 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5230 memset(pHostID, 0, PROXY_HOSTIDLEN);
5231 if( gethostuuid(pHostID, &timeout) ){
5232 int err = errno;
5233 if( pError ){
5234 *pError = err;
5235 }
5236 return SQLITE_IOERR;
5237 }
5238#ifdef SQLITE_TEST
5239 /* simulate multiple hosts by creating unique hostid file paths */
5240 if( sqlite3_hostid_num != 0){
5241 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5242 }
5243#endif
5244
5245 return SQLITE_OK;
5246}
5247
5248/* The conch file contains the header, host id and lock file path
5249 */
5250#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5251#define PROXY_HEADERLEN 1 /* conch file header length */
5252#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5253#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5254
5255/*
5256** Takes an open conch file, copies the contents to a new path and then moves
5257** it back. The newly created file's file descriptor is assigned to the
5258** conch file structure and finally the original conch file descriptor is
5259** closed. Returns zero if successful.
5260*/
5261static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5262 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5263 unixFile *conchFile = pCtx->conchFile;
5264 char tPath[MAXPATHLEN];
5265 char buf[PROXY_MAXCONCHLEN];
5266 char *cPath = pCtx->conchFilePath;
5267 size_t readLen = 0;
5268 size_t pathLen = 0;
5269 char errmsg[64] = "";
5270 int fd = -1;
5271 int rc = -1;
5272
5273 /* create a new path by replace the trailing '-conch' with '-break' */
5274 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5275 if( pathLen>MAXPATHLEN || pathLen<6 ||
5276 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5277 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5278 goto end_breaklock;
5279 }
5280 /* read the conch content */
5281 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5282 if( readLen<PROXY_PATHINDEX ){
5283 sprintf(errmsg, "read error (len %d)", (int)readLen);
5284 goto end_breaklock;
5285 }
5286 /* write it out to the temporary break file */
5287 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5288 if( fd<0 ){
5289 sprintf(errmsg, "create failed (%d)", errno);
5290 goto end_breaklock;
5291 }
5292 if( pwrite(fd, buf, readLen, 0) != readLen ){
5293 sprintf(errmsg, "write failed (%d)", errno);
5294 goto end_breaklock;
5295 }
5296 if( rename(tPath, cPath) ){
5297 sprintf(errmsg, "rename failed (%d)", errno);
5298 goto end_breaklock;
5299 }
5300 rc = 0;
5301 fprintf(stderr, "broke stale lock on %s\n", cPath);
5302 close(conchFile->h);
5303 conchFile->h = fd;
5304 conchFile->openFlags = O_RDWR | O_CREAT;
5305
5306end_breaklock:
5307 if( rc ){
5308 if( fd>=0 ){
5309 unlink(tPath);
5310 close(fd);
5311 }
5312 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5313 }
5314 return rc;
5315}
5316
5317/* Take the requested lock on the conch file and break a stale lock if the
5318** host id matches.
5319*/
5320static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5321 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5322 unixFile *conchFile = pCtx->conchFile;
5323 int rc = SQLITE_OK;
5324 int nTries = 0;
5325 struct timespec conchModTime;
5326
5327 do {
5328 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5329 nTries ++;
5330 if( rc==SQLITE_BUSY ){
5331 /* If the lock failed (busy):
5332 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5333 * 2nd try: fail if the mod time changed or host id is different, wait
5334 * 10 sec and try again
5335 * 3rd try: break the lock unless the mod time has changed.
5336 */
5337 struct stat buf;
5338 if( fstat(conchFile->h, &buf) ){
5339 pFile->lastErrno = errno;
5340 return SQLITE_IOERR_LOCK;
5341 }
5342
5343 if( nTries==1 ){
5344 conchModTime = buf.st_mtimespec;
5345 usleep(500000); /* wait 0.5 sec and try the lock again*/
5346 continue;
5347 }
5348
5349 assert( nTries>1 );
5350 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5351 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5352 return SQLITE_BUSY;
5353 }
5354
5355 if( nTries==2 ){
5356 char tBuf[PROXY_MAXCONCHLEN];
5357 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5358 if( len<0 ){
5359 pFile->lastErrno = errno;
5360 return SQLITE_IOERR_LOCK;
5361 }
5362 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5363 /* don't break the lock if the host id doesn't match */
5364 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5365 return SQLITE_BUSY;
5366 }
5367 }else{
5368 /* don't break the lock on short read or a version mismatch */
5369 return SQLITE_BUSY;
5370 }
5371 usleep(10000000); /* wait 10 sec and try the lock again */
5372 continue;
5373 }
5374
5375 assert( nTries==3 );
5376 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5377 rc = SQLITE_OK;
5378 if( lockType==EXCLUSIVE_LOCK ){
5379 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5380 }
5381 if( !rc ){
5382 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5383 }
5384 }
5385 }
5386 } while( rc==SQLITE_BUSY && nTries<3 );
5387
5388 return rc;
5389}
5390
5391/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005392** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5393** lockPath means that the lockPath in the conch file will be used if the
5394** host IDs match, or a new lock path will be generated automatically
5395** and written to the conch file.
5396*/
5397static int proxyTakeConch(unixFile *pFile){
5398 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5399
drh7ed97b92010-01-20 13:07:21 +00005400 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005401 return SQLITE_OK;
5402 }else{
5403 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005404 uuid_t myHostID;
5405 int pError = 0;
5406 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005407 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005408 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005409 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005410 int createConch = 0;
5411 int hostIdMatch = 0;
5412 int readLen = 0;
5413 int tryOldLockPath = 0;
5414 int forceNewLockPath = 0;
5415
drh308c2a52010-05-14 11:30:18 +00005416 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5417 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005418
drh7ed97b92010-01-20 13:07:21 +00005419 rc = proxyGetHostID(myHostID, &pError);
5420 if( (rc&0xff)==SQLITE_IOERR ){
5421 pFile->lastErrno = pError;
5422 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005423 }
drh7ed97b92010-01-20 13:07:21 +00005424 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005425 if( rc!=SQLITE_OK ){
5426 goto end_takeconch;
5427 }
drh7ed97b92010-01-20 13:07:21 +00005428 /* read the existing conch file */
5429 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5430 if( readLen<0 ){
5431 /* I/O error: lastErrno set by seekAndRead */
5432 pFile->lastErrno = conchFile->lastErrno;
5433 rc = SQLITE_IOERR_READ;
5434 goto end_takeconch;
5435 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5436 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5437 /* a short read or version format mismatch means we need to create a new
5438 ** conch file.
5439 */
5440 createConch = 1;
5441 }
5442 /* if the host id matches and the lock path already exists in the conch
5443 ** we'll try to use the path there, if we can't open that path, we'll
5444 ** retry with a new auto-generated path
5445 */
5446 do { /* in case we need to try again for an :auto: named lock file */
5447
5448 if( !createConch && !forceNewLockPath ){
5449 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5450 PROXY_HOSTIDLEN);
5451 /* if the conch has data compare the contents */
5452 if( !pCtx->lockProxyPath ){
5453 /* for auto-named local lock file, just check the host ID and we'll
5454 ** use the local lock file path that's already in there
5455 */
5456 if( hostIdMatch ){
5457 size_t pathLen = (readLen - PROXY_PATHINDEX);
5458
5459 if( pathLen>=MAXPATHLEN ){
5460 pathLen=MAXPATHLEN-1;
5461 }
5462 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5463 lockPath[pathLen] = 0;
5464 tempLockPath = lockPath;
5465 tryOldLockPath = 1;
5466 /* create a copy of the lock path if the conch is taken */
5467 goto end_takeconch;
5468 }
5469 }else if( hostIdMatch
5470 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5471 readLen-PROXY_PATHINDEX)
5472 ){
5473 /* conch host and lock path match */
5474 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005475 }
drh7ed97b92010-01-20 13:07:21 +00005476 }
5477
5478 /* if the conch isn't writable and doesn't match, we can't take it */
5479 if( (conchFile->openFlags&O_RDWR) == 0 ){
5480 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005481 goto end_takeconch;
5482 }
drh7ed97b92010-01-20 13:07:21 +00005483
5484 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005485 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005486 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5487 tempLockPath = lockPath;
5488 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005489 }
drh7ed97b92010-01-20 13:07:21 +00005490
5491 /* update conch with host and path (this will fail if other process
5492 ** has a shared lock already), if the host id matches, use the big
5493 ** stick.
drh715ff302008-12-03 22:32:44 +00005494 */
drh7ed97b92010-01-20 13:07:21 +00005495 futimes(conchFile->h, NULL);
5496 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005497 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005498 /* We are trying for an exclusive lock but another thread in this
5499 ** same process is still holding a shared lock. */
5500 rc = SQLITE_BUSY;
5501 } else {
5502 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005503 }
drh715ff302008-12-03 22:32:44 +00005504 }else{
drh7ed97b92010-01-20 13:07:21 +00005505 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005506 }
drh7ed97b92010-01-20 13:07:21 +00005507 if( rc==SQLITE_OK ){
5508 char writeBuffer[PROXY_MAXCONCHLEN];
5509 int writeSize = 0;
5510
5511 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5512 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5513 if( pCtx->lockProxyPath!=NULL ){
5514 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5515 }else{
5516 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5517 }
5518 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5519 ftruncate(conchFile->h, writeSize);
5520 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5521 fsync(conchFile->h);
5522 /* If we created a new conch file (not just updated the contents of a
5523 ** valid conch file), try to match the permissions of the database
5524 */
5525 if( rc==SQLITE_OK && createConch ){
5526 struct stat buf;
5527 int err = fstat(pFile->h, &buf);
5528 if( err==0 ){
5529 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5530 S_IROTH|S_IWOTH);
5531 /* try to match the database file R/W permissions, ignore failure */
5532#ifndef SQLITE_PROXY_DEBUG
5533 fchmod(conchFile->h, cmode);
5534#else
5535 if( fchmod(conchFile->h, cmode)!=0 ){
5536 int code = errno;
5537 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5538 cmode, code, strerror(code));
5539 } else {
5540 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5541 }
5542 }else{
5543 int code = errno;
5544 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5545 err, code, strerror(code));
5546#endif
5547 }
drh715ff302008-12-03 22:32:44 +00005548 }
5549 }
drh7ed97b92010-01-20 13:07:21 +00005550 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5551
5552 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005553 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005554 if( rc==SQLITE_OK && pFile->openFlags ){
5555 if( pFile->h>=0 ){
5556#ifdef STRICT_CLOSE_ERROR
5557 if( close(pFile->h) ){
5558 pFile->lastErrno = errno;
5559 return SQLITE_IOERR_CLOSE;
5560 }
5561#else
5562 close(pFile->h); /* silently leak fd if fail */
5563#endif
5564 }
5565 pFile->h = -1;
5566 int fd = open(pCtx->dbPath, pFile->openFlags,
5567 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005568 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005569 if( fd>=0 ){
5570 pFile->h = fd;
5571 }else{
drh9978c972010-02-23 17:36:32 +00005572 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005573 during locking */
5574 }
5575 }
5576 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5577 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5578 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5579 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5580 /* we couldn't create the proxy lock file with the old lock file path
5581 ** so try again via auto-naming
5582 */
5583 forceNewLockPath = 1;
5584 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005585 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005586 }
5587 }
5588 if( rc==SQLITE_OK ){
5589 /* Need to make a copy of path if we extracted the value
5590 ** from the conch file or the path was allocated on the stack
5591 */
5592 if( tempLockPath ){
5593 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5594 if( !pCtx->lockProxyPath ){
5595 rc = SQLITE_NOMEM;
5596 }
5597 }
5598 }
5599 if( rc==SQLITE_OK ){
5600 pCtx->conchHeld = 1;
5601
5602 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5603 afpLockingContext *afpCtx;
5604 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5605 afpCtx->dbPath = pCtx->lockProxyPath;
5606 }
5607 } else {
5608 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5609 }
drh308c2a52010-05-14 11:30:18 +00005610 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5611 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005612 return rc;
drh308c2a52010-05-14 11:30:18 +00005613 } while (1); /* in case we need to retry the :auto: lock file -
5614 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005615 }
5616}
5617
5618/*
5619** If pFile holds a lock on a conch file, then release that lock.
5620*/
5621static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005622 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005623 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5624 unixFile *conchFile; /* Name of the conch file */
5625
5626 pCtx = (proxyLockingContext *)pFile->lockingContext;
5627 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005628 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005629 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005630 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005631 if( pCtx->conchHeld>0 ){
5632 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5633 }
drh715ff302008-12-03 22:32:44 +00005634 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005635 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5636 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005637 return rc;
5638}
5639
5640/*
5641** Given the name of a database file, compute the name of its conch file.
5642** Store the conch filename in memory obtained from sqlite3_malloc().
5643** Make *pConchPath point to the new name. Return SQLITE_OK on success
5644** or SQLITE_NOMEM if unable to obtain memory.
5645**
5646** The caller is responsible for ensuring that the allocated memory
5647** space is eventually freed.
5648**
5649** *pConchPath is set to NULL if a memory allocation error occurs.
5650*/
5651static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5652 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005653 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005654 char *conchPath; /* buffer in which to construct conch name */
5655
5656 /* Allocate space for the conch filename and initialize the name to
5657 ** the name of the original database file. */
5658 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5659 if( conchPath==0 ){
5660 return SQLITE_NOMEM;
5661 }
5662 memcpy(conchPath, dbPath, len+1);
5663
5664 /* now insert a "." before the last / character */
5665 for( i=(len-1); i>=0; i-- ){
5666 if( conchPath[i]=='/' ){
5667 i++;
5668 break;
5669 }
5670 }
5671 conchPath[i]='.';
5672 while ( i<len ){
5673 conchPath[i+1]=dbPath[i];
5674 i++;
5675 }
5676
5677 /* append the "-conch" suffix to the file */
5678 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005679 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005680
5681 return SQLITE_OK;
5682}
5683
5684
5685/* Takes a fully configured proxy locking-style unix file and switches
5686** the local lock file path
5687*/
5688static int switchLockProxyPath(unixFile *pFile, const char *path) {
5689 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5690 char *oldPath = pCtx->lockProxyPath;
5691 int rc = SQLITE_OK;
5692
drh308c2a52010-05-14 11:30:18 +00005693 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005694 return SQLITE_BUSY;
5695 }
5696
5697 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5698 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5699 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5700 return SQLITE_OK;
5701 }else{
5702 unixFile *lockProxy = pCtx->lockProxy;
5703 pCtx->lockProxy=NULL;
5704 pCtx->conchHeld = 0;
5705 if( lockProxy!=NULL ){
5706 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5707 if( rc ) return rc;
5708 sqlite3_free(lockProxy);
5709 }
5710 sqlite3_free(oldPath);
5711 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5712 }
5713
5714 return rc;
5715}
5716
5717/*
5718** pFile is a file that has been opened by a prior xOpen call. dbPath
5719** is a string buffer at least MAXPATHLEN+1 characters in size.
5720**
5721** This routine find the filename associated with pFile and writes it
5722** int dbPath.
5723*/
5724static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005725#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005726 if( pFile->pMethod == &afpIoMethods ){
5727 /* afp style keeps a reference to the db path in the filePath field
5728 ** of the struct */
drhea678832008-12-10 19:26:22 +00005729 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005730 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5731 } else
drh715ff302008-12-03 22:32:44 +00005732#endif
5733 if( pFile->pMethod == &dotlockIoMethods ){
5734 /* dot lock style uses the locking context to store the dot lock
5735 ** file path */
5736 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5737 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5738 }else{
5739 /* all other styles use the locking context to store the db file path */
5740 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005741 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005742 }
5743 return SQLITE_OK;
5744}
5745
5746/*
5747** Takes an already filled in unix file and alters it so all file locking
5748** will be performed on the local proxy lock file. The following fields
5749** are preserved in the locking context so that they can be restored and
5750** the unix structure properly cleaned up at close time:
5751** ->lockingContext
5752** ->pMethod
5753*/
5754static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5755 proxyLockingContext *pCtx;
5756 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5757 char *lockPath=NULL;
5758 int rc = SQLITE_OK;
5759
drh308c2a52010-05-14 11:30:18 +00005760 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005761 return SQLITE_BUSY;
5762 }
5763 proxyGetDbPathForUnixFile(pFile, dbPath);
5764 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5765 lockPath=NULL;
5766 }else{
5767 lockPath=(char *)path;
5768 }
5769
drh308c2a52010-05-14 11:30:18 +00005770 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5771 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005772
5773 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5774 if( pCtx==0 ){
5775 return SQLITE_NOMEM;
5776 }
5777 memset(pCtx, 0, sizeof(*pCtx));
5778
5779 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5780 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005781 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5782 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5783 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5784 ** (c) the file system is read-only, then enable no-locking access.
5785 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5786 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5787 */
5788 struct statfs fsInfo;
5789 struct stat conchInfo;
5790 int goLockless = 0;
5791
5792 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5793 int err = errno;
5794 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5795 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5796 }
5797 }
5798 if( goLockless ){
5799 pCtx->conchHeld = -1; /* read only FS/ lockless */
5800 rc = SQLITE_OK;
5801 }
5802 }
drh715ff302008-12-03 22:32:44 +00005803 }
5804 if( rc==SQLITE_OK && lockPath ){
5805 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5806 }
5807
5808 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005809 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5810 if( pCtx->dbPath==NULL ){
5811 rc = SQLITE_NOMEM;
5812 }
5813 }
5814 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005815 /* all memory is allocated, proxys are created and assigned,
5816 ** switch the locking context and pMethod then return.
5817 */
drh715ff302008-12-03 22:32:44 +00005818 pCtx->oldLockingContext = pFile->lockingContext;
5819 pFile->lockingContext = pCtx;
5820 pCtx->pOldMethod = pFile->pMethod;
5821 pFile->pMethod = &proxyIoMethods;
5822 }else{
5823 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00005824 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00005825 sqlite3_free(pCtx->conchFile);
5826 }
drh7ed97b92010-01-20 13:07:21 +00005827 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00005828 sqlite3_free(pCtx->conchFilePath);
5829 sqlite3_free(pCtx);
5830 }
drh308c2a52010-05-14 11:30:18 +00005831 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
5832 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005833 return rc;
5834}
5835
5836
5837/*
5838** This routine handles sqlite3_file_control() calls that are specific
5839** to proxy locking.
5840*/
5841static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5842 switch( op ){
5843 case SQLITE_GET_LOCKPROXYFILE: {
5844 unixFile *pFile = (unixFile*)id;
5845 if( pFile->pMethod == &proxyIoMethods ){
5846 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5847 proxyTakeConch(pFile);
5848 if( pCtx->lockProxyPath ){
5849 *(const char **)pArg = pCtx->lockProxyPath;
5850 }else{
5851 *(const char **)pArg = ":auto: (not held)";
5852 }
5853 } else {
5854 *(const char **)pArg = NULL;
5855 }
5856 return SQLITE_OK;
5857 }
5858 case SQLITE_SET_LOCKPROXYFILE: {
5859 unixFile *pFile = (unixFile*)id;
5860 int rc = SQLITE_OK;
5861 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5862 if( pArg==NULL || (const char *)pArg==0 ){
5863 if( isProxyStyle ){
5864 /* turn off proxy locking - not supported */
5865 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5866 }else{
5867 /* turn off proxy locking - already off - NOOP */
5868 rc = SQLITE_OK;
5869 }
5870 }else{
5871 const char *proxyPath = (const char *)pArg;
5872 if( isProxyStyle ){
5873 proxyLockingContext *pCtx =
5874 (proxyLockingContext*)pFile->lockingContext;
5875 if( !strcmp(pArg, ":auto:")
5876 || (pCtx->lockProxyPath &&
5877 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5878 ){
5879 rc = SQLITE_OK;
5880 }else{
5881 rc = switchLockProxyPath(pFile, proxyPath);
5882 }
5883 }else{
5884 /* turn on proxy file locking */
5885 rc = proxyTransformUnixFile(pFile, proxyPath);
5886 }
5887 }
5888 return rc;
5889 }
5890 default: {
5891 assert( 0 ); /* The call assures that only valid opcodes are sent */
5892 }
5893 }
5894 /*NOTREACHED*/
5895 return SQLITE_ERROR;
5896}
5897
5898/*
5899** Within this division (the proxying locking implementation) the procedures
5900** above this point are all utilities. The lock-related methods of the
5901** proxy-locking sqlite3_io_method object follow.
5902*/
5903
5904
5905/*
5906** This routine checks if there is a RESERVED lock held on the specified
5907** file by this or any other process. If such a lock is held, set *pResOut
5908** to a non-zero value otherwise *pResOut is set to zero. The return value
5909** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5910*/
5911static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5912 unixFile *pFile = (unixFile*)id;
5913 int rc = proxyTakeConch(pFile);
5914 if( rc==SQLITE_OK ){
5915 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005916 if( pCtx->conchHeld>0 ){
5917 unixFile *proxy = pCtx->lockProxy;
5918 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5919 }else{ /* conchHeld < 0 is lockless */
5920 pResOut=0;
5921 }
drh715ff302008-12-03 22:32:44 +00005922 }
5923 return rc;
5924}
5925
5926/*
drh308c2a52010-05-14 11:30:18 +00005927** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00005928** of the following:
5929**
5930** (1) SHARED_LOCK
5931** (2) RESERVED_LOCK
5932** (3) PENDING_LOCK
5933** (4) EXCLUSIVE_LOCK
5934**
5935** Sometimes when requesting one lock state, additional lock states
5936** are inserted in between. The locking might fail on one of the later
5937** transitions leaving the lock state different from what it started but
5938** still short of its goal. The following chart shows the allowed
5939** transitions and the inserted intermediate states:
5940**
5941** UNLOCKED -> SHARED
5942** SHARED -> RESERVED
5943** SHARED -> (PENDING) -> EXCLUSIVE
5944** RESERVED -> (PENDING) -> EXCLUSIVE
5945** PENDING -> EXCLUSIVE
5946**
5947** This routine will only increase a lock. Use the sqlite3OsUnlock()
5948** routine to lower a locking level.
5949*/
drh308c2a52010-05-14 11:30:18 +00005950static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00005951 unixFile *pFile = (unixFile*)id;
5952 int rc = proxyTakeConch(pFile);
5953 if( rc==SQLITE_OK ){
5954 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005955 if( pCtx->conchHeld>0 ){
5956 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00005957 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
5958 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00005959 }else{
5960 /* conchHeld < 0 is lockless */
5961 }
drh715ff302008-12-03 22:32:44 +00005962 }
5963 return rc;
5964}
5965
5966
5967/*
drh308c2a52010-05-14 11:30:18 +00005968** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00005969** must be either NO_LOCK or SHARED_LOCK.
5970**
5971** If the locking level of the file descriptor is already at or below
5972** the requested locking level, this routine is a no-op.
5973*/
drh308c2a52010-05-14 11:30:18 +00005974static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00005975 unixFile *pFile = (unixFile*)id;
5976 int rc = proxyTakeConch(pFile);
5977 if( rc==SQLITE_OK ){
5978 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005979 if( pCtx->conchHeld>0 ){
5980 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00005981 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
5982 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00005983 }else{
5984 /* conchHeld < 0 is lockless */
5985 }
drh715ff302008-12-03 22:32:44 +00005986 }
5987 return rc;
5988}
5989
5990/*
5991** Close a file that uses proxy locks.
5992*/
5993static int proxyClose(sqlite3_file *id) {
5994 if( id ){
5995 unixFile *pFile = (unixFile*)id;
5996 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5997 unixFile *lockProxy = pCtx->lockProxy;
5998 unixFile *conchFile = pCtx->conchFile;
5999 int rc = SQLITE_OK;
6000
6001 if( lockProxy ){
6002 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6003 if( rc ) return rc;
6004 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6005 if( rc ) return rc;
6006 sqlite3_free(lockProxy);
6007 pCtx->lockProxy = 0;
6008 }
6009 if( conchFile ){
6010 if( pCtx->conchHeld ){
6011 rc = proxyReleaseConch(pFile);
6012 if( rc ) return rc;
6013 }
6014 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6015 if( rc ) return rc;
6016 sqlite3_free(conchFile);
6017 }
6018 sqlite3_free(pCtx->lockProxyPath);
6019 sqlite3_free(pCtx->conchFilePath);
6020 sqlite3_free(pCtx->dbPath);
6021 /* restore the original locking context and pMethod then close it */
6022 pFile->lockingContext = pCtx->oldLockingContext;
6023 pFile->pMethod = pCtx->pOldMethod;
6024 sqlite3_free(pCtx);
6025 return pFile->pMethod->xClose(id);
6026 }
6027 return SQLITE_OK;
6028}
6029
6030
6031
drhd2cb50b2009-01-09 21:41:17 +00006032#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006033/*
6034** The proxy locking style is intended for use with AFP filesystems.
6035** And since AFP is only supported on MacOSX, the proxy locking is also
6036** restricted to MacOSX.
6037**
6038**
6039******************* End of the proxy lock implementation **********************
6040******************************************************************************/
6041
drh734c9862008-11-28 15:37:20 +00006042/*
danielk1977e339d652008-06-28 11:23:00 +00006043** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006044**
6045** This routine registers all VFS implementations for unix-like operating
6046** systems. This routine, and the sqlite3_os_end() routine that follows,
6047** should be the only routines in this file that are visible from other
6048** files.
drh6b9d6dd2008-12-03 19:34:47 +00006049**
6050** This routine is called once during SQLite initialization and by a
6051** single thread. The memory allocation and mutex subsystems have not
6052** necessarily been initialized when this routine is called, and so they
6053** should not be used.
drh153c62c2007-08-24 03:51:33 +00006054*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006055int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006056 /*
6057 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006058 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6059 ** to the "finder" function. (pAppData is a pointer to a pointer because
6060 ** silly C90 rules prohibit a void* from being cast to a function pointer
6061 ** and so we have to go through the intermediate pointer to avoid problems
6062 ** when compiling with -pedantic-errors on GCC.)
6063 **
6064 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006065 ** finder-function. The finder-function returns a pointer to the
6066 ** sqlite_io_methods object that implements the desired locking
6067 ** behaviors. See the division above that contains the IOMETHODS
6068 ** macro for addition information on finder-functions.
6069 **
6070 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6071 ** object. But the "autolockIoFinder" available on MacOSX does a little
6072 ** more than that; it looks at the filesystem type that hosts the
6073 ** database file and tries to choose an locking method appropriate for
6074 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006075 */
drh7708e972008-11-29 00:56:52 +00006076 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006077 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006078 sizeof(unixFile), /* szOsFile */ \
6079 MAX_PATHNAME, /* mxPathname */ \
6080 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006081 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006082 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006083 unixOpen, /* xOpen */ \
6084 unixDelete, /* xDelete */ \
6085 unixAccess, /* xAccess */ \
6086 unixFullPathname, /* xFullPathname */ \
6087 unixDlOpen, /* xDlOpen */ \
6088 unixDlError, /* xDlError */ \
6089 unixDlSym, /* xDlSym */ \
6090 unixDlClose, /* xDlClose */ \
6091 unixRandomness, /* xRandomness */ \
6092 unixSleep, /* xSleep */ \
6093 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006094 unixGetLastError, /* xGetLastError */ \
drhf2424c52010-04-26 00:04:55 +00006095 0, /* xRename */ \
drhb7e8ea22010-05-03 14:32:30 +00006096 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006097 }
6098
drh6b9d6dd2008-12-03 19:34:47 +00006099 /*
6100 ** All default VFSes for unix are contained in the following array.
6101 **
6102 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6103 ** by the SQLite core when the VFS is registered. So the following
6104 ** array cannot be const.
6105 */
danielk1977e339d652008-06-28 11:23:00 +00006106 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006107#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006108 UNIXVFS("unix", autolockIoFinder ),
6109#else
6110 UNIXVFS("unix", posixIoFinder ),
6111#endif
6112 UNIXVFS("unix-none", nolockIoFinder ),
6113 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006114#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006115 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006116#endif
6117#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006118 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006119#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006120 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006121#endif
chw78a13182009-04-07 05:35:03 +00006122#endif
drhd2cb50b2009-01-09 21:41:17 +00006123#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006124 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006125 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006126 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006127#endif
drh153c62c2007-08-24 03:51:33 +00006128 };
drh6b9d6dd2008-12-03 19:34:47 +00006129 unsigned int i; /* Loop counter */
6130
6131 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006132 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006133 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006134 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006135 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006136}
danielk1977e339d652008-06-28 11:23:00 +00006137
6138/*
drh6b9d6dd2008-12-03 19:34:47 +00006139** Shutdown the operating system interface.
6140**
6141** Some operating systems might need to do some cleanup in this routine,
6142** to release dynamically allocated objects. But not on unix.
6143** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006144*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006145int sqlite3_os_end(void){
6146 return SQLITE_OK;
6147}
drhdce8bdb2007-08-16 13:01:44 +00006148
danielk197729bafea2008-06-26 10:41:19 +00006149#endif /* SQLITE_OS_UNIX */