blob: 769e75df39ec62c85a4b0f5663e960bea4b1951c [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>
danielk1977e339d652008-06-28 11:23:00 +0000122
drh40bbb0a2008-09-23 10:23:26 +0000123#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000124# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000125# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <semaphore.h>
127# include <limits.h>
128# else
drh9b35ea62008-11-29 02:20:26 +0000129# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000131# endif
drhbfe66312006-10-03 17:40:40 +0000132#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000133
drhf8b4d8c2010-03-05 13:53:22 +0000134#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000135# include <sys/mount.h>
136#endif
137
drh9cbe6352005-11-29 03:13:21 +0000138/*
drh7ed97b92010-01-20 13:07:21 +0000139** Allowed values of unixFile.fsFlags
140*/
141#define SQLITE_FSFLAGS_IS_MSDOS 0x1
142
143/*
drhf1a221e2006-01-15 17:27:17 +0000144** If we are to be thread-safe, include the pthreads header and define
145** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000146*/
drhd677b3d2007-08-20 22:48:41 +0000147#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000148# include <pthread.h>
149# define SQLITE_UNIX_THREADS 1
150#endif
151
152/*
153** Default permissions when creating a new file
154*/
155#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
156# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
157#endif
158
danielk1977b4b47412007-08-17 15:53:36 +0000159/*
aswiftaebf4132008-11-21 00:10:35 +0000160 ** Default permissions when creating auto proxy dir
161 */
162#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
163# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
164#endif
165
166/*
danielk1977b4b47412007-08-17 15:53:36 +0000167** Maximum supported path-length.
168*/
169#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000170
drh734c9862008-11-28 15:37:20 +0000171/*
drh734c9862008-11-28 15:37:20 +0000172** Only set the lastErrno if the error code is a real error and not
173** a normal expected return code of SQLITE_BUSY or SQLITE_OK
174*/
175#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
176
drh9cbe6352005-11-29 03:13:21 +0000177
178/*
dane946c392009-08-22 11:39:46 +0000179** Sometimes, after a file handle is closed by SQLite, the file descriptor
180** cannot be closed immediately. In these cases, instances of the following
181** structure are used to store the file descriptor while waiting for an
182** opportunity to either close or reuse it.
183*/
184typedef struct UnixUnusedFd UnixUnusedFd;
185struct UnixUnusedFd {
186 int fd; /* File descriptor to close */
187 int flags; /* Flags this file descriptor was opened with */
188 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
189};
190
191/*
drh9b35ea62008-11-29 02:20:26 +0000192** The unixFile structure is subclass of sqlite3_file specific to the unix
193** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000194*/
drh054889e2005-11-30 03:20:31 +0000195typedef struct unixFile unixFile;
196struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000197 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000198 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
199 struct unixLockInfo *pLock; /* Info about locks on this inode */
200 int h; /* The file descriptor */
201 int dirfd; /* File descriptor for the directory */
202 unsigned char locktype; /* The type of lock held on this fd */
203 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000204 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000205 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000206 int fileFlags; /* Miscellanous flags */
drh08c6d442009-02-09 17:34:07 +0000207#if SQLITE_ENABLE_LOCKING_STYLE
208 int openFlags; /* The flags specified at open() */
209#endif
drh7ed97b92010-01-20 13:07:21 +0000210#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
211 unsigned fsFlags; /* cached details from statfs() */
212#endif
drh734c9862008-11-28 15:37:20 +0000213#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000214 pthread_t tid; /* The thread that "owns" this unixFile */
215#endif
216#if OS_VXWORKS
217 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000218 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000219#endif
drh8f941bc2009-01-14 23:03:40 +0000220#ifndef NDEBUG
221 /* The next group of variables are used to track whether or not the
222 ** transaction counter in bytes 24-27 of database files are updated
223 ** whenever any part of the database changes. An assertion fault will
224 ** occur if a file is updated without also updating the transaction
225 ** counter. This test is made to avoid new problems similar to the
226 ** one described by ticket #3584.
227 */
228 unsigned char transCntrChng; /* True if the transaction counter changed */
229 unsigned char dbUpdate; /* True if any part of database file changed */
230 unsigned char inNormalWrite; /* True if in a normal write operation */
231#endif
danielk1977967a4a12007-08-20 14:23:44 +0000232#ifdef SQLITE_TEST
233 /* In test mode, increase the size of this structure a bit so that
234 ** it is larger than the struct CrashFile defined in test6.c.
235 */
236 char aPadding[32];
237#endif
drh9cbe6352005-11-29 03:13:21 +0000238};
239
drh0ccebe72005-06-07 22:22:50 +0000240/*
drh0c2694b2009-09-03 16:23:44 +0000241** The following macros define bits in unixFile.fileFlags
242*/
243#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
244
245/*
drh198bf392006-01-06 21:52:49 +0000246** Include code that is common to all os_*.c files
247*/
248#include "os_common.h"
249
250/*
drh0ccebe72005-06-07 22:22:50 +0000251** Define various macros that are missing from some systems.
252*/
drhbbd42a62004-05-22 17:41:58 +0000253#ifndef O_LARGEFILE
254# define O_LARGEFILE 0
255#endif
256#ifdef SQLITE_DISABLE_LFS
257# undef O_LARGEFILE
258# define O_LARGEFILE 0
259#endif
260#ifndef O_NOFOLLOW
261# define O_NOFOLLOW 0
262#endif
263#ifndef O_BINARY
264# define O_BINARY 0
265#endif
266
267/*
268** The DJGPP compiler environment looks mostly like Unix, but it
269** lacks the fcntl() system call. So redefine fcntl() to be something
270** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000271** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000272*/
273#ifdef __DJGPP__
274# define fcntl(A,B,C) 0
275#endif
276
277/*
drh2b4b5962005-06-15 17:47:55 +0000278** The threadid macro resolves to the thread-id or to 0. Used for
279** testing and debugging only.
280*/
drhd677b3d2007-08-20 22:48:41 +0000281#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000282#define threadid pthread_self()
283#else
284#define threadid 0
285#endif
286
danielk197713adf8a2004-06-03 16:08:41 +0000287
drh107886a2008-11-21 22:21:50 +0000288/*
dan9359c7b2009-08-21 08:29:10 +0000289** Helper functions to obtain and relinquish the global mutex. The
290** global mutex is used to protect the unixOpenCnt, unixLockInfo and
291** vxworksFileId objects used by this file, all of which may be
292** shared by multiple threads.
293**
294** Function unixMutexHeld() is used to assert() that the global mutex
295** is held when required. This function is only used as part of assert()
296** statements. e.g.
297**
298** unixEnterMutex()
299** assert( unixMutexHeld() );
300** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000301*/
302static void unixEnterMutex(void){
303 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
304}
305static void unixLeaveMutex(void){
306 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
307}
dan9359c7b2009-08-21 08:29:10 +0000308#ifdef SQLITE_DEBUG
309static int unixMutexHeld(void) {
310 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
311}
312#endif
drh107886a2008-11-21 22:21:50 +0000313
drh734c9862008-11-28 15:37:20 +0000314
315#ifdef SQLITE_DEBUG
316/*
317** Helper function for printing out trace information from debugging
318** binaries. This returns the string represetation of the supplied
319** integer lock-type.
320*/
321static const char *locktypeName(int locktype){
322 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000323 case NO_LOCK: return "NONE";
324 case SHARED_LOCK: return "SHARED";
325 case RESERVED_LOCK: return "RESERVED";
326 case PENDING_LOCK: return "PENDING";
327 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000328 }
329 return "ERROR";
330}
331#endif
332
333#ifdef SQLITE_LOCK_TRACE
334/*
335** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000336**
drh734c9862008-11-28 15:37:20 +0000337** This routine is used for troubleshooting locks on multithreaded
338** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
339** command-line option on the compiler. This code is normally
340** turned off.
341*/
342static int lockTrace(int fd, int op, struct flock *p){
343 char *zOpName, *zType;
344 int s;
345 int savedErrno;
346 if( op==F_GETLK ){
347 zOpName = "GETLK";
348 }else if( op==F_SETLK ){
349 zOpName = "SETLK";
350 }else{
351 s = fcntl(fd, op, p);
352 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
353 return s;
354 }
355 if( p->l_type==F_RDLCK ){
356 zType = "RDLCK";
357 }else if( p->l_type==F_WRLCK ){
358 zType = "WRLCK";
359 }else if( p->l_type==F_UNLCK ){
360 zType = "UNLCK";
361 }else{
362 assert( 0 );
363 }
364 assert( p->l_whence==SEEK_SET );
365 s = fcntl(fd, op, p);
366 savedErrno = errno;
367 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
368 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
369 (int)p->l_pid, s);
370 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
371 struct flock l2;
372 l2 = *p;
373 fcntl(fd, F_GETLK, &l2);
374 if( l2.l_type==F_RDLCK ){
375 zType = "RDLCK";
376 }else if( l2.l_type==F_WRLCK ){
377 zType = "WRLCK";
378 }else if( l2.l_type==F_UNLCK ){
379 zType = "UNLCK";
380 }else{
381 assert( 0 );
382 }
383 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
384 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
385 }
386 errno = savedErrno;
387 return s;
388}
389#define fcntl lockTrace
390#endif /* SQLITE_LOCK_TRACE */
391
392
393
394/*
395** This routine translates a standard POSIX errno code into something
396** useful to the clients of the sqlite3 functions. Specifically, it is
397** intended to translate a variety of "try again" errors into SQLITE_BUSY
398** and a variety of "please close the file descriptor NOW" errors into
399** SQLITE_IOERR
400**
401** Errors during initialization of locks, or file system support for locks,
402** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
403*/
404static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
405 switch (posixError) {
406 case 0:
407 return SQLITE_OK;
408
409 case EAGAIN:
410 case ETIMEDOUT:
411 case EBUSY:
412 case EINTR:
413 case ENOLCK:
414 /* random NFS retry error, unless during file system support
415 * introspection, in which it actually means what it says */
416 return SQLITE_BUSY;
417
418 case EACCES:
419 /* EACCES is like EAGAIN during locking operations, but not any other time*/
420 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
421 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
422 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
423 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
424 return SQLITE_BUSY;
425 }
426 /* else fall through */
427 case EPERM:
428 return SQLITE_PERM;
429
430 case EDEADLK:
431 return SQLITE_IOERR_BLOCKED;
432
433#if EOPNOTSUPP!=ENOTSUP
434 case EOPNOTSUPP:
435 /* something went terribly awry, unless during file system support
436 * introspection, in which it actually means what it says */
437#endif
438#ifdef ENOTSUP
439 case ENOTSUP:
440 /* invalid fd, unless during file system support introspection, in which
441 * it actually means what it says */
442#endif
443 case EIO:
444 case EBADF:
445 case EINVAL:
446 case ENOTCONN:
447 case ENODEV:
448 case ENXIO:
449 case ENOENT:
450 case ESTALE:
451 case ENOSYS:
452 /* these should force the client to close the file and reconnect */
453
454 default:
455 return sqliteIOErr;
456 }
457}
458
459
460
461/******************************************************************************
462****************** Begin Unique File ID Utility Used By VxWorks ***************
463**
464** On most versions of unix, we can get a unique ID for a file by concatenating
465** the device number and the inode number. But this does not work on VxWorks.
466** On VxWorks, a unique file id must be based on the canonical filename.
467**
468** A pointer to an instance of the following structure can be used as a
469** unique file ID in VxWorks. Each instance of this structure contains
470** a copy of the canonical filename. There is also a reference count.
471** The structure is reclaimed when the number of pointers to it drops to
472** zero.
473**
474** There are never very many files open at one time and lookups are not
475** a performance-critical path, so it is sufficient to put these
476** structures on a linked list.
477*/
478struct vxworksFileId {
479 struct vxworksFileId *pNext; /* Next in a list of them all */
480 int nRef; /* Number of references to this one */
481 int nName; /* Length of the zCanonicalName[] string */
482 char *zCanonicalName; /* Canonical filename */
483};
484
485#if OS_VXWORKS
486/*
drh9b35ea62008-11-29 02:20:26 +0000487** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000488** variable:
489*/
490static struct vxworksFileId *vxworksFileList = 0;
491
492/*
493** Simplify a filename into its canonical form
494** by making the following changes:
495**
496** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000497** * convert /./ into just /
498** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000499**
500** Changes are made in-place. Return the new name length.
501**
502** The original filename is in z[0..n-1]. Return the number of
503** characters in the simplified name.
504*/
505static int vxworksSimplifyName(char *z, int n){
506 int i, j;
507 while( n>1 && z[n-1]=='/' ){ n--; }
508 for(i=j=0; i<n; i++){
509 if( z[i]=='/' ){
510 if( z[i+1]=='/' ) continue;
511 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
512 i += 1;
513 continue;
514 }
515 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
516 while( j>0 && z[j-1]!='/' ){ j--; }
517 if( j>0 ){ j--; }
518 i += 2;
519 continue;
520 }
521 }
522 z[j++] = z[i];
523 }
524 z[j] = 0;
525 return j;
526}
527
528/*
529** Find a unique file ID for the given absolute pathname. Return
530** a pointer to the vxworksFileId object. This pointer is the unique
531** file ID.
532**
533** The nRef field of the vxworksFileId object is incremented before
534** the object is returned. A new vxworksFileId object is created
535** and added to the global list if necessary.
536**
537** If a memory allocation error occurs, return NULL.
538*/
539static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
540 struct vxworksFileId *pNew; /* search key and new file ID */
541 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
542 int n; /* Length of zAbsoluteName string */
543
544 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000545 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000546 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
547 if( pNew==0 ) return 0;
548 pNew->zCanonicalName = (char*)&pNew[1];
549 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
550 n = vxworksSimplifyName(pNew->zCanonicalName, n);
551
552 /* Search for an existing entry that matching the canonical name.
553 ** If found, increment the reference count and return a pointer to
554 ** the existing file ID.
555 */
556 unixEnterMutex();
557 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
558 if( pCandidate->nName==n
559 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
560 ){
561 sqlite3_free(pNew);
562 pCandidate->nRef++;
563 unixLeaveMutex();
564 return pCandidate;
565 }
566 }
567
568 /* No match was found. We will make a new file ID */
569 pNew->nRef = 1;
570 pNew->nName = n;
571 pNew->pNext = vxworksFileList;
572 vxworksFileList = pNew;
573 unixLeaveMutex();
574 return pNew;
575}
576
577/*
578** Decrement the reference count on a vxworksFileId object. Free
579** the object when the reference count reaches zero.
580*/
581static void vxworksReleaseFileId(struct vxworksFileId *pId){
582 unixEnterMutex();
583 assert( pId->nRef>0 );
584 pId->nRef--;
585 if( pId->nRef==0 ){
586 struct vxworksFileId **pp;
587 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
588 assert( *pp==pId );
589 *pp = pId->pNext;
590 sqlite3_free(pId);
591 }
592 unixLeaveMutex();
593}
594#endif /* OS_VXWORKS */
595/*************** End of Unique File ID Utility Used By VxWorks ****************
596******************************************************************************/
597
598
599/******************************************************************************
600*************************** Posix Advisory Locking ****************************
601**
drh9b35ea62008-11-29 02:20:26 +0000602** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000603** section 6.5.2.2 lines 483 through 490 specify that when a process
604** sets or clears a lock, that operation overrides any prior locks set
605** by the same process. It does not explicitly say so, but this implies
606** that it overrides locks set by the same process using a different
607** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000608**
609** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000610** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
611**
612** Suppose ./file1 and ./file2 are really the same file (because
613** one is a hard or symbolic link to the other) then if you set
614** an exclusive lock on fd1, then try to get an exclusive lock
615** on fd2, it works. I would have expected the second lock to
616** fail since there was already a lock on the file due to fd1.
617** But not so. Since both locks came from the same process, the
618** second overrides the first, even though they were on different
619** file descriptors opened on different file names.
620**
drh734c9862008-11-28 15:37:20 +0000621** This means that we cannot use POSIX locks to synchronize file access
622** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000623** to synchronize access for threads in separate processes, but not
624** threads within the same process.
625**
626** To work around the problem, SQLite has to manage file locks internally
627** on its own. Whenever a new database is opened, we have to find the
628** specific inode of the database file (the inode is determined by the
629** st_dev and st_ino fields of the stat structure that fstat() fills in)
630** and check for locks already existing on that inode. When locks are
631** created or removed, we have to look at our own internal record of the
632** locks to see if another thread has previously set a lock on that same
633** inode.
634**
drh9b35ea62008-11-29 02:20:26 +0000635** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
636** For VxWorks, we have to use the alternative unique ID system based on
637** canonical filename and implemented in the previous division.)
638**
danielk1977ad94b582007-08-20 06:44:22 +0000639** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000640** descriptor. It is now a structure that holds the integer file
641** descriptor and a pointer to a structure that describes the internal
642** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000643** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000644** point to the same locking structure. The locking structure keeps
645** a reference count (so we will know when to delete it) and a "cnt"
646** field that tells us its internal lock status. cnt==0 means the
647** file is unlocked. cnt==-1 means the file has an exclusive lock.
648** cnt>0 means there are cnt shared locks on the file.
649**
650** Any attempt to lock or unlock a file first checks the locking
651** structure. The fcntl() system call is only invoked to set a
652** POSIX lock if the internal lock structure transitions between
653** a locked and an unlocked state.
654**
drh734c9862008-11-28 15:37:20 +0000655** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000656**
657** If you close a file descriptor that points to a file that has locks,
658** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000659** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000660** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000661** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000662** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000663** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000664** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000665** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000666** be closed and that list is walked (and cleared) when the last lock
667** clears.
668**
drh9b35ea62008-11-29 02:20:26 +0000669** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000670**
drh9b35ea62008-11-29 02:20:26 +0000671** Many older versions of linux use the LinuxThreads library which is
672** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000673** A cannot be modified or overridden by a different thread B.
674** Only thread A can modify the lock. Locking behavior is correct
675** if the appliation uses the newer Native Posix Thread Library (NPTL)
676** on linux - with NPTL a lock created by thread A can override locks
677** in thread B. But there is no way to know at compile-time which
678** threading library is being used. So there is no way to know at
679** compile-time whether or not thread A can override locks on thread B.
680** We have to do a run-time check to discover the behavior of the
681** current process.
drh5fdae772004-06-29 03:29:00 +0000682**
drh734c9862008-11-28 15:37:20 +0000683** On systems where thread A is unable to modify locks created by
684** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000685** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000686** structure to record this information. And on those systems it
687** is illegal to begin a transaction in one thread and finish it
688** in another. For this latter restriction, there is no work-around.
689** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000690*/
691
692/*
drh6c7d5c52008-11-21 20:32:33 +0000693** Set or check the unixFile.tid field. This field is set when an unixFile
694** is first opened. All subsequent uses of the unixFile verify that the
695** same thread is operating on the unixFile. Some operating systems do
696** not allow locks to be overridden by other threads and that restriction
697** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000698** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000699**
700** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
701** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000702** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000703** or if no locks are held. But the unixFile.pLock field needs to be
704** recomputed because its key includes the thread-id. See the
705** transferOwnership() function below for additional information
706*/
drh734c9862008-11-28 15:37:20 +0000707#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000708# define SET_THREADID(X) (X)->tid = pthread_self()
709# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
710 !pthread_equal((X)->tid, pthread_self()))
711#else
712# define SET_THREADID(X)
713# define CHECK_THREADID(X) 0
714#endif
715
716/*
drhbbd42a62004-05-22 17:41:58 +0000717** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000718** to locate a particular unixOpenCnt structure given its inode. This
719** is the same as the unixLockKey except that the thread ID is omitted.
720*/
721struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000722 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000723#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000724 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000725#else
drh107886a2008-11-21 22:21:50 +0000726 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000727#endif
728};
729
730/*
731** An instance of the following structure serves as the key used
732** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000733**
drh734c9862008-11-28 15:37:20 +0000734** If threads cannot override each others locks (LinuxThreads), then we
735** set the unixLockKey.tid field to the thread ID. If threads can override
736** each others locks (Posix and NPTL) then tid is always set to zero.
737** tid is omitted if we compile without threading support or on an OS
738** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000739*/
drh6c7d5c52008-11-21 20:32:33 +0000740struct unixLockKey {
741 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000742#if SQLITE_THREADSAFE && defined(__linux__)
743 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000744#endif
drhbbd42a62004-05-22 17:41:58 +0000745};
746
747/*
748** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000749** inode. Or, on LinuxThreads, there is one of these structures for
750** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000751**
danielk1977ad94b582007-08-20 06:44:22 +0000752** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000753** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000754** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000755*/
drh6c7d5c52008-11-21 20:32:33 +0000756struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000757 struct unixLockKey lockKey; /* The lookup key */
758 int cnt; /* Number of SHARED locks held */
759 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
760 int nRef; /* Number of pointers to this structure */
drh7ed97b92010-01-20 13:07:21 +0000761#if defined(SQLITE_ENABLE_LOCKING_STYLE)
762 unsigned long long sharedByte; /* for AFP simulated shared lock */
763#endif
drh734c9862008-11-28 15:37:20 +0000764 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
765 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000766};
767
768/*
769** An instance of the following structure is allocated for each open
770** inode. This structure keeps track of the number of locks on that
771** inode. If a close is attempted against an inode that is holding
772** locks, the close is deferred until all locks clear by adding the
773** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000774**
775** TODO: Consider changing this so that there is only a single file
776** descriptor for each open file, even when it is opened multiple times.
777** The close() system call would only occur when the last database
778** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000779*/
drh6c7d5c52008-11-21 20:32:33 +0000780struct unixOpenCnt {
781 struct unixFileId fileId; /* The lookup key */
782 int nRef; /* Number of pointers to this structure */
783 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000784 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000785#if OS_VXWORKS
786 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000787 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000788#endif
drh6c7d5c52008-11-21 20:32:33 +0000789 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000790};
791
drhda0e7682008-07-30 15:27:54 +0000792/*
drh9b35ea62008-11-29 02:20:26 +0000793** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
794** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000795** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000796** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000797*/
drh6c7d5c52008-11-21 20:32:33 +0000798static struct unixLockInfo *lockList = 0;
799static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000800
drh5fdae772004-06-29 03:29:00 +0000801/*
drh9b35ea62008-11-29 02:20:26 +0000802** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000803** locks.
804**
drh9b35ea62008-11-29 02:20:26 +0000805** 0: No. Threads cannot override each others locks. (LinuxThreads)
806** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000807** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000808**
drh5062d3a2006-01-31 23:03:35 +0000809** On some systems, we know at compile-time if threads can override each
810** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
811** will be set appropriately. On other systems, we have to check at
812** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
813** undefined.
814**
drhf1a221e2006-01-15 17:27:17 +0000815** This variable normally has file scope only. But during testing, we make
816** it a global so that the test code can change its value in order to verify
817** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000818*/
drh715ff302008-12-03 22:32:44 +0000819#if SQLITE_THREADSAFE && defined(__linux__)
820# ifndef SQLITE_THREAD_OVERRIDE_LOCK
821# define SQLITE_THREAD_OVERRIDE_LOCK -1
822# endif
823# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000824int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000825# else
drh5062d3a2006-01-31 23:03:35 +0000826static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000827# endif
drh029b44b2006-01-15 00:13:15 +0000828#endif
drh5fdae772004-06-29 03:29:00 +0000829
830/*
831** This structure holds information passed into individual test
832** threads by the testThreadLockingBehavior() routine.
833*/
834struct threadTestData {
835 int fd; /* File to be locked */
836 struct flock lock; /* The locking operation */
837 int result; /* Result of the locking operation */
838};
839
drh6c7d5c52008-11-21 20:32:33 +0000840#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000841/*
danielk197741a6a612008-11-11 18:34:35 +0000842** This function is used as the main routine for a thread launched by
843** testThreadLockingBehavior(). It tests whether the shared-lock obtained
844** by the main thread in testThreadLockingBehavior() conflicts with a
845** hypothetical write-lock obtained by this thread on the same file.
846**
847** The write-lock is not actually acquired, as this is not possible if
848** the file is open in read-only mode (see ticket #3472).
849*/
drh5fdae772004-06-29 03:29:00 +0000850static void *threadLockingTest(void *pArg){
851 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000852 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000853 return pArg;
854}
drh6c7d5c52008-11-21 20:32:33 +0000855#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000856
drh6c7d5c52008-11-21 20:32:33 +0000857
858#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000859/*
860** This procedure attempts to determine whether or not threads
861** can override each others locks then sets the
862** threadsOverrideEachOthersLocks variable appropriately.
863*/
danielk19774d5238f2006-01-27 06:32:00 +0000864static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000865 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000866 int rc;
867 struct threadTestData d;
868 struct flock l;
869 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000870
871 fd = dup(fd_orig);
872 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000873 memset(&l, 0, sizeof(l));
874 l.l_type = F_RDLCK;
875 l.l_len = 1;
876 l.l_start = 0;
877 l.l_whence = SEEK_SET;
878 rc = fcntl(fd_orig, F_SETLK, &l);
879 if( rc!=0 ) return;
880 memset(&d, 0, sizeof(d));
881 d.fd = fd;
882 d.lock = l;
883 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000884 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
885 pthread_join(t, 0);
886 }
drh5fdae772004-06-29 03:29:00 +0000887 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000888 if( d.result!=0 ) return;
889 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000890}
drh06150f92009-07-03 12:57:58 +0000891#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000892
drhbbd42a62004-05-22 17:41:58 +0000893/*
drh6c7d5c52008-11-21 20:32:33 +0000894** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000895**
896** The mutex entered using the unixEnterMutex() function must be held
897** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000898*/
899static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000900 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000901 if( pLock ){
902 pLock->nRef--;
903 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000904 if( pLock->pPrev ){
905 assert( pLock->pPrev->pNext==pLock );
906 pLock->pPrev->pNext = pLock->pNext;
907 }else{
908 assert( lockList==pLock );
909 lockList = pLock->pNext;
910 }
911 if( pLock->pNext ){
912 assert( pLock->pNext->pPrev==pLock );
913 pLock->pNext->pPrev = pLock->pPrev;
914 }
danielk1977e339d652008-06-28 11:23:00 +0000915 sqlite3_free(pLock);
916 }
drhbbd42a62004-05-22 17:41:58 +0000917 }
918}
919
920/*
drh6c7d5c52008-11-21 20:32:33 +0000921** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000922**
923** The mutex entered using the unixEnterMutex() function must be held
924** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000925*/
drh6c7d5c52008-11-21 20:32:33 +0000926static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000927 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000928 if( pOpen ){
929 pOpen->nRef--;
930 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000931 if( pOpen->pPrev ){
932 assert( pOpen->pPrev->pNext==pOpen );
933 pOpen->pPrev->pNext = pOpen->pNext;
934 }else{
935 assert( openList==pOpen );
936 openList = pOpen->pNext;
937 }
938 if( pOpen->pNext ){
939 assert( pOpen->pNext->pPrev==pOpen );
940 pOpen->pNext->pPrev = pOpen->pPrev;
941 }
drh08da4bb2009-09-10 19:20:03 +0000942#if SQLITE_THREADSAFE && defined(__linux__)
dan11b38792009-09-09 18:46:52 +0000943 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
drh08da4bb2009-09-10 19:20:03 +0000944#endif
dan11b38792009-09-09 18:46:52 +0000945
946 /* If pOpen->pUnused is not null, then memory and file-descriptors
947 ** are leaked.
948 **
949 ** This will only happen if, under Linuxthreads, the user has opened
950 ** a transaction in one thread, then attempts to close the database
951 ** handle from another thread (without first unlocking the db file).
952 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000953 sqlite3_free(pOpen);
954 }
drhbbd42a62004-05-22 17:41:58 +0000955 }
956}
957
drh6c7d5c52008-11-21 20:32:33 +0000958/*
959** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
960** describes that file descriptor. Create new ones if necessary. The
961** return values might be uninitialized if an error occurs.
962**
dan9359c7b2009-08-21 08:29:10 +0000963** The mutex entered using the unixEnterMutex() function must be held
964** when this function is called.
965**
drh6c7d5c52008-11-21 20:32:33 +0000966** Return an appropriate error code.
967*/
968static int findLockInfo(
969 unixFile *pFile, /* Unix file with file desc used in the key */
970 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
971 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
972){
973 int rc; /* System call return code */
974 int fd; /* The file descriptor for pFile */
975 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
976 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
977 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000978 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000979 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
980
dan9359c7b2009-08-21 08:29:10 +0000981 assert( unixMutexHeld() );
982
drh6c7d5c52008-11-21 20:32:33 +0000983 /* Get low-level information about the file that we can used to
984 ** create a unique name for the file.
985 */
986 fd = pFile->h;
987 rc = fstat(fd, &statbuf);
988 if( rc!=0 ){
989 pFile->lastErrno = errno;
990#ifdef EOVERFLOW
991 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
992#endif
993 return SQLITE_IOERR;
994 }
995
drheb0d74f2009-02-03 15:27:02 +0000996#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000997 /* On OS X on an msdos filesystem, the inode number is reported
998 ** incorrectly for zero-size files. See ticket #3260. To work
999 ** around this problem (we consider it a bug in OS X, not SQLite)
1000 ** we always increase the file size to 1 by writing a single byte
1001 ** prior to accessing the inode number. The one byte written is
1002 ** an ASCII 'S' character which also happens to be the first byte
1003 ** in the header of every SQLite database. In this way, if there
1004 ** is a race condition such that another thread has already populated
1005 ** the first page of the database, no damage is done.
1006 */
drh7ed97b92010-01-20 13:07:21 +00001007 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +00001008 rc = write(fd, "S", 1);
1009 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001010 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001011 return SQLITE_IOERR;
1012 }
drh6c7d5c52008-11-21 20:32:33 +00001013 rc = fstat(fd, &statbuf);
1014 if( rc!=0 ){
1015 pFile->lastErrno = errno;
1016 return SQLITE_IOERR;
1017 }
1018 }
drheb0d74f2009-02-03 15:27:02 +00001019#endif
drh6c7d5c52008-11-21 20:32:33 +00001020
1021 memset(&lockKey, 0, sizeof(lockKey));
1022 lockKey.fid.dev = statbuf.st_dev;
1023#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001024 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001025#else
1026 lockKey.fid.ino = statbuf.st_ino;
1027#endif
drh734c9862008-11-28 15:37:20 +00001028#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001029 if( threadsOverrideEachOthersLocks<0 ){
1030 testThreadLockingBehavior(fd);
1031 }
1032 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1033#endif
1034 fileId = lockKey.fid;
1035 if( ppLock!=0 ){
1036 pLock = lockList;
1037 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1038 pLock = pLock->pNext;
1039 }
1040 if( pLock==0 ){
1041 pLock = sqlite3_malloc( sizeof(*pLock) );
1042 if( pLock==0 ){
1043 rc = SQLITE_NOMEM;
1044 goto exit_findlockinfo;
1045 }
drh9b5db1d2009-10-07 23:42:25 +00001046 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
drh6c7d5c52008-11-21 20:32:33 +00001047 pLock->nRef = 1;
1048 pLock->cnt = 0;
1049 pLock->locktype = 0;
drh7ed97b92010-01-20 13:07:21 +00001050#if defined(SQLITE_ENABLE_LOCKING_STYLE)
1051 pLock->sharedByte = 0;
1052#endif
drh6c7d5c52008-11-21 20:32:33 +00001053 pLock->pNext = lockList;
1054 pLock->pPrev = 0;
1055 if( lockList ) lockList->pPrev = pLock;
1056 lockList = pLock;
1057 }else{
1058 pLock->nRef++;
1059 }
1060 *ppLock = pLock;
1061 }
1062 if( ppOpen!=0 ){
1063 pOpen = openList;
1064 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1065 pOpen = pOpen->pNext;
1066 }
1067 if( pOpen==0 ){
1068 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1069 if( pOpen==0 ){
1070 releaseLockInfo(pLock);
1071 rc = SQLITE_NOMEM;
1072 goto exit_findlockinfo;
1073 }
dane946c392009-08-22 11:39:46 +00001074 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001075 pOpen->fileId = fileId;
1076 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001077 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001078 if( openList ) openList->pPrev = pOpen;
1079 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001080 }else{
1081 pOpen->nRef++;
1082 }
1083 *ppOpen = pOpen;
1084 }
1085
1086exit_findlockinfo:
1087 return rc;
1088}
drh6c7d5c52008-11-21 20:32:33 +00001089
drh7708e972008-11-29 00:56:52 +00001090/*
1091** If we are currently in a different thread than the thread that the
1092** unixFile argument belongs to, then transfer ownership of the unixFile
1093** over to the current thread.
1094**
1095** A unixFile is only owned by a thread on systems that use LinuxThreads.
1096**
1097** Ownership transfer is only allowed if the unixFile is currently unlocked.
1098** If the unixFile is locked and an ownership is wrong, then return
1099** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1100*/
1101#if SQLITE_THREADSAFE && defined(__linux__)
1102static int transferOwnership(unixFile *pFile){
1103 int rc;
1104 pthread_t hSelf;
1105 if( threadsOverrideEachOthersLocks ){
1106 /* Ownership transfers not needed on this system */
1107 return SQLITE_OK;
1108 }
1109 hSelf = pthread_self();
1110 if( pthread_equal(pFile->tid, hSelf) ){
1111 /* We are still in the same thread */
1112 OSTRACE1("No-transfer, same thread\n");
1113 return SQLITE_OK;
1114 }
1115 if( pFile->locktype!=NO_LOCK ){
1116 /* We cannot change ownership while we are holding a lock! */
drh413c3d32010-02-23 20:11:56 +00001117 return SQLITE_MISUSE_BKPT;
drh7708e972008-11-29 00:56:52 +00001118 }
1119 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1120 pFile->h, pFile->tid, hSelf);
1121 pFile->tid = hSelf;
1122 if (pFile->pLock != NULL) {
1123 releaseLockInfo(pFile->pLock);
1124 rc = findLockInfo(pFile, &pFile->pLock, 0);
1125 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1126 locktypeName(pFile->locktype),
1127 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1128 return rc;
1129 } else {
1130 return SQLITE_OK;
1131 }
1132}
1133#else /* if not SQLITE_THREADSAFE */
1134 /* On single-threaded builds, ownership transfer is a no-op */
1135# define transferOwnership(X) SQLITE_OK
1136#endif /* SQLITE_THREADSAFE */
1137
aswift5b1a2562008-08-22 00:22:35 +00001138
1139/*
danielk197713adf8a2004-06-03 16:08:41 +00001140** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001141** file by this or any other process. If such a lock is held, set *pResOut
1142** to a non-zero value otherwise *pResOut is set to zero. The return value
1143** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001144*/
danielk1977861f7452008-06-05 11:39:11 +00001145static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001146 int rc = SQLITE_OK;
1147 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001148 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001149
danielk1977861f7452008-06-05 11:39:11 +00001150 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1151
drh054889e2005-11-30 03:20:31 +00001152 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001153 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001154
1155 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001156 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001157 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001158 }
1159
drh2ac3ee92004-06-07 16:27:46 +00001160 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001161 */
danielk197709480a92009-02-09 05:32:32 +00001162#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001163 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001164 struct flock lock;
1165 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001166 lock.l_start = RESERVED_BYTE;
1167 lock.l_len = 1;
1168 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001169 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1170 int tErrno = errno;
1171 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1172 pFile->lastErrno = tErrno;
1173 } else if( lock.l_type!=F_UNLCK ){
1174 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001175 }
1176 }
danielk197709480a92009-02-09 05:32:32 +00001177#endif
danielk197713adf8a2004-06-03 16:08:41 +00001178
drh6c7d5c52008-11-21 20:32:33 +00001179 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001180 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001181
aswift5b1a2562008-08-22 00:22:35 +00001182 *pResOut = reserved;
1183 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001184}
1185
1186/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001187** Lock the file with the lock specified by parameter locktype - one
1188** of the following:
1189**
drh2ac3ee92004-06-07 16:27:46 +00001190** (1) SHARED_LOCK
1191** (2) RESERVED_LOCK
1192** (3) PENDING_LOCK
1193** (4) EXCLUSIVE_LOCK
1194**
drhb3e04342004-06-08 00:47:47 +00001195** Sometimes when requesting one lock state, additional lock states
1196** are inserted in between. The locking might fail on one of the later
1197** transitions leaving the lock state different from what it started but
1198** still short of its goal. The following chart shows the allowed
1199** transitions and the inserted intermediate states:
1200**
1201** UNLOCKED -> SHARED
1202** SHARED -> RESERVED
1203** SHARED -> (PENDING) -> EXCLUSIVE
1204** RESERVED -> (PENDING) -> EXCLUSIVE
1205** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001206**
drha6abd042004-06-09 17:37:22 +00001207** This routine will only increase a lock. Use the sqlite3OsUnlock()
1208** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001209*/
danielk197762079062007-08-15 17:08:46 +00001210static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001211 /* The following describes the implementation of the various locks and
1212 ** lock transitions in terms of the POSIX advisory shared and exclusive
1213 ** lock primitives (called read-locks and write-locks below, to avoid
1214 ** confusion with SQLite lock names). The algorithms are complicated
1215 ** slightly in order to be compatible with windows systems simultaneously
1216 ** accessing the same database file, in case that is ever required.
1217 **
1218 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1219 ** byte', each single bytes at well known offsets, and the 'shared byte
1220 ** range', a range of 510 bytes at a well known offset.
1221 **
1222 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1223 ** byte'. If this is successful, a random byte from the 'shared byte
1224 ** range' is read-locked and the lock on the 'pending byte' released.
1225 **
danielk197790ba3bd2004-06-25 08:32:25 +00001226 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1227 ** A RESERVED lock is implemented by grabbing a write-lock on the
1228 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001229 **
1230 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001231 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1232 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1233 ** obtained, but existing SHARED locks are allowed to persist. A process
1234 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1235 ** This property is used by the algorithm for rolling back a journal file
1236 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001237 **
danielk197790ba3bd2004-06-25 08:32:25 +00001238 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1239 ** implemented by obtaining a write-lock on the entire 'shared byte
1240 ** range'. Since all other locks require a read-lock on one of the bytes
1241 ** within this range, this ensures that no other locks are held on the
1242 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001243 **
1244 ** The reason a single byte cannot be used instead of the 'shared byte
1245 ** range' is that some versions of windows do not support read-locks. By
1246 ** locking a random byte from a range, concurrent SHARED locks may exist
1247 ** even if the locking primitive used is always a write-lock.
1248 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001249 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001250 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001251 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001252 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001253 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001254 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001255
drh054889e2005-11-30 03:20:31 +00001256 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001257 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001258 locktypeName(locktype), locktypeName(pFile->locktype),
1259 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001260
1261 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001262 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001263 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001264 */
drh054889e2005-11-30 03:20:31 +00001265 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00001266 OSTRACE3("LOCK %d %s ok (already held) (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001267 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001268 return SQLITE_OK;
1269 }
1270
drh0c2694b2009-09-03 16:23:44 +00001271 /* Make sure the locking sequence is correct.
1272 ** (1) We never move from unlocked to anything higher than shared lock.
1273 ** (2) SQLite never explicitly requests a pendig lock.
1274 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001275 */
drh054889e2005-11-30 03:20:31 +00001276 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001277 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001278 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001279
drh054889e2005-11-30 03:20:31 +00001280 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001281 */
drh6c7d5c52008-11-21 20:32:33 +00001282 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001283
drh029b44b2006-01-15 00:13:15 +00001284 /* Make sure the current thread owns the pFile.
1285 */
1286 rc = transferOwnership(pFile);
1287 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001288 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001289 return rc;
1290 }
drh64b1bea2006-01-15 02:30:57 +00001291 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001292
danielk1977ad94b582007-08-20 06:44:22 +00001293 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 ** handle that precludes the requested lock, return BUSY.
1295 */
drh054889e2005-11-30 03:20:31 +00001296 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001297 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001298 ){
1299 rc = SQLITE_BUSY;
1300 goto end_lock;
1301 }
1302
1303 /* If a SHARED lock is requested, and some thread using this PID already
1304 ** has a SHARED or RESERVED lock, then increment reference counts and
1305 ** return SQLITE_OK.
1306 */
1307 if( locktype==SHARED_LOCK &&
1308 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1309 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001310 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001311 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001312 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001313 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001314 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001315 goto end_lock;
1316 }
1317
danielk19779a1d0ab2004-06-01 14:09:28 +00001318
drh3cde3bb2004-06-12 02:17:14 +00001319 /* A PENDING lock is needed before acquiring a SHARED lock and before
1320 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1321 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001322 */
drh0c2694b2009-09-03 16:23:44 +00001323 lock.l_len = 1L;
1324 lock.l_whence = SEEK_SET;
drh3cde3bb2004-06-12 02:17:14 +00001325 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001326 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001327 ){
danielk1977489468c2004-06-28 08:25:47 +00001328 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001329 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001330 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001331 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001332 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001333 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1334 if( IS_LOCK_ERROR(rc) ){
1335 pFile->lastErrno = tErrno;
1336 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001337 goto end_lock;
1338 }
drh3cde3bb2004-06-12 02:17:14 +00001339 }
1340
1341
1342 /* If control gets to this point, then actually go ahead and make
1343 ** operating system calls for the specified lock.
1344 */
1345 if( locktype==SHARED_LOCK ){
1346 assert( pLock->cnt==0 );
1347 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001348
drh2ac3ee92004-06-07 16:27:46 +00001349 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001350 lock.l_start = SHARED_FIRST;
1351 lock.l_len = SHARED_SIZE;
1352 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1353 tErrno = errno;
1354 }
drh2ac3ee92004-06-07 16:27:46 +00001355 /* Drop the temporary PENDING lock */
1356 lock.l_start = PENDING_BYTE;
1357 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001359 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001360 if( s != -1 ){
1361 /* This could happen with a network mount */
1362 tErrno = errno;
1363 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1364 if( IS_LOCK_ERROR(rc) ){
1365 pFile->lastErrno = tErrno;
1366 }
1367 goto end_lock;
1368 }
drh2b4b5962005-06-15 17:47:55 +00001369 }
drhe2396a12007-03-29 20:19:58 +00001370 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001371 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1372 if( IS_LOCK_ERROR(rc) ){
1373 pFile->lastErrno = tErrno;
1374 }
drhbbd42a62004-05-22 17:41:58 +00001375 }else{
drh054889e2005-11-30 03:20:31 +00001376 pFile->locktype = SHARED_LOCK;
1377 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001378 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001379 }
drh3cde3bb2004-06-12 02:17:14 +00001380 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1381 /* We are trying for an exclusive lock but another thread in this
1382 ** same process is still holding a shared lock. */
1383 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001384 }else{
drh3cde3bb2004-06-12 02:17:14 +00001385 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001386 ** assumed that there is a SHARED or greater lock on the file
1387 ** already.
1388 */
drh054889e2005-11-30 03:20:31 +00001389 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001390 lock.l_type = F_WRLCK;
1391 switch( locktype ){
1392 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001393 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001394 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001395 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001396 lock.l_start = SHARED_FIRST;
1397 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001398 break;
1399 default:
1400 assert(0);
1401 }
drh7ed97b92010-01-20 13:07:21 +00001402 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001403 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001404 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001405 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1406 if( IS_LOCK_ERROR(rc) ){
1407 pFile->lastErrno = tErrno;
1408 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001409 }
drhbbd42a62004-05-22 17:41:58 +00001410 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001411
drh8f941bc2009-01-14 23:03:40 +00001412
1413#ifndef NDEBUG
1414 /* Set up the transaction-counter change checking flags when
1415 ** transitioning from a SHARED to a RESERVED lock. The change
1416 ** from SHARED to RESERVED marks the beginning of a normal
1417 ** write operation (not a hot journal rollback).
1418 */
1419 if( rc==SQLITE_OK
1420 && pFile->locktype<=SHARED_LOCK
1421 && locktype==RESERVED_LOCK
1422 ){
1423 pFile->transCntrChng = 0;
1424 pFile->dbUpdate = 0;
1425 pFile->inNormalWrite = 1;
1426 }
1427#endif
1428
1429
danielk1977ecb2a962004-06-02 06:30:16 +00001430 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001431 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001432 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001433 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001434 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001435 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001436 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001437
1438end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001439 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001440 OSTRACE4("LOCK %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001441 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001442 return rc;
1443}
1444
1445/*
dane946c392009-08-22 11:39:46 +00001446** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1447** If all such file descriptors are closed without error, the list is
1448** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001449**
1450** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001451** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001452** not deleted and SQLITE_IOERR_CLOSE returned.
1453*/
1454static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001455 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001456 struct unixOpenCnt *pOpen = pFile->pOpen;
1457 UnixUnusedFd *pError = 0;
1458 UnixUnusedFd *p;
1459 UnixUnusedFd *pNext;
1460 for(p=pOpen->pUnused; p; p=pNext){
1461 pNext = p->pNext;
1462 if( close(p->fd) ){
1463 pFile->lastErrno = errno;
1464 rc = SQLITE_IOERR_CLOSE;
1465 p->pNext = pError;
1466 pError = p;
dane946c392009-08-22 11:39:46 +00001467 }else{
1468 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001469 }
1470 }
dane946c392009-08-22 11:39:46 +00001471 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001472 return rc;
1473}
1474
1475/*
1476** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001477** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001478*/
1479static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001480 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001481 UnixUnusedFd *p = pFile->pUnused;
1482 p->pNext = pOpen->pUnused;
1483 pOpen->pUnused = p;
1484 pFile->h = -1;
1485 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001486}
1487
1488/*
drh054889e2005-11-30 03:20:31 +00001489** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001490** must be either NO_LOCK or SHARED_LOCK.
1491**
1492** If the locking level of the file descriptor is already at or below
1493** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001494**
1495** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1496** the byte range is divided into 2 parts and the first part is unlocked then
1497** set to a read lock, then the other part is simply unlocked. This works
1498** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1499** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001500*/
drh7ed97b92010-01-20 13:07:21 +00001501static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
1502 unixFile *pFile = (unixFile*)id;
1503 struct unixLockInfo *pLock;
1504 struct flock lock;
1505 int rc = SQLITE_OK;
1506 int h;
drh0c2694b2009-09-03 16:23:44 +00001507 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001508
drh054889e2005-11-30 03:20:31 +00001509 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001510 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001511 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001512
1513 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001514 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001515 return SQLITE_OK;
1516 }
drhf1a221e2006-01-15 17:27:17 +00001517 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00001518 return SQLITE_MISUSE_BKPT;
drhf1a221e2006-01-15 17:27:17 +00001519 }
drh6c7d5c52008-11-21 20:32:33 +00001520 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001521 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001522 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001523 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001524 if( pFile->locktype>SHARED_LOCK ){
1525 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001526 SimulateIOErrorBenign(1);
1527 SimulateIOError( h=(-1) )
1528 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001529
1530#ifndef NDEBUG
1531 /* When reducing a lock such that other processes can start
1532 ** reading the database file again, make sure that the
1533 ** transaction counter was updated if any part of the database
1534 ** file changed. If the transaction counter is not updated,
1535 ** other connections to the same file might not realize that
1536 ** the file has changed and hence might not know to flush their
1537 ** cache. The use of a stale cache can lead to database corruption.
1538 */
1539 assert( pFile->inNormalWrite==0
1540 || pFile->dbUpdate==0
1541 || pFile->transCntrChng==1 );
1542 pFile->inNormalWrite = 0;
1543#endif
1544
drh7ed97b92010-01-20 13:07:21 +00001545 /* downgrading to a shared lock on NFS involves clearing the write lock
1546 ** before establishing the readlock - to avoid a race condition we downgrade
1547 ** the lock in 2 blocks, so that part of the range will be covered by a
1548 ** write lock until the rest is covered by a read lock:
1549 ** 1: [WWWWW]
1550 ** 2: [....W]
1551 ** 3: [RRRRW]
1552 ** 4: [RRRR.]
1553 */
drh9c105bb2004-10-02 20:38:28 +00001554 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001555 if( handleNFSUnlock ){
1556 off_t divSize = SHARED_SIZE - 1;
1557
1558 lock.l_type = F_UNLCK;
1559 lock.l_whence = SEEK_SET;
1560 lock.l_start = SHARED_FIRST;
1561 lock.l_len = divSize;
1562 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001563 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001564 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1565 if( IS_LOCK_ERROR(rc) ){
1566 pFile->lastErrno = tErrno;
1567 }
1568 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001569 }
drh7ed97b92010-01-20 13:07:21 +00001570 lock.l_type = F_RDLCK;
1571 lock.l_whence = SEEK_SET;
1572 lock.l_start = SHARED_FIRST;
1573 lock.l_len = divSize;
1574 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001575 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001576 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1577 if( IS_LOCK_ERROR(rc) ){
1578 pFile->lastErrno = tErrno;
1579 }
1580 goto end_unlock;
1581 }
1582 lock.l_type = F_UNLCK;
1583 lock.l_whence = SEEK_SET;
1584 lock.l_start = SHARED_FIRST+divSize;
1585 lock.l_len = SHARED_SIZE-divSize;
1586 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001587 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001588 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1589 if( IS_LOCK_ERROR(rc) ){
1590 pFile->lastErrno = tErrno;
1591 }
1592 goto end_unlock;
1593 }
1594 }else{
1595 lock.l_type = F_RDLCK;
1596 lock.l_whence = SEEK_SET;
1597 lock.l_start = SHARED_FIRST;
1598 lock.l_len = SHARED_SIZE;
1599 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001600 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001601 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1602 if( IS_LOCK_ERROR(rc) ){
1603 pFile->lastErrno = tErrno;
1604 }
1605 goto end_unlock;
1606 }
drh9c105bb2004-10-02 20:38:28 +00001607 }
1608 }
drhbbd42a62004-05-22 17:41:58 +00001609 lock.l_type = F_UNLCK;
1610 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001611 lock.l_start = PENDING_BYTE;
1612 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001613 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001614 pLock->locktype = SHARED_LOCK;
1615 }else{
drh0c2694b2009-09-03 16:23:44 +00001616 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001617 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1618 if( IS_LOCK_ERROR(rc) ){
1619 pFile->lastErrno = tErrno;
1620 }
drhcd731cf2009-03-28 23:23:02 +00001621 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001622 }
drhbbd42a62004-05-22 17:41:58 +00001623 }
drha6abd042004-06-09 17:37:22 +00001624 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001625 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001626
drha6abd042004-06-09 17:37:22 +00001627 /* Decrement the shared lock counter. Release the lock using an
1628 ** OS call only when all threads in this same process have released
1629 ** the lock.
1630 */
1631 pLock->cnt--;
1632 if( pLock->cnt==0 ){
1633 lock.l_type = F_UNLCK;
1634 lock.l_whence = SEEK_SET;
1635 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001636 SimulateIOErrorBenign(1);
1637 SimulateIOError( h=(-1) )
1638 SimulateIOErrorBenign(0);
1639 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001640 pLock->locktype = NO_LOCK;
1641 }else{
drh0c2694b2009-09-03 16:23:44 +00001642 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001643 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001644 if( IS_LOCK_ERROR(rc) ){
1645 pFile->lastErrno = tErrno;
1646 }
drhf48f9ca2009-03-28 23:47:10 +00001647 pLock->locktype = NO_LOCK;
1648 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001649 }
drha6abd042004-06-09 17:37:22 +00001650 }
1651
drhbbd42a62004-05-22 17:41:58 +00001652 /* Decrement the count of locks against this same file. When the
1653 ** count reaches zero, close any other file descriptors whose close
1654 ** was deferred because of outstanding locks.
1655 */
danielk197764a54c52009-03-30 07:39:35 +00001656 pOpen = pFile->pOpen;
1657 pOpen->nLock--;
1658 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001659 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001660 int rc2 = closePendingFds(pFile);
1661 if( rc==SQLITE_OK ){
1662 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001663 }
drhbbd42a62004-05-22 17:41:58 +00001664 }
1665 }
aswift5b1a2562008-08-22 00:22:35 +00001666
1667end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001668 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001669 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001670 return rc;
drhbbd42a62004-05-22 17:41:58 +00001671}
1672
1673/*
drh7ed97b92010-01-20 13:07:21 +00001674** Lower the locking level on file descriptor pFile to locktype. locktype
1675** must be either NO_LOCK or SHARED_LOCK.
1676**
1677** If the locking level of the file descriptor is already at or below
1678** the requested locking level, this routine is a no-op.
1679*/
1680static int unixUnlock(sqlite3_file *id, int locktype){
1681 return _posixUnlock(id, locktype, 0);
1682}
1683
1684/*
danielk1977e339d652008-06-28 11:23:00 +00001685** This function performs the parts of the "close file" operation
1686** common to all locking schemes. It closes the directory and file
1687** handles, if they are valid, and sets all fields of the unixFile
1688** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001689**
1690** It is *not* necessary to hold the mutex when this routine is called,
1691** even on VxWorks. A mutex will be acquired on VxWorks by the
1692** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001693*/
1694static int closeUnixFile(sqlite3_file *id){
1695 unixFile *pFile = (unixFile*)id;
1696 if( pFile ){
1697 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001698 int err = close(pFile->dirfd);
1699 if( err ){
1700 pFile->lastErrno = errno;
1701 return SQLITE_IOERR_DIR_CLOSE;
1702 }else{
1703 pFile->dirfd=-1;
1704 }
danielk1977e339d652008-06-28 11:23:00 +00001705 }
1706 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001707 int err = close(pFile->h);
1708 if( err ){
1709 pFile->lastErrno = errno;
1710 return SQLITE_IOERR_CLOSE;
1711 }
danielk1977e339d652008-06-28 11:23:00 +00001712 }
drh6c7d5c52008-11-21 20:32:33 +00001713#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001714 if( pFile->pId ){
1715 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001716 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001717 }
drh107886a2008-11-21 22:21:50 +00001718 vxworksReleaseFileId(pFile->pId);
1719 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001720 }
1721#endif
danielk1977e339d652008-06-28 11:23:00 +00001722 OSTRACE2("CLOSE %-3d\n", pFile->h);
1723 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001724 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001725 memset(pFile, 0, sizeof(unixFile));
1726 }
1727 return SQLITE_OK;
1728}
1729
1730/*
danielk1977e3026632004-06-22 11:29:02 +00001731** Close a file.
1732*/
danielk197762079062007-08-15 17:08:46 +00001733static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001734 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001735 if( id ){
1736 unixFile *pFile = (unixFile *)id;
1737 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001738 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001739 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001740 /* If there are outstanding locks, do not actually close the file just
1741 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001742 ** descriptor to pOpen->pUnused list. It will be automatically closed
1743 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001744 */
dan08da86a2009-08-21 17:18:03 +00001745 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001746 }
danielk1977e339d652008-06-28 11:23:00 +00001747 releaseLockInfo(pFile->pLock);
1748 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001749 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001750 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001751 }
aswiftaebf4132008-11-21 00:10:35 +00001752 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001753}
1754
drh734c9862008-11-28 15:37:20 +00001755/************** End of the posix advisory lock implementation *****************
1756******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001757
drh734c9862008-11-28 15:37:20 +00001758/******************************************************************************
1759****************************** No-op Locking **********************************
1760**
1761** Of the various locking implementations available, this is by far the
1762** simplest: locking is ignored. No attempt is made to lock the database
1763** file for reading or writing.
1764**
1765** This locking mode is appropriate for use on read-only databases
1766** (ex: databases that are burned into CD-ROM, for example.) It can
1767** also be used if the application employs some external mechanism to
1768** prevent simultaneous access of the same database by two or more
1769** database connections. But there is a serious risk of database
1770** corruption if this locking mode is used in situations where multiple
1771** database connections are accessing the same database file at the same
1772** time and one or more of those connections are writing.
1773*/
drhbfe66312006-10-03 17:40:40 +00001774
drh734c9862008-11-28 15:37:20 +00001775static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1776 UNUSED_PARAMETER(NotUsed);
1777 *pResOut = 0;
1778 return SQLITE_OK;
1779}
drh734c9862008-11-28 15:37:20 +00001780static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1781 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1782 return SQLITE_OK;
1783}
drh734c9862008-11-28 15:37:20 +00001784static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1785 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1786 return SQLITE_OK;
1787}
1788
1789/*
drh9b35ea62008-11-29 02:20:26 +00001790** Close the file.
drh734c9862008-11-28 15:37:20 +00001791*/
1792static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001793 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001794}
1795
1796/******************* End of the no-op lock implementation *********************
1797******************************************************************************/
1798
1799/******************************************************************************
1800************************* Begin dot-file Locking ******************************
1801**
drh0c2694b2009-09-03 16:23:44 +00001802** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001803** files in order to control access to the database. This works on just
1804** about every filesystem imaginable. But there are serious downsides:
1805**
1806** (1) There is zero concurrency. A single reader blocks all other
1807** connections from reading or writing the database.
1808**
1809** (2) An application crash or power loss can leave stale lock files
1810** sitting around that need to be cleared manually.
1811**
1812** Nevertheless, a dotlock is an appropriate locking mode for use if no
1813** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001814**
1815** Dotfile locking works by creating a file in the same directory as the
1816** database and with the same name but with a ".lock" extension added.
1817** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1818** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001819*/
1820
1821/*
1822** The file suffix added to the data base filename in order to create the
1823** lock file.
1824*/
1825#define DOTLOCK_SUFFIX ".lock"
1826
drh7708e972008-11-29 00:56:52 +00001827/*
1828** This routine checks if there is a RESERVED lock held on the specified
1829** file by this or any other process. If such a lock is held, set *pResOut
1830** to a non-zero value otherwise *pResOut is set to zero. The return value
1831** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1832**
1833** In dotfile locking, either a lock exists or it does not. So in this
1834** variation of CheckReservedLock(), *pResOut is set to true if any lock
1835** is held on the file and false if the file is unlocked.
1836*/
drh734c9862008-11-28 15:37:20 +00001837static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1838 int rc = SQLITE_OK;
1839 int reserved = 0;
1840 unixFile *pFile = (unixFile*)id;
1841
1842 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1843
1844 assert( pFile );
1845
1846 /* Check if a thread in this process holds such a lock */
1847 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001848 /* Either this connection or some other connection in the same process
1849 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001850 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001851 }else{
1852 /* The lock is held if and only if the lockfile exists */
1853 const char *zLockFile = (const char*)pFile->lockingContext;
1854 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001855 }
drh476bda72009-12-04 14:25:18 +00001856 OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001857 *pResOut = reserved;
1858 return rc;
1859}
1860
drh7708e972008-11-29 00:56:52 +00001861/*
1862** Lock the file with the lock specified by parameter locktype - one
1863** of the following:
1864**
1865** (1) SHARED_LOCK
1866** (2) RESERVED_LOCK
1867** (3) PENDING_LOCK
1868** (4) EXCLUSIVE_LOCK
1869**
1870** Sometimes when requesting one lock state, additional lock states
1871** are inserted in between. The locking might fail on one of the later
1872** transitions leaving the lock state different from what it started but
1873** still short of its goal. The following chart shows the allowed
1874** transitions and the inserted intermediate states:
1875**
1876** UNLOCKED -> SHARED
1877** SHARED -> RESERVED
1878** SHARED -> (PENDING) -> EXCLUSIVE
1879** RESERVED -> (PENDING) -> EXCLUSIVE
1880** PENDING -> EXCLUSIVE
1881**
1882** This routine will only increase a lock. Use the sqlite3OsUnlock()
1883** routine to lower a locking level.
1884**
1885** With dotfile locking, we really only support state (4): EXCLUSIVE.
1886** But we track the other locking levels internally.
1887*/
drh734c9862008-11-28 15:37:20 +00001888static int dotlockLock(sqlite3_file *id, int locktype) {
1889 unixFile *pFile = (unixFile*)id;
1890 int fd;
1891 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001892 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001893
drh7708e972008-11-29 00:56:52 +00001894
1895 /* If we have any lock, then the lock file already exists. All we have
1896 ** to do is adjust our internal record of the lock level.
1897 */
1898 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001899 pFile->locktype = locktype;
1900#if !OS_VXWORKS
1901 /* Always update the timestamp on the old file */
1902 utimes(zLockFile, NULL);
1903#endif
drh7708e972008-11-29 00:56:52 +00001904 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001905 }
1906
1907 /* grab an exclusive lock */
1908 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1909 if( fd<0 ){
1910 /* failed to open/create the file, someone else may have stolen the lock */
1911 int tErrno = errno;
1912 if( EEXIST == tErrno ){
1913 rc = SQLITE_BUSY;
1914 } else {
1915 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1916 if( IS_LOCK_ERROR(rc) ){
1917 pFile->lastErrno = tErrno;
1918 }
1919 }
drh7708e972008-11-29 00:56:52 +00001920 return rc;
drh734c9862008-11-28 15:37:20 +00001921 }
1922 if( close(fd) ){
1923 pFile->lastErrno = errno;
1924 rc = SQLITE_IOERR_CLOSE;
1925 }
1926
1927 /* got it, set the type and return ok */
1928 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001929 return rc;
1930}
1931
drh7708e972008-11-29 00:56:52 +00001932/*
1933** Lower the locking level on file descriptor pFile to locktype. locktype
1934** must be either NO_LOCK or SHARED_LOCK.
1935**
1936** If the locking level of the file descriptor is already at or below
1937** the requested locking level, this routine is a no-op.
1938**
1939** When the locking level reaches NO_LOCK, delete the lock file.
1940*/
drh734c9862008-11-28 15:37:20 +00001941static int dotlockUnlock(sqlite3_file *id, int locktype) {
1942 unixFile *pFile = (unixFile*)id;
1943 char *zLockFile = (char *)pFile->lockingContext;
1944
1945 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001946 OSTRACE5("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00001947 pFile->locktype, getpid());
1948 assert( locktype<=SHARED_LOCK );
1949
1950 /* no-op if possible */
1951 if( pFile->locktype==locktype ){
1952 return SQLITE_OK;
1953 }
drh7708e972008-11-29 00:56:52 +00001954
1955 /* To downgrade to shared, simply update our internal notion of the
1956 ** lock state. No need to mess with the file on disk.
1957 */
1958 if( locktype==SHARED_LOCK ){
1959 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001960 return SQLITE_OK;
1961 }
1962
drh7708e972008-11-29 00:56:52 +00001963 /* To fully unlock the database, delete the lock file */
1964 assert( locktype==NO_LOCK );
1965 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001966 int rc = 0;
1967 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001968 if( ENOENT != tErrno ){
1969 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1970 }
1971 if( IS_LOCK_ERROR(rc) ){
1972 pFile->lastErrno = tErrno;
1973 }
1974 return rc;
1975 }
1976 pFile->locktype = NO_LOCK;
1977 return SQLITE_OK;
1978}
1979
1980/*
drh9b35ea62008-11-29 02:20:26 +00001981** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001982*/
1983static int dotlockClose(sqlite3_file *id) {
1984 int rc;
1985 if( id ){
1986 unixFile *pFile = (unixFile*)id;
1987 dotlockUnlock(id, NO_LOCK);
1988 sqlite3_free(pFile->lockingContext);
1989 }
drh734c9862008-11-28 15:37:20 +00001990 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001991 return rc;
1992}
1993/****************** End of the dot-file lock implementation *******************
1994******************************************************************************/
1995
1996/******************************************************************************
1997************************** Begin flock Locking ********************************
1998**
1999** Use the flock() system call to do file locking.
2000**
drh6b9d6dd2008-12-03 19:34:47 +00002001** flock() locking is like dot-file locking in that the various
2002** fine-grain locking levels supported by SQLite are collapsed into
2003** a single exclusive lock. In other words, SHARED, RESERVED, and
2004** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2005** still works when you do this, but concurrency is reduced since
2006** only a single process can be reading the database at a time.
2007**
drh734c9862008-11-28 15:37:20 +00002008** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2009** compiling for VXWORKS.
2010*/
2011#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002012
drh6b9d6dd2008-12-03 19:34:47 +00002013/*
2014** This routine checks if there is a RESERVED lock held on the specified
2015** file by this or any other process. If such a lock is held, set *pResOut
2016** to a non-zero value otherwise *pResOut is set to zero. The return value
2017** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2018*/
drh734c9862008-11-28 15:37:20 +00002019static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2020 int rc = SQLITE_OK;
2021 int reserved = 0;
2022 unixFile *pFile = (unixFile*)id;
2023
2024 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2025
2026 assert( pFile );
2027
2028 /* Check if a thread in this process holds such a lock */
2029 if( pFile->locktype>SHARED_LOCK ){
2030 reserved = 1;
2031 }
2032
2033 /* Otherwise see if some other process holds it. */
2034 if( !reserved ){
2035 /* attempt to get the lock */
2036 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2037 if( !lrc ){
2038 /* got the lock, unlock it */
2039 lrc = flock(pFile->h, LOCK_UN);
2040 if ( lrc ) {
2041 int tErrno = errno;
2042 /* unlock failed with an error */
2043 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2044 if( IS_LOCK_ERROR(lrc) ){
2045 pFile->lastErrno = tErrno;
2046 rc = lrc;
2047 }
2048 }
2049 } else {
2050 int tErrno = errno;
2051 reserved = 1;
2052 /* someone else might have it reserved */
2053 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2054 if( IS_LOCK_ERROR(lrc) ){
2055 pFile->lastErrno = tErrno;
2056 rc = lrc;
2057 }
2058 }
2059 }
drh476bda72009-12-04 14:25:18 +00002060 OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002061
2062#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2063 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2064 rc = SQLITE_OK;
2065 reserved=1;
2066 }
2067#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2068 *pResOut = reserved;
2069 return rc;
2070}
2071
drh6b9d6dd2008-12-03 19:34:47 +00002072/*
2073** Lock the file with the lock specified by parameter locktype - one
2074** of the following:
2075**
2076** (1) SHARED_LOCK
2077** (2) RESERVED_LOCK
2078** (3) PENDING_LOCK
2079** (4) EXCLUSIVE_LOCK
2080**
2081** Sometimes when requesting one lock state, additional lock states
2082** are inserted in between. The locking might fail on one of the later
2083** transitions leaving the lock state different from what it started but
2084** still short of its goal. The following chart shows the allowed
2085** transitions and the inserted intermediate states:
2086**
2087** UNLOCKED -> SHARED
2088** SHARED -> RESERVED
2089** SHARED -> (PENDING) -> EXCLUSIVE
2090** RESERVED -> (PENDING) -> EXCLUSIVE
2091** PENDING -> EXCLUSIVE
2092**
2093** flock() only really support EXCLUSIVE locks. We track intermediate
2094** lock states in the sqlite3_file structure, but all locks SHARED or
2095** above are really EXCLUSIVE locks and exclude all other processes from
2096** access the file.
2097**
2098** This routine will only increase a lock. Use the sqlite3OsUnlock()
2099** routine to lower a locking level.
2100*/
drh734c9862008-11-28 15:37:20 +00002101static int flockLock(sqlite3_file *id, int locktype) {
2102 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002103 unixFile *pFile = (unixFile*)id;
2104
2105 assert( pFile );
2106
2107 /* if we already have a lock, it is exclusive.
2108 ** Just adjust level and punt on outta here. */
2109 if (pFile->locktype > NO_LOCK) {
2110 pFile->locktype = locktype;
2111 return SQLITE_OK;
2112 }
2113
2114 /* grab an exclusive lock */
2115
2116 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2117 int tErrno = errno;
2118 /* didn't get, must be busy */
2119 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2120 if( IS_LOCK_ERROR(rc) ){
2121 pFile->lastErrno = tErrno;
2122 }
2123 } else {
2124 /* got it, set the type and return ok */
2125 pFile->locktype = locktype;
2126 }
drh476bda72009-12-04 14:25:18 +00002127 OSTRACE4("LOCK %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
drh734c9862008-11-28 15:37:20 +00002128 rc==SQLITE_OK ? "ok" : "failed");
2129#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2130 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2131 rc = SQLITE_BUSY;
2132 }
2133#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2134 return rc;
2135}
2136
drh6b9d6dd2008-12-03 19:34:47 +00002137
2138/*
2139** Lower the locking level on file descriptor pFile to locktype. locktype
2140** must be either NO_LOCK or SHARED_LOCK.
2141**
2142** If the locking level of the file descriptor is already at or below
2143** the requested locking level, this routine is a no-op.
2144*/
drh734c9862008-11-28 15:37:20 +00002145static int flockUnlock(sqlite3_file *id, int locktype) {
2146 unixFile *pFile = (unixFile*)id;
2147
2148 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002149 OSTRACE5("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002150 pFile->locktype, getpid());
2151 assert( locktype<=SHARED_LOCK );
2152
2153 /* no-op if possible */
2154 if( pFile->locktype==locktype ){
2155 return SQLITE_OK;
2156 }
2157
2158 /* shared can just be set because we always have an exclusive */
2159 if (locktype==SHARED_LOCK) {
2160 pFile->locktype = locktype;
2161 return SQLITE_OK;
2162 }
2163
2164 /* no, really, unlock. */
2165 int rc = flock(pFile->h, LOCK_UN);
2166 if (rc) {
2167 int r, tErrno = errno;
2168 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2169 if( IS_LOCK_ERROR(r) ){
2170 pFile->lastErrno = tErrno;
2171 }
2172#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2173 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2174 r = SQLITE_BUSY;
2175 }
2176#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2177
2178 return r;
2179 } else {
2180 pFile->locktype = NO_LOCK;
2181 return SQLITE_OK;
2182 }
2183}
2184
2185/*
2186** Close a file.
2187*/
2188static int flockClose(sqlite3_file *id) {
2189 if( id ){
2190 flockUnlock(id, NO_LOCK);
2191 }
2192 return closeUnixFile(id);
2193}
2194
2195#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2196
2197/******************* End of the flock lock implementation *********************
2198******************************************************************************/
2199
2200/******************************************************************************
2201************************ Begin Named Semaphore Locking ************************
2202**
2203** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002204**
2205** Semaphore locking is like dot-lock and flock in that it really only
2206** supports EXCLUSIVE locking. Only a single process can read or write
2207** the database file at a time. This reduces potential concurrency, but
2208** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002209*/
2210#if OS_VXWORKS
2211
drh6b9d6dd2008-12-03 19:34:47 +00002212/*
2213** This routine checks if there is a RESERVED lock held on the specified
2214** file by this or any other process. If such a lock is held, set *pResOut
2215** to a non-zero value otherwise *pResOut is set to zero. The return value
2216** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2217*/
drh734c9862008-11-28 15:37:20 +00002218static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2219 int rc = SQLITE_OK;
2220 int reserved = 0;
2221 unixFile *pFile = (unixFile*)id;
2222
2223 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2224
2225 assert( pFile );
2226
2227 /* Check if a thread in this process holds such a lock */
2228 if( pFile->locktype>SHARED_LOCK ){
2229 reserved = 1;
2230 }
2231
2232 /* Otherwise see if some other process holds it. */
2233 if( !reserved ){
2234 sem_t *pSem = pFile->pOpen->pSem;
2235 struct stat statBuf;
2236
2237 if( sem_trywait(pSem)==-1 ){
2238 int tErrno = errno;
2239 if( EAGAIN != tErrno ){
2240 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2241 pFile->lastErrno = tErrno;
2242 } else {
2243 /* someone else has the lock when we are in NO_LOCK */
2244 reserved = (pFile->locktype < SHARED_LOCK);
2245 }
2246 }else{
2247 /* we could have it if we want it */
2248 sem_post(pSem);
2249 }
2250 }
drh476bda72009-12-04 14:25:18 +00002251 OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002252
2253 *pResOut = reserved;
2254 return rc;
2255}
2256
drh6b9d6dd2008-12-03 19:34:47 +00002257/*
2258** Lock the file with the lock specified by parameter locktype - one
2259** of the following:
2260**
2261** (1) SHARED_LOCK
2262** (2) RESERVED_LOCK
2263** (3) PENDING_LOCK
2264** (4) EXCLUSIVE_LOCK
2265**
2266** Sometimes when requesting one lock state, additional lock states
2267** are inserted in between. The locking might fail on one of the later
2268** transitions leaving the lock state different from what it started but
2269** still short of its goal. The following chart shows the allowed
2270** transitions and the inserted intermediate states:
2271**
2272** UNLOCKED -> SHARED
2273** SHARED -> RESERVED
2274** SHARED -> (PENDING) -> EXCLUSIVE
2275** RESERVED -> (PENDING) -> EXCLUSIVE
2276** PENDING -> EXCLUSIVE
2277**
2278** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2279** lock states in the sqlite3_file structure, but all locks SHARED or
2280** above are really EXCLUSIVE locks and exclude all other processes from
2281** access the file.
2282**
2283** This routine will only increase a lock. Use the sqlite3OsUnlock()
2284** routine to lower a locking level.
2285*/
drh734c9862008-11-28 15:37:20 +00002286static int semLock(sqlite3_file *id, int locktype) {
2287 unixFile *pFile = (unixFile*)id;
2288 int fd;
2289 sem_t *pSem = pFile->pOpen->pSem;
2290 int rc = SQLITE_OK;
2291
2292 /* if we already have a lock, it is exclusive.
2293 ** Just adjust level and punt on outta here. */
2294 if (pFile->locktype > NO_LOCK) {
2295 pFile->locktype = locktype;
2296 rc = SQLITE_OK;
2297 goto sem_end_lock;
2298 }
2299
2300 /* lock semaphore now but bail out when already locked. */
2301 if( sem_trywait(pSem)==-1 ){
2302 rc = SQLITE_BUSY;
2303 goto sem_end_lock;
2304 }
2305
2306 /* got it, set the type and return ok */
2307 pFile->locktype = locktype;
2308
2309 sem_end_lock:
2310 return rc;
2311}
2312
drh6b9d6dd2008-12-03 19:34:47 +00002313/*
2314** Lower the locking level on file descriptor pFile to locktype. locktype
2315** must be either NO_LOCK or SHARED_LOCK.
2316**
2317** If the locking level of the file descriptor is already at or below
2318** the requested locking level, this routine is a no-op.
2319*/
drh734c9862008-11-28 15:37:20 +00002320static int semUnlock(sqlite3_file *id, int locktype) {
2321 unixFile *pFile = (unixFile*)id;
2322 sem_t *pSem = pFile->pOpen->pSem;
2323
2324 assert( pFile );
2325 assert( pSem );
drh476bda72009-12-04 14:25:18 +00002326 OSTRACE5("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002327 pFile->locktype, getpid());
2328 assert( locktype<=SHARED_LOCK );
2329
2330 /* no-op if possible */
2331 if( pFile->locktype==locktype ){
2332 return SQLITE_OK;
2333 }
2334
2335 /* shared can just be set because we always have an exclusive */
2336 if (locktype==SHARED_LOCK) {
2337 pFile->locktype = locktype;
2338 return SQLITE_OK;
2339 }
2340
2341 /* no, really unlock. */
2342 if ( sem_post(pSem)==-1 ) {
2343 int rc, tErrno = errno;
2344 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2345 if( IS_LOCK_ERROR(rc) ){
2346 pFile->lastErrno = tErrno;
2347 }
2348 return rc;
2349 }
2350 pFile->locktype = NO_LOCK;
2351 return SQLITE_OK;
2352}
2353
2354/*
2355 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002356 */
drh734c9862008-11-28 15:37:20 +00002357static int semClose(sqlite3_file *id) {
2358 if( id ){
2359 unixFile *pFile = (unixFile*)id;
2360 semUnlock(id, NO_LOCK);
2361 assert( pFile );
2362 unixEnterMutex();
2363 releaseLockInfo(pFile->pLock);
2364 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002365 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002366 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002367 }
2368 return SQLITE_OK;
2369}
2370
2371#endif /* OS_VXWORKS */
2372/*
2373** Named semaphore locking is only available on VxWorks.
2374**
2375*************** End of the named semaphore lock implementation ****************
2376******************************************************************************/
2377
2378
2379/******************************************************************************
2380*************************** Begin AFP Locking *********************************
2381**
2382** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2383** on Apple Macintosh computers - both OS9 and OSX.
2384**
2385** Third-party implementations of AFP are available. But this code here
2386** only works on OSX.
2387*/
2388
drhd2cb50b2009-01-09 21:41:17 +00002389#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002390/*
2391** The afpLockingContext structure contains all afp lock specific state
2392*/
drhbfe66312006-10-03 17:40:40 +00002393typedef struct afpLockingContext afpLockingContext;
2394struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002395 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002396 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002397};
2398
2399struct ByteRangeLockPB2
2400{
2401 unsigned long long offset; /* offset to first byte to lock */
2402 unsigned long long length; /* nbr of bytes to lock */
2403 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2404 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2405 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2406 int fd; /* file desc to assoc this lock with */
2407};
2408
drhfd131da2007-08-07 17:13:03 +00002409#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002410
drh6b9d6dd2008-12-03 19:34:47 +00002411/*
2412** This is a utility for setting or clearing a bit-range lock on an
2413** AFP filesystem.
2414**
2415** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2416*/
2417static int afpSetLock(
2418 const char *path, /* Name of the file to be locked or unlocked */
2419 unixFile *pFile, /* Open file descriptor on path */
2420 unsigned long long offset, /* First byte to be locked */
2421 unsigned long long length, /* Number of bytes to lock */
2422 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002423){
drh6b9d6dd2008-12-03 19:34:47 +00002424 struct ByteRangeLockPB2 pb;
2425 int err;
drhbfe66312006-10-03 17:40:40 +00002426
2427 pb.unLockFlag = setLockFlag ? 0 : 1;
2428 pb.startEndFlag = 0;
2429 pb.offset = offset;
2430 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002431 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002432
2433 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002434 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2435 offset, length);
drhbfe66312006-10-03 17:40:40 +00002436 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2437 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002438 int rc;
2439 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002440 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2441 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002442#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2443 rc = SQLITE_BUSY;
2444#else
drh734c9862008-11-28 15:37:20 +00002445 rc = sqliteErrorFromPosixError(tErrno,
2446 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002447#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002448 if( IS_LOCK_ERROR(rc) ){
2449 pFile->lastErrno = tErrno;
2450 }
2451 return rc;
drhbfe66312006-10-03 17:40:40 +00002452 } else {
aswift5b1a2562008-08-22 00:22:35 +00002453 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002454 }
2455}
2456
drh6b9d6dd2008-12-03 19:34:47 +00002457/*
2458** This routine checks if there is a RESERVED lock held on the specified
2459** file by this or any other process. If such a lock is held, set *pResOut
2460** to a non-zero value otherwise *pResOut is set to zero. The return value
2461** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2462*/
danielk1977e339d652008-06-28 11:23:00 +00002463static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002464 int rc = SQLITE_OK;
2465 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002466 unixFile *pFile = (unixFile*)id;
2467
aswift5b1a2562008-08-22 00:22:35 +00002468 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2469
2470 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002471 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002472 if( context->reserved ){
2473 *pResOut = 1;
2474 return SQLITE_OK;
2475 }
2476 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002477
2478 /* Check if a thread in this process holds such a lock */
drh7ed97b92010-01-20 13:07:21 +00002479 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002480 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002481 }
2482
2483 /* Otherwise see if some other process holds it.
2484 */
aswift5b1a2562008-08-22 00:22:35 +00002485 if( !reserved ){
2486 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002487 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002488 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002489 /* if we succeeded in taking the reserved lock, unlock it to restore
2490 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002491 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002492 } else {
2493 /* if we failed to get the lock then someone else must have it */
2494 reserved = 1;
2495 }
2496 if( IS_LOCK_ERROR(lrc) ){
2497 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002498 }
2499 }
drhbfe66312006-10-03 17:40:40 +00002500
drh7ed97b92010-01-20 13:07:21 +00002501 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002502 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
aswift5b1a2562008-08-22 00:22:35 +00002503
2504 *pResOut = reserved;
2505 return rc;
drhbfe66312006-10-03 17:40:40 +00002506}
2507
drh6b9d6dd2008-12-03 19:34:47 +00002508/*
2509** Lock the file with the lock specified by parameter locktype - one
2510** of the following:
2511**
2512** (1) SHARED_LOCK
2513** (2) RESERVED_LOCK
2514** (3) PENDING_LOCK
2515** (4) EXCLUSIVE_LOCK
2516**
2517** Sometimes when requesting one lock state, additional lock states
2518** are inserted in between. The locking might fail on one of the later
2519** transitions leaving the lock state different from what it started but
2520** still short of its goal. The following chart shows the allowed
2521** transitions and the inserted intermediate states:
2522**
2523** UNLOCKED -> SHARED
2524** SHARED -> RESERVED
2525** SHARED -> (PENDING) -> EXCLUSIVE
2526** RESERVED -> (PENDING) -> EXCLUSIVE
2527** PENDING -> EXCLUSIVE
2528**
2529** This routine will only increase a lock. Use the sqlite3OsUnlock()
2530** routine to lower a locking level.
2531*/
danielk1977e339d652008-06-28 11:23:00 +00002532static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002533 int rc = SQLITE_OK;
2534 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002535 struct unixLockInfo *pLock = pFile->pLock;
drhbfe66312006-10-03 17:40:40 +00002536 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002537
2538 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002539 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2540 locktypeName(locktype), locktypeName(pFile->locktype),
2541 locktypeName(pLock->locktype), pLock->cnt , getpid());
drh339eb0b2008-03-07 15:34:11 +00002542
drhbfe66312006-10-03 17:40:40 +00002543 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002544 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002545 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002546 */
drhbfe66312006-10-03 17:40:40 +00002547 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00002548 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002549 locktypeName(locktype));
2550 return SQLITE_OK;
2551 }
2552
2553 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002554 ** (1) We never move from unlocked to anything higher than shared lock.
2555 ** (2) SQLite never explicitly requests a pendig lock.
2556 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002557 */
drhbfe66312006-10-03 17:40:40 +00002558 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2559 assert( locktype!=PENDING_LOCK );
2560 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2561
2562 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002563 */
drh6c7d5c52008-11-21 20:32:33 +00002564 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002565
2566 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002567 */
drhbfe66312006-10-03 17:40:40 +00002568 rc = transferOwnership(pFile);
2569 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002570 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002571 return rc;
2572 }
drh7ed97b92010-01-20 13:07:21 +00002573 pLock = pFile->pLock;
2574
2575 /* If some thread using this PID has a lock via a different unixFile*
2576 ** handle that precludes the requested lock, return BUSY.
2577 */
2578 if( (pFile->locktype!=pLock->locktype &&
2579 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
2580 ){
2581 rc = SQLITE_BUSY;
2582 goto afp_end_lock;
2583 }
2584
2585 /* If a SHARED lock is requested, and some thread using this PID already
2586 ** has a SHARED or RESERVED lock, then increment reference counts and
2587 ** return SQLITE_OK.
2588 */
2589 if( locktype==SHARED_LOCK &&
2590 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
2591 assert( locktype==SHARED_LOCK );
2592 assert( pFile->locktype==0 );
2593 assert( pLock->cnt>0 );
2594 pFile->locktype = SHARED_LOCK;
2595 pLock->cnt++;
2596 pFile->pOpen->nLock++;
2597 goto afp_end_lock;
2598 }
drhbfe66312006-10-03 17:40:40 +00002599
2600 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002601 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2602 ** be released.
2603 */
drhbfe66312006-10-03 17:40:40 +00002604 if( locktype==SHARED_LOCK
2605 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002606 ){
2607 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002608 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002609 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002610 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002611 goto afp_end_lock;
2612 }
2613 }
2614
2615 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002616 ** operating system calls for the specified lock.
2617 */
drhbfe66312006-10-03 17:40:40 +00002618 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002619 int lrc1, lrc2, lrc1Errno;
2620 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002621
drh7ed97b92010-01-20 13:07:21 +00002622 assert( pLock->cnt==0 );
2623 assert( pLock->locktype==0 );
2624
2625 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002626 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002627 /* note that the quality of the randomness doesn't matter that much */
2628 lk = random();
drh7ed97b92010-01-20 13:07:21 +00002629 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002630 lrc1 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002631 SHARED_FIRST+pLock->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002632 if( IS_LOCK_ERROR(lrc1) ){
2633 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002634 }
aswift5b1a2562008-08-22 00:22:35 +00002635 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002636 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002637
aswift5b1a2562008-08-22 00:22:35 +00002638 if( IS_LOCK_ERROR(lrc1) ) {
2639 pFile->lastErrno = lrc1Errno;
2640 rc = lrc1;
2641 goto afp_end_lock;
2642 } else if( IS_LOCK_ERROR(lrc2) ){
2643 rc = lrc2;
2644 goto afp_end_lock;
2645 } else if( lrc1 != SQLITE_OK ) {
2646 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002647 } else {
2648 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002649 pFile->pOpen->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002650 pLock->cnt = 1;
drhbfe66312006-10-03 17:40:40 +00002651 }
drh7ed97b92010-01-20 13:07:21 +00002652 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
2653 /* We are trying for an exclusive lock but another thread in this
2654 ** same process is still holding a shared lock. */
2655 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002656 }else{
2657 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2658 ** assumed that there is a SHARED or greater lock on the file
2659 ** already.
2660 */
2661 int failed = 0;
2662 assert( 0!=pFile->locktype );
2663 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2664 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002665 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002666 if( !failed ){
2667 context->reserved = 1;
2668 }
drhbfe66312006-10-03 17:40:40 +00002669 }
2670 if (!failed && locktype == EXCLUSIVE_LOCK) {
2671 /* Acquire an EXCLUSIVE lock */
2672
2673 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002674 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002675 */
drh6b9d6dd2008-12-03 19:34:47 +00002676 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh7ed97b92010-01-20 13:07:21 +00002677 pLock->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002678 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002679 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002680 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002681 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002682 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002683 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002684 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2685 ** a critical I/O error
2686 */
2687 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2688 SQLITE_IOERR_LOCK;
2689 goto afp_end_lock;
2690 }
2691 }else{
aswift5b1a2562008-08-22 00:22:35 +00002692 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002693 }
2694 }
aswift5b1a2562008-08-22 00:22:35 +00002695 if( failed ){
2696 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002697 }
2698 }
2699
2700 if( rc==SQLITE_OK ){
2701 pFile->locktype = locktype;
drh7ed97b92010-01-20 13:07:21 +00002702 pLock->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002703 }else if( locktype==EXCLUSIVE_LOCK ){
2704 pFile->locktype = PENDING_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002705 pLock->locktype = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002706 }
2707
2708afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002709 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002710 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002711 rc==SQLITE_OK ? "ok" : "failed");
2712 return rc;
2713}
2714
2715/*
drh339eb0b2008-03-07 15:34:11 +00002716** Lower the locking level on file descriptor pFile to locktype. locktype
2717** must be either NO_LOCK or SHARED_LOCK.
2718**
2719** If the locking level of the file descriptor is already at or below
2720** the requested locking level, this routine is a no-op.
2721*/
danielk1977e339d652008-06-28 11:23:00 +00002722static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002723 int rc = SQLITE_OK;
2724 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002725 struct unixLockInfo *pLock;
2726 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2727 int skipShared = 0;
2728#ifdef SQLITE_TEST
2729 int h = pFile->h;
2730#endif
drhbfe66312006-10-03 17:40:40 +00002731
2732 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002733 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
2734 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002735
drhbfe66312006-10-03 17:40:40 +00002736 assert( locktype<=SHARED_LOCK );
2737 if( pFile->locktype<=locktype ){
2738 return SQLITE_OK;
2739 }
2740 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00002741 return SQLITE_MISUSE_BKPT;
drhbfe66312006-10-03 17:40:40 +00002742 }
drh6c7d5c52008-11-21 20:32:33 +00002743 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00002744 pLock = pFile->pLock;
2745 assert( pLock->cnt!=0 );
drhbfe66312006-10-03 17:40:40 +00002746 if( pFile->locktype>SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002747 assert( pLock->locktype==pFile->locktype );
2748 SimulateIOErrorBenign(1);
2749 SimulateIOError( h=(-1) )
2750 SimulateIOErrorBenign(0);
2751
2752#ifndef NDEBUG
2753 /* When reducing a lock such that other processes can start
2754 ** reading the database file again, make sure that the
2755 ** transaction counter was updated if any part of the database
2756 ** file changed. If the transaction counter is not updated,
2757 ** other connections to the same file might not realize that
2758 ** the file has changed and hence might not know to flush their
2759 ** cache. The use of a stale cache can lead to database corruption.
2760 */
2761 assert( pFile->inNormalWrite==0
2762 || pFile->dbUpdate==0
2763 || pFile->transCntrChng==1 );
2764 pFile->inNormalWrite = 0;
2765#endif
aswiftaebf4132008-11-21 00:10:35 +00002766
2767 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002768 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2769 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002770 /* only re-establish the shared lock if necessary */
drh7ed97b92010-01-20 13:07:21 +00002771 int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2772 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2773 } else {
2774 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002775 }
2776 }
2777 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002778 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002779 }
drh7ed97b92010-01-20 13:07:21 +00002780 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
2781 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2782 if( !rc ){
2783 context->reserved = 0;
2784 }
aswiftaebf4132008-11-21 00:10:35 +00002785 }
drh7ed97b92010-01-20 13:07:21 +00002786 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
2787 pLock->locktype = SHARED_LOCK;
2788 }
aswiftaebf4132008-11-21 00:10:35 +00002789 }
drh7ed97b92010-01-20 13:07:21 +00002790 if( rc==SQLITE_OK && locktype==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002791
drh7ed97b92010-01-20 13:07:21 +00002792 /* Decrement the shared lock counter. Release the lock using an
2793 ** OS call only when all threads in this same process have released
2794 ** the lock.
2795 */
2796 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2797 pLock->cnt--;
2798 if( pLock->cnt==0 ){
2799 SimulateIOErrorBenign(1);
2800 SimulateIOError( h=(-1) )
2801 SimulateIOErrorBenign(0);
2802 if( !skipShared ){
2803 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2804 }
2805 if( !rc ){
2806 pLock->locktype = NO_LOCK;
2807 pFile->locktype = NO_LOCK;
2808 }
2809 }
2810 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002811 struct unixOpenCnt *pOpen = pFile->pOpen;
drh7ed97b92010-01-20 13:07:21 +00002812
aswiftaebf4132008-11-21 00:10:35 +00002813 pOpen->nLock--;
2814 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002815 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002816 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002817 }
2818 }
drhbfe66312006-10-03 17:40:40 +00002819 }
drh7ed97b92010-01-20 13:07:21 +00002820
drh6c7d5c52008-11-21 20:32:33 +00002821 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00002822 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002823 return rc;
2824}
2825
2826/*
drh339eb0b2008-03-07 15:34:11 +00002827** Close a file & cleanup AFP specific locking context
2828*/
danielk1977e339d652008-06-28 11:23:00 +00002829static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002830 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002831 if( id ){
2832 unixFile *pFile = (unixFile*)id;
2833 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002834 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002835 if( pFile->pOpen && pFile->pOpen->nLock ){
2836 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002837 ** yet because that would clear those locks. Instead, add the file
2838 ** descriptor to pOpen->aPending. It will be automatically closed when
2839 ** the last lock is cleared.
2840 */
dan08da86a2009-08-21 17:18:03 +00002841 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002842 }
drh7ed97b92010-01-20 13:07:21 +00002843 releaseLockInfo(pFile->pLock);
aswiftaebf4132008-11-21 00:10:35 +00002844 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002845 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002846 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002847 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002848 }
drh7ed97b92010-01-20 13:07:21 +00002849 return rc;
drhbfe66312006-10-03 17:40:40 +00002850}
2851
drhd2cb50b2009-01-09 21:41:17 +00002852#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002853/*
2854** The code above is the AFP lock implementation. The code is specific
2855** to MacOSX and does not work on other unix platforms. No alternative
2856** is available. If you don't compile for a mac, then the "unix-afp"
2857** VFS is not available.
2858**
2859********************* End of the AFP lock implementation **********************
2860******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002861
drh7ed97b92010-01-20 13:07:21 +00002862/******************************************************************************
2863*************************** Begin NFS Locking ********************************/
2864
2865#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2866/*
2867 ** Lower the locking level on file descriptor pFile to locktype. locktype
2868 ** must be either NO_LOCK or SHARED_LOCK.
2869 **
2870 ** If the locking level of the file descriptor is already at or below
2871 ** the requested locking level, this routine is a no-op.
2872 */
2873static int nfsUnlock(sqlite3_file *id, int locktype){
2874 return _posixUnlock(id, locktype, 1);
2875}
2876
2877#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2878/*
2879** The code above is the NFS lock implementation. The code is specific
2880** to MacOSX and does not work on other unix platforms. No alternative
2881** is available.
2882**
2883********************* End of the NFS lock implementation **********************
2884******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002885
2886/******************************************************************************
2887**************** Non-locking sqlite3_file methods *****************************
2888**
2889** The next division contains implementations for all methods of the
2890** sqlite3_file object other than the locking methods. The locking
2891** methods were defined in divisions above (one locking method per
2892** division). Those methods that are common to all locking modes
2893** are gather together into this division.
2894*/
drhbfe66312006-10-03 17:40:40 +00002895
2896/*
drh734c9862008-11-28 15:37:20 +00002897** Seek to the offset passed as the second argument, then read cnt
2898** bytes into pBuf. Return the number of bytes actually read.
2899**
2900** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2901** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2902** one system to another. Since SQLite does not define USE_PREAD
2903** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2904** See tickets #2741 and #2681.
2905**
2906** To avoid stomping the errno value on a failed read the lastErrno value
2907** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002908*/
drh734c9862008-11-28 15:37:20 +00002909static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2910 int got;
drh7ed97b92010-01-20 13:07:21 +00002911#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002912 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002913#endif
drh734c9862008-11-28 15:37:20 +00002914 TIMER_START;
2915#if defined(USE_PREAD)
2916 got = pread(id->h, pBuf, cnt, offset);
2917 SimulateIOError( got = -1 );
2918#elif defined(USE_PREAD64)
2919 got = pread64(id->h, pBuf, cnt, offset);
2920 SimulateIOError( got = -1 );
2921#else
2922 newOffset = lseek(id->h, offset, SEEK_SET);
2923 SimulateIOError( newOffset-- );
2924 if( newOffset!=offset ){
2925 if( newOffset == -1 ){
2926 ((unixFile*)id)->lastErrno = errno;
2927 }else{
2928 ((unixFile*)id)->lastErrno = 0;
2929 }
2930 return -1;
2931 }
2932 got = read(id->h, pBuf, cnt);
2933#endif
2934 TIMER_END;
2935 if( got<0 ){
2936 ((unixFile*)id)->lastErrno = errno;
2937 }
2938 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2939 return got;
drhbfe66312006-10-03 17:40:40 +00002940}
2941
2942/*
drh734c9862008-11-28 15:37:20 +00002943** Read data from a file into a buffer. Return SQLITE_OK if all
2944** bytes were read successfully and SQLITE_IOERR if anything goes
2945** wrong.
drh339eb0b2008-03-07 15:34:11 +00002946*/
drh734c9862008-11-28 15:37:20 +00002947static int unixRead(
2948 sqlite3_file *id,
2949 void *pBuf,
2950 int amt,
2951 sqlite3_int64 offset
2952){
dan08da86a2009-08-21 17:18:03 +00002953 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002954 int got;
2955 assert( id );
drh08c6d442009-02-09 17:34:07 +00002956
dan08da86a2009-08-21 17:18:03 +00002957 /* If this is a database file (not a journal, master-journal or temp
2958 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002959 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002960 || offset>=PENDING_BYTE+512
2961 || offset+amt<=PENDING_BYTE
2962 );
drh08c6d442009-02-09 17:34:07 +00002963
dan08da86a2009-08-21 17:18:03 +00002964 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002965 if( got==amt ){
2966 return SQLITE_OK;
2967 }else if( got<0 ){
2968 /* lastErrno set by seekAndRead */
2969 return SQLITE_IOERR_READ;
2970 }else{
dan08da86a2009-08-21 17:18:03 +00002971 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002972 /* Unread parts of the buffer must be zero-filled */
2973 memset(&((char*)pBuf)[got], 0, amt-got);
2974 return SQLITE_IOERR_SHORT_READ;
2975 }
2976}
2977
2978/*
2979** Seek to the offset in id->offset then read cnt bytes into pBuf.
2980** Return the number of bytes actually read. Update the offset.
2981**
2982** To avoid stomping the errno value on a failed write the lastErrno value
2983** is set before returning.
2984*/
2985static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2986 int got;
drh7ed97b92010-01-20 13:07:21 +00002987#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002988 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002989#endif
drh734c9862008-11-28 15:37:20 +00002990 TIMER_START;
2991#if defined(USE_PREAD)
2992 got = pwrite(id->h, pBuf, cnt, offset);
2993#elif defined(USE_PREAD64)
2994 got = pwrite64(id->h, pBuf, cnt, offset);
2995#else
2996 newOffset = lseek(id->h, offset, SEEK_SET);
2997 if( newOffset!=offset ){
2998 if( newOffset == -1 ){
2999 ((unixFile*)id)->lastErrno = errno;
3000 }else{
3001 ((unixFile*)id)->lastErrno = 0;
3002 }
3003 return -1;
3004 }
3005 got = write(id->h, pBuf, cnt);
3006#endif
3007 TIMER_END;
3008 if( got<0 ){
3009 ((unixFile*)id)->lastErrno = errno;
3010 }
3011
3012 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3013 return got;
3014}
3015
3016
3017/*
3018** Write data from a buffer into a file. Return SQLITE_OK on success
3019** or some other error code on failure.
3020*/
3021static int unixWrite(
3022 sqlite3_file *id,
3023 const void *pBuf,
3024 int amt,
3025 sqlite3_int64 offset
3026){
dan08da86a2009-08-21 17:18:03 +00003027 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003028 int wrote = 0;
3029 assert( id );
3030 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003031
dan08da86a2009-08-21 17:18:03 +00003032 /* If this is a database file (not a journal, master-journal or temp
3033 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00003034 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003035 || offset>=PENDING_BYTE+512
3036 || offset+amt<=PENDING_BYTE
3037 );
drh08c6d442009-02-09 17:34:07 +00003038
drh8f941bc2009-01-14 23:03:40 +00003039#ifndef NDEBUG
3040 /* If we are doing a normal write to a database file (as opposed to
3041 ** doing a hot-journal rollback or a write to some file other than a
3042 ** normal database file) then record the fact that the database
3043 ** has changed. If the transaction counter is modified, record that
3044 ** fact too.
3045 */
dan08da86a2009-08-21 17:18:03 +00003046 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003047 pFile->dbUpdate = 1; /* The database has been modified */
3048 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003049 int rc;
drh8f941bc2009-01-14 23:03:40 +00003050 char oldCntr[4];
3051 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003052 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003053 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003054 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003055 pFile->transCntrChng = 1; /* The transaction counter has changed */
3056 }
3057 }
3058 }
3059#endif
3060
dan08da86a2009-08-21 17:18:03 +00003061 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003062 amt -= wrote;
3063 offset += wrote;
3064 pBuf = &((char*)pBuf)[wrote];
3065 }
3066 SimulateIOError(( wrote=(-1), amt=1 ));
3067 SimulateDiskfullError(( wrote=0, amt=1 ));
3068 if( amt>0 ){
3069 if( wrote<0 ){
3070 /* lastErrno set by seekAndWrite */
3071 return SQLITE_IOERR_WRITE;
3072 }else{
dan08da86a2009-08-21 17:18:03 +00003073 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003074 return SQLITE_FULL;
3075 }
3076 }
3077 return SQLITE_OK;
3078}
3079
3080#ifdef SQLITE_TEST
3081/*
3082** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003083** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003084*/
3085int sqlite3_sync_count = 0;
3086int sqlite3_fullsync_count = 0;
3087#endif
3088
3089/*
drh89240432009-03-25 01:06:01 +00003090** We do not trust systems to provide a working fdatasync(). Some do.
3091** Others do no. To be safe, we will stick with the (slower) fsync().
3092** If you know that your system does support fdatasync() correctly,
3093** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003094*/
drh89240432009-03-25 01:06:01 +00003095#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003096# define fdatasync fsync
3097#endif
3098
3099/*
3100** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3101** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3102** only available on Mac OS X. But that could change.
3103*/
3104#ifdef F_FULLFSYNC
3105# define HAVE_FULLFSYNC 1
3106#else
3107# define HAVE_FULLFSYNC 0
3108#endif
3109
3110
3111/*
3112** The fsync() system call does not work as advertised on many
3113** unix systems. The following procedure is an attempt to make
3114** it work better.
3115**
3116** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3117** for testing when we want to run through the test suite quickly.
3118** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3119** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3120** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003121**
3122** SQLite sets the dataOnly flag if the size of the file is unchanged.
3123** The idea behind dataOnly is that it should only write the file content
3124** to disk, not the inode. We only set dataOnly if the file size is
3125** unchanged since the file size is part of the inode. However,
3126** Ted Ts'o tells us that fdatasync() will also write the inode if the
3127** file size has changed. The only real difference between fdatasync()
3128** and fsync(), Ted tells us, is that fdatasync() will not flush the
3129** inode if the mtime or owner or other inode attributes have changed.
3130** We only care about the file size, not the other file attributes, so
3131** as far as SQLite is concerned, an fdatasync() is always adequate.
3132** So, we always use fdatasync() if it is available, regardless of
3133** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003134*/
3135static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003136 int rc;
drh734c9862008-11-28 15:37:20 +00003137
3138 /* The following "ifdef/elif/else/" block has the same structure as
3139 ** the one below. It is replicated here solely to avoid cluttering
3140 ** up the real code with the UNUSED_PARAMETER() macros.
3141 */
3142#ifdef SQLITE_NO_SYNC
3143 UNUSED_PARAMETER(fd);
3144 UNUSED_PARAMETER(fullSync);
3145 UNUSED_PARAMETER(dataOnly);
3146#elif HAVE_FULLFSYNC
3147 UNUSED_PARAMETER(dataOnly);
3148#else
3149 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003150 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003151#endif
3152
3153 /* Record the number of times that we do a normal fsync() and
3154 ** FULLSYNC. This is used during testing to verify that this procedure
3155 ** gets called with the correct arguments.
3156 */
3157#ifdef SQLITE_TEST
3158 if( fullSync ) sqlite3_fullsync_count++;
3159 sqlite3_sync_count++;
3160#endif
3161
3162 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3163 ** no-op
3164 */
3165#ifdef SQLITE_NO_SYNC
3166 rc = SQLITE_OK;
3167#elif HAVE_FULLFSYNC
3168 if( fullSync ){
3169 rc = fcntl(fd, F_FULLFSYNC, 0);
3170 }else{
3171 rc = 1;
3172 }
3173 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003174 ** It shouldn't be possible for fullfsync to fail on the local
3175 ** file system (on OSX), so failure indicates that FULLFSYNC
3176 ** isn't supported for this file system. So, attempt an fsync
3177 ** and (for now) ignore the overhead of a superfluous fcntl call.
3178 ** It'd be better to detect fullfsync support once and avoid
3179 ** the fcntl call every time sync is called.
3180 */
drh734c9862008-11-28 15:37:20 +00003181 if( rc ) rc = fsync(fd);
3182
drh7ed97b92010-01-20 13:07:21 +00003183#elif defined(__APPLE__)
3184 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3185 ** so currently we default to the macro that redefines fdatasync to fsync
3186 */
3187 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003188#else
drh0b647ff2009-03-21 14:41:04 +00003189 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003190#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003191 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003192 rc = fsync(fd);
3193 }
drh0b647ff2009-03-21 14:41:04 +00003194#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003195#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3196
3197 if( OS_VXWORKS && rc!= -1 ){
3198 rc = 0;
3199 }
chw97185482008-11-17 08:05:31 +00003200 return rc;
drhbfe66312006-10-03 17:40:40 +00003201}
3202
drh734c9862008-11-28 15:37:20 +00003203/*
3204** Make sure all writes to a particular file are committed to disk.
3205**
3206** If dataOnly==0 then both the file itself and its metadata (file
3207** size, access time, etc) are synced. If dataOnly!=0 then only the
3208** file data is synced.
3209**
3210** Under Unix, also make sure that the directory entry for the file
3211** has been created by fsync-ing the directory that contains the file.
3212** If we do not do this and we encounter a power failure, the directory
3213** entry for the journal might not exist after we reboot. The next
3214** SQLite to access the file will not know that the journal exists (because
3215** the directory entry for the journal was never created) and the transaction
3216** will not roll back - possibly leading to database corruption.
3217*/
3218static int unixSync(sqlite3_file *id, int flags){
3219 int rc;
3220 unixFile *pFile = (unixFile*)id;
3221
3222 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3223 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3224
3225 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3226 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3227 || (flags&0x0F)==SQLITE_SYNC_FULL
3228 );
3229
3230 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3231 ** line is to test that doing so does not cause any problems.
3232 */
3233 SimulateDiskfullError( return SQLITE_FULL );
3234
3235 assert( pFile );
3236 OSTRACE2("SYNC %-3d\n", pFile->h);
3237 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3238 SimulateIOError( rc=1 );
3239 if( rc ){
3240 pFile->lastErrno = errno;
3241 return SQLITE_IOERR_FSYNC;
3242 }
3243 if( pFile->dirfd>=0 ){
3244 int err;
3245 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3246 HAVE_FULLFSYNC, isFullsync);
3247#ifndef SQLITE_DISABLE_DIRSYNC
3248 /* The directory sync is only attempted if full_fsync is
3249 ** turned off or unavailable. If a full_fsync occurred above,
3250 ** then the directory sync is superfluous.
3251 */
3252 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3253 /*
3254 ** We have received multiple reports of fsync() returning
3255 ** errors when applied to directories on certain file systems.
3256 ** A failed directory sync is not a big deal. So it seems
3257 ** better to ignore the error. Ticket #1657
3258 */
3259 /* pFile->lastErrno = errno; */
3260 /* return SQLITE_IOERR; */
3261 }
3262#endif
3263 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3264 if( err==0 ){ /* directory when we are done */
3265 pFile->dirfd = -1;
3266 }else{
3267 pFile->lastErrno = errno;
3268 rc = SQLITE_IOERR_DIR_CLOSE;
3269 }
3270 }
3271 return rc;
3272}
3273
3274/*
3275** Truncate an open file to a specified size
3276*/
3277static int unixTruncate(sqlite3_file *id, i64 nByte){
3278 int rc;
3279 assert( id );
3280 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3281 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3282 if( rc ){
3283 ((unixFile*)id)->lastErrno = errno;
3284 return SQLITE_IOERR_TRUNCATE;
3285 }else{
drh3313b142009-11-06 04:13:18 +00003286#ifndef NDEBUG
3287 /* If we are doing a normal write to a database file (as opposed to
3288 ** doing a hot-journal rollback or a write to some file other than a
3289 ** normal database file) and we truncate the file to zero length,
3290 ** that effectively updates the change counter. This might happen
3291 ** when restoring a database using the backup API from a zero-length
3292 ** source.
3293 */
3294 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3295 ((unixFile*)id)->transCntrChng = 1;
3296 }
3297#endif
3298
drh734c9862008-11-28 15:37:20 +00003299 return SQLITE_OK;
3300 }
3301}
3302
3303/*
3304** Determine the current size of a file in bytes
3305*/
3306static int unixFileSize(sqlite3_file *id, i64 *pSize){
3307 int rc;
3308 struct stat buf;
3309 assert( id );
3310 rc = fstat(((unixFile*)id)->h, &buf);
3311 SimulateIOError( rc=1 );
3312 if( rc!=0 ){
3313 ((unixFile*)id)->lastErrno = errno;
3314 return SQLITE_IOERR_FSTAT;
3315 }
3316 *pSize = buf.st_size;
3317
3318 /* When opening a zero-size database, the findLockInfo() procedure
3319 ** writes a single byte into that file in order to work around a bug
3320 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3321 ** layers, we need to report this file size as zero even though it is
3322 ** really 1. Ticket #3260.
3323 */
3324 if( *pSize==1 ) *pSize = 0;
3325
3326
3327 return SQLITE_OK;
3328}
3329
drhd2cb50b2009-01-09 21:41:17 +00003330#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003331/*
3332** Handler for proxy-locking file-control verbs. Defined below in the
3333** proxying locking division.
3334*/
3335static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003336#endif
drh715ff302008-12-03 22:32:44 +00003337
danielk1977ad94b582007-08-20 06:44:22 +00003338
danielk1977e3026632004-06-22 11:29:02 +00003339/*
drh9e33c2c2007-08-31 18:34:59 +00003340** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003341*/
drhcc6bb3e2007-08-31 16:11:35 +00003342static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003343 switch( op ){
3344 case SQLITE_FCNTL_LOCKSTATE: {
3345 *(int*)pArg = ((unixFile*)id)->locktype;
3346 return SQLITE_OK;
3347 }
drh7708e972008-11-29 00:56:52 +00003348 case SQLITE_LAST_ERRNO: {
3349 *(int*)pArg = ((unixFile*)id)->lastErrno;
3350 return SQLITE_OK;
3351 }
drh8f941bc2009-01-14 23:03:40 +00003352#ifndef NDEBUG
3353 /* The pager calls this method to signal that it has done
3354 ** a rollback and that the database is therefore unchanged and
3355 ** it hence it is OK for the transaction change counter to be
3356 ** unchanged.
3357 */
3358 case SQLITE_FCNTL_DB_UNCHANGED: {
3359 ((unixFile*)id)->dbUpdate = 0;
3360 return SQLITE_OK;
3361 }
3362#endif
drhd2cb50b2009-01-09 21:41:17 +00003363#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003364 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003365 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003366 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003367 }
drhd2cb50b2009-01-09 21:41:17 +00003368#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003369 }
drhcc6bb3e2007-08-31 16:11:35 +00003370 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003371}
3372
3373/*
danielk1977a3d4c882007-03-23 10:08:38 +00003374** Return the sector size in bytes of the underlying block device for
3375** the specified file. This is almost always 512 bytes, but may be
3376** larger for some devices.
3377**
3378** SQLite code assumes this function cannot fail. It also assumes that
3379** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003380** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003381** same for both.
3382*/
danielk1977397d65f2008-11-19 11:35:39 +00003383static int unixSectorSize(sqlite3_file *NotUsed){
3384 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003385 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003386}
3387
danielk197790949c22007-08-17 16:50:38 +00003388/*
danielk1977397d65f2008-11-19 11:35:39 +00003389** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003390*/
danielk1977397d65f2008-11-19 11:35:39 +00003391static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3392 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003393 return 0;
3394}
3395
drh734c9862008-11-28 15:37:20 +00003396/*
3397** Here ends the implementation of all sqlite3_file methods.
3398**
3399********************** End sqlite3_file Methods *******************************
3400******************************************************************************/
3401
3402/*
drh6b9d6dd2008-12-03 19:34:47 +00003403** This division contains definitions of sqlite3_io_methods objects that
3404** implement various file locking strategies. It also contains definitions
3405** of "finder" functions. A finder-function is used to locate the appropriate
3406** sqlite3_io_methods object for a particular database file. The pAppData
3407** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3408** the correct finder-function for that VFS.
3409**
3410** Most finder functions return a pointer to a fixed sqlite3_io_methods
3411** object. The only interesting finder-function is autolockIoFinder, which
3412** looks at the filesystem type and tries to guess the best locking
3413** strategy from that.
3414**
drh1875f7a2008-12-08 18:19:17 +00003415** For finder-funtion F, two objects are created:
3416**
3417** (1) The real finder-function named "FImpt()".
3418**
dane946c392009-08-22 11:39:46 +00003419** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003420**
3421**
3422** A pointer to the F pointer is used as the pAppData value for VFS
3423** objects. We have to do this instead of letting pAppData point
3424** directly at the finder-function since C90 rules prevent a void*
3425** from be cast into a function pointer.
3426**
drh6b9d6dd2008-12-03 19:34:47 +00003427**
drh7708e972008-11-29 00:56:52 +00003428** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003429**
drh7708e972008-11-29 00:56:52 +00003430** * A constant sqlite3_io_methods object call METHOD that has locking
3431** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3432**
3433** * An I/O method finder function called FINDER that returns a pointer
3434** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003435*/
drh7708e972008-11-29 00:56:52 +00003436#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3437static const sqlite3_io_methods METHOD = { \
3438 1, /* iVersion */ \
3439 CLOSE, /* xClose */ \
3440 unixRead, /* xRead */ \
3441 unixWrite, /* xWrite */ \
3442 unixTruncate, /* xTruncate */ \
3443 unixSync, /* xSync */ \
3444 unixFileSize, /* xFileSize */ \
3445 LOCK, /* xLock */ \
3446 UNLOCK, /* xUnlock */ \
3447 CKLOCK, /* xCheckReservedLock */ \
3448 unixFileControl, /* xFileControl */ \
3449 unixSectorSize, /* xSectorSize */ \
3450 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3451}; \
drh0c2694b2009-09-03 16:23:44 +00003452static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3453 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003454 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003455} \
drh0c2694b2009-09-03 16:23:44 +00003456static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003457 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003458
3459/*
3460** Here are all of the sqlite3_io_methods objects for each of the
3461** locking strategies. Functions that return pointers to these methods
3462** are also created.
3463*/
3464IOMETHODS(
3465 posixIoFinder, /* Finder function name */
3466 posixIoMethods, /* sqlite3_io_methods object name */
3467 unixClose, /* xClose method */
3468 unixLock, /* xLock method */
3469 unixUnlock, /* xUnlock method */
3470 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003471)
drh7708e972008-11-29 00:56:52 +00003472IOMETHODS(
3473 nolockIoFinder, /* Finder function name */
3474 nolockIoMethods, /* sqlite3_io_methods object name */
3475 nolockClose, /* xClose method */
3476 nolockLock, /* xLock method */
3477 nolockUnlock, /* xUnlock method */
3478 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003479)
drh7708e972008-11-29 00:56:52 +00003480IOMETHODS(
3481 dotlockIoFinder, /* Finder function name */
3482 dotlockIoMethods, /* sqlite3_io_methods object name */
3483 dotlockClose, /* xClose method */
3484 dotlockLock, /* xLock method */
3485 dotlockUnlock, /* xUnlock method */
3486 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003487)
drh7708e972008-11-29 00:56:52 +00003488
chw78a13182009-04-07 05:35:03 +00003489#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003490IOMETHODS(
3491 flockIoFinder, /* Finder function name */
3492 flockIoMethods, /* sqlite3_io_methods object name */
3493 flockClose, /* xClose method */
3494 flockLock, /* xLock method */
3495 flockUnlock, /* xUnlock method */
3496 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003497)
drh7708e972008-11-29 00:56:52 +00003498#endif
3499
drh6c7d5c52008-11-21 20:32:33 +00003500#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003501IOMETHODS(
3502 semIoFinder, /* Finder function name */
3503 semIoMethods, /* sqlite3_io_methods object name */
3504 semClose, /* xClose method */
3505 semLock, /* xLock method */
3506 semUnlock, /* xUnlock method */
3507 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003508)
aswiftaebf4132008-11-21 00:10:35 +00003509#endif
drh7708e972008-11-29 00:56:52 +00003510
drhd2cb50b2009-01-09 21:41:17 +00003511#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003512IOMETHODS(
3513 afpIoFinder, /* Finder function name */
3514 afpIoMethods, /* sqlite3_io_methods object name */
3515 afpClose, /* xClose method */
3516 afpLock, /* xLock method */
3517 afpUnlock, /* xUnlock method */
3518 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003519)
drh715ff302008-12-03 22:32:44 +00003520#endif
3521
3522/*
3523** The proxy locking method is a "super-method" in the sense that it
3524** opens secondary file descriptors for the conch and lock files and
3525** it uses proxy, dot-file, AFP, and flock() locking methods on those
3526** secondary files. For this reason, the division that implements
3527** proxy locking is located much further down in the file. But we need
3528** to go ahead and define the sqlite3_io_methods and finder function
3529** for proxy locking here. So we forward declare the I/O methods.
3530*/
drhd2cb50b2009-01-09 21:41:17 +00003531#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003532static int proxyClose(sqlite3_file*);
3533static int proxyLock(sqlite3_file*, int);
3534static int proxyUnlock(sqlite3_file*, int);
3535static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003536IOMETHODS(
3537 proxyIoFinder, /* Finder function name */
3538 proxyIoMethods, /* sqlite3_io_methods object name */
3539 proxyClose, /* xClose method */
3540 proxyLock, /* xLock method */
3541 proxyUnlock, /* xUnlock method */
3542 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003543)
aswiftaebf4132008-11-21 00:10:35 +00003544#endif
drh7708e972008-11-29 00:56:52 +00003545
drh7ed97b92010-01-20 13:07:21 +00003546/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3547#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3548IOMETHODS(
3549 nfsIoFinder, /* Finder function name */
3550 nfsIoMethods, /* sqlite3_io_methods object name */
3551 unixClose, /* xClose method */
3552 unixLock, /* xLock method */
3553 nfsUnlock, /* xUnlock method */
3554 unixCheckReservedLock /* xCheckReservedLock method */
3555)
3556#endif
drh7708e972008-11-29 00:56:52 +00003557
drhd2cb50b2009-01-09 21:41:17 +00003558#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003559/*
drh6b9d6dd2008-12-03 19:34:47 +00003560** This "finder" function attempts to determine the best locking strategy
3561** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003562** object that implements that strategy.
3563**
3564** This is for MacOSX only.
3565*/
drh1875f7a2008-12-08 18:19:17 +00003566static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003567 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003568 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003569){
3570 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003571 const char *zFilesystem; /* Filesystem type name */
3572 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003573 } aMap[] = {
3574 { "hfs", &posixIoMethods },
3575 { "ufs", &posixIoMethods },
3576 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003577 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003578 { "webdav", &nolockIoMethods },
3579 { 0, 0 }
3580 };
3581 int i;
3582 struct statfs fsInfo;
3583 struct flock lockInfo;
3584
3585 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003586 /* If filePath==NULL that means we are dealing with a transient file
3587 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003588 return &nolockIoMethods;
3589 }
3590 if( statfs(filePath, &fsInfo) != -1 ){
3591 if( fsInfo.f_flags & MNT_RDONLY ){
3592 return &nolockIoMethods;
3593 }
3594 for(i=0; aMap[i].zFilesystem; i++){
3595 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3596 return aMap[i].pMethods;
3597 }
3598 }
3599 }
3600
3601 /* Default case. Handles, amongst others, "nfs".
3602 ** Test byte-range lock using fcntl(). If the call succeeds,
3603 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003604 */
drh7708e972008-11-29 00:56:52 +00003605 lockInfo.l_len = 1;
3606 lockInfo.l_start = 0;
3607 lockInfo.l_whence = SEEK_SET;
3608 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003609 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003610 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3611 return &nfsIoMethods;
3612 } else {
3613 return &posixIoMethods;
3614 }
drh7708e972008-11-29 00:56:52 +00003615 }else{
3616 return &dotlockIoMethods;
3617 }
3618}
drh0c2694b2009-09-03 16:23:44 +00003619static const sqlite3_io_methods
3620 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003621
drhd2cb50b2009-01-09 21:41:17 +00003622#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003623
chw78a13182009-04-07 05:35:03 +00003624#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3625/*
3626** This "finder" function attempts to determine the best locking strategy
3627** for the database file "filePath". It then returns the sqlite3_io_methods
3628** object that implements that strategy.
3629**
3630** This is for VXWorks only.
3631*/
3632static const sqlite3_io_methods *autolockIoFinderImpl(
3633 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003634 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003635){
3636 struct flock lockInfo;
3637
3638 if( !filePath ){
3639 /* If filePath==NULL that means we are dealing with a transient file
3640 ** that does not need to be locked. */
3641 return &nolockIoMethods;
3642 }
3643
3644 /* Test if fcntl() is supported and use POSIX style locks.
3645 ** Otherwise fall back to the named semaphore method.
3646 */
3647 lockInfo.l_len = 1;
3648 lockInfo.l_start = 0;
3649 lockInfo.l_whence = SEEK_SET;
3650 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003651 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003652 return &posixIoMethods;
3653 }else{
3654 return &semIoMethods;
3655 }
3656}
drh0c2694b2009-09-03 16:23:44 +00003657static const sqlite3_io_methods
3658 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003659
3660#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3661
drh7708e972008-11-29 00:56:52 +00003662/*
3663** An abstract type for a pointer to a IO method finder function:
3664*/
drh0c2694b2009-09-03 16:23:44 +00003665typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003666
aswiftaebf4132008-11-21 00:10:35 +00003667
drh734c9862008-11-28 15:37:20 +00003668/****************************************************************************
3669**************************** sqlite3_vfs methods ****************************
3670**
3671** This division contains the implementation of methods on the
3672** sqlite3_vfs object.
3673*/
3674
danielk1977a3d4c882007-03-23 10:08:38 +00003675/*
danielk1977e339d652008-06-28 11:23:00 +00003676** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003677*/
3678static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003679 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003680 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003681 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003682 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003683 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003684 int noLock, /* Omit locking if true */
3685 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003686){
drh7708e972008-11-29 00:56:52 +00003687 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003688 unixFile *pNew = (unixFile *)pId;
3689 int rc = SQLITE_OK;
3690
danielk197717b90b52008-06-06 11:11:25 +00003691 assert( pNew->pLock==NULL );
3692 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003693
dane946c392009-08-22 11:39:46 +00003694 /* Parameter isDelete is only used on vxworks. Express this explicitly
3695 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003696 */
drh7708e972008-11-29 00:56:52 +00003697 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003698
drh218c5082008-03-07 00:27:10 +00003699 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003700 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003701 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003702 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00003703 pNew->fileFlags = 0;
drh339eb0b2008-03-07 15:34:11 +00003704
drh6c7d5c52008-11-21 20:32:33 +00003705#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003706 pNew->pId = vxworksFindFileId(zFilename);
3707 if( pNew->pId==0 ){
3708 noLock = 1;
3709 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003710 }
3711#endif
3712
drhda0e7682008-07-30 15:27:54 +00003713 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003714 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003715 }else{
drh0c2694b2009-09-03 16:23:44 +00003716 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003717#if SQLITE_ENABLE_LOCKING_STYLE
3718 /* Cache zFilename in the locking context (AFP and dotlock override) for
3719 ** proxyLock activation is possible (remote proxy is based on db name)
3720 ** zFilename remains valid until file is closed, to support */
3721 pNew->lockingContext = (void*)zFilename;
3722#endif
drhda0e7682008-07-30 15:27:54 +00003723 }
danielk1977e339d652008-06-28 11:23:00 +00003724
drh7ed97b92010-01-20 13:07:21 +00003725 if( pLockingStyle == &posixIoMethods
3726#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3727 || pLockingStyle == &nfsIoMethods
3728#endif
3729 ){
drh7708e972008-11-29 00:56:52 +00003730 unixEnterMutex();
3731 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003732 if( rc!=SQLITE_OK ){
3733 /* If an error occured in findLockInfo(), close the file descriptor
3734 ** immediately, before releasing the mutex. findLockInfo() may fail
3735 ** in two scenarios:
3736 **
3737 ** (a) A call to fstat() failed.
3738 ** (b) A malloc failed.
3739 **
3740 ** Scenario (b) may only occur if the process is holding no other
3741 ** file descriptors open on the same file. If there were other file
3742 ** descriptors on this file, then no malloc would be required by
3743 ** findLockInfo(). If this is the case, it is quite safe to close
3744 ** handle h - as it is guaranteed that no posix locks will be released
3745 ** by doing so.
3746 **
3747 ** If scenario (a) caused the error then things are not so safe. The
3748 ** implicit assumption here is that if fstat() fails, things are in
3749 ** such bad shape that dropping a lock or two doesn't matter much.
3750 */
3751 close(h);
3752 h = -1;
3753 }
drh7708e972008-11-29 00:56:52 +00003754 unixLeaveMutex();
3755 }
danielk1977e339d652008-06-28 11:23:00 +00003756
drhd2cb50b2009-01-09 21:41:17 +00003757#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003758 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003759 /* AFP locking uses the file path so it needs to be included in
3760 ** the afpLockingContext.
3761 */
3762 afpLockingContext *pCtx;
3763 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3764 if( pCtx==0 ){
3765 rc = SQLITE_NOMEM;
3766 }else{
3767 /* NB: zFilename exists and remains valid until the file is closed
3768 ** according to requirement F11141. So we do not need to make a
3769 ** copy of the filename. */
3770 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00003771 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00003772 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003773 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00003774 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3775 if( rc!=SQLITE_OK ){
3776 sqlite3_free(pNew->lockingContext);
3777 close(h);
3778 h = -1;
3779 }
drh7708e972008-11-29 00:56:52 +00003780 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003781 }
drh7708e972008-11-29 00:56:52 +00003782 }
3783#endif
danielk1977e339d652008-06-28 11:23:00 +00003784
drh7708e972008-11-29 00:56:52 +00003785 else if( pLockingStyle == &dotlockIoMethods ){
3786 /* Dotfile locking uses the file path so it needs to be included in
3787 ** the dotlockLockingContext
3788 */
3789 char *zLockFile;
3790 int nFilename;
drhea678832008-12-10 19:26:22 +00003791 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003792 zLockFile = (char *)sqlite3_malloc(nFilename);
3793 if( zLockFile==0 ){
3794 rc = SQLITE_NOMEM;
3795 }else{
3796 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003797 }
drh7708e972008-11-29 00:56:52 +00003798 pNew->lockingContext = zLockFile;
3799 }
danielk1977e339d652008-06-28 11:23:00 +00003800
drh6c7d5c52008-11-21 20:32:33 +00003801#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003802 else if( pLockingStyle == &semIoMethods ){
3803 /* Named semaphore locking uses the file path so it needs to be
3804 ** included in the semLockingContext
3805 */
3806 unixEnterMutex();
3807 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3808 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3809 char *zSemName = pNew->pOpen->aSemName;
3810 int n;
drh2238dcc2009-08-27 17:56:20 +00003811 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003812 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003813 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003814 if( zSemName[n]=='/' ) zSemName[n] = '_';
3815 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3816 if( pNew->pOpen->pSem == SEM_FAILED ){
3817 rc = SQLITE_NOMEM;
3818 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003819 }
chw97185482008-11-17 08:05:31 +00003820 }
drh7708e972008-11-29 00:56:52 +00003821 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003822 }
drh7708e972008-11-29 00:56:52 +00003823#endif
aswift5b1a2562008-08-22 00:22:35 +00003824
3825 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003826#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003827 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00003828 if( h>=0 ) close(h);
3829 h = -1;
chw97185482008-11-17 08:05:31 +00003830 unlink(zFilename);
3831 isDelete = 0;
3832 }
3833 pNew->isDelete = isDelete;
3834#endif
danielk1977e339d652008-06-28 11:23:00 +00003835 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003836 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003837 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003838 }else{
drh7708e972008-11-29 00:56:52 +00003839 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003840 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003841 }
danielk1977e339d652008-06-28 11:23:00 +00003842 return rc;
drh054889e2005-11-30 03:20:31 +00003843}
drh9c06c952005-11-26 00:25:00 +00003844
danielk1977ad94b582007-08-20 06:44:22 +00003845/*
3846** Open a file descriptor to the directory containing file zFilename.
3847** If successful, *pFd is set to the opened file descriptor and
3848** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3849** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3850** value.
3851**
3852** If SQLITE_OK is returned, the caller is responsible for closing
3853** the file descriptor *pFd using close().
3854*/
danielk1977fee2d252007-08-18 10:59:19 +00003855static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003856 int ii;
drh777b17a2007-09-20 10:02:54 +00003857 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003858 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003859
drh153c62c2007-08-24 03:51:33 +00003860 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003861 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003862 if( ii>0 ){
3863 zDirname[ii] = '\0';
3864 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003865 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003866#ifdef FD_CLOEXEC
3867 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3868#endif
3869 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3870 }
3871 }
danielk1977fee2d252007-08-18 10:59:19 +00003872 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00003873 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00003874}
3875
danielk1977b4b47412007-08-17 15:53:36 +00003876/*
danielk197717b90b52008-06-06 11:11:25 +00003877** Create a temporary file name in zBuf. zBuf must be allocated
3878** by the calling process and must be big enough to hold at least
3879** pVfs->mxPathname bytes.
3880*/
3881static int getTempname(int nBuf, char *zBuf){
3882 static const char *azDirs[] = {
3883 0,
aswiftaebf4132008-11-21 00:10:35 +00003884 0,
danielk197717b90b52008-06-06 11:11:25 +00003885 "/var/tmp",
3886 "/usr/tmp",
3887 "/tmp",
3888 ".",
3889 };
3890 static const unsigned char zChars[] =
3891 "abcdefghijklmnopqrstuvwxyz"
3892 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3893 "0123456789";
drh41022642008-11-21 00:24:42 +00003894 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003895 struct stat buf;
3896 const char *zDir = ".";
3897
3898 /* It's odd to simulate an io-error here, but really this is just
3899 ** using the io-error infrastructure to test that SQLite handles this
3900 ** function failing.
3901 */
3902 SimulateIOError( return SQLITE_IOERR );
3903
3904 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003905 if (NULL == azDirs[1]) {
3906 azDirs[1] = getenv("TMPDIR");
3907 }
3908
3909 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003910 if( azDirs[i]==0 ) continue;
3911 if( stat(azDirs[i], &buf) ) continue;
3912 if( !S_ISDIR(buf.st_mode) ) continue;
3913 if( access(azDirs[i], 07) ) continue;
3914 zDir = azDirs[i];
3915 break;
3916 }
3917
3918 /* Check that the output buffer is large enough for the temporary file
3919 ** name. If it is not, return SQLITE_ERROR.
3920 */
danielk197700e13612008-11-17 19:18:54 +00003921 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003922 return SQLITE_ERROR;
3923 }
3924
3925 do{
3926 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003927 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003928 sqlite3_randomness(15, &zBuf[j]);
3929 for(i=0; i<15; i++, j++){
3930 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3931 }
3932 zBuf[j] = 0;
3933 }while( access(zBuf,0)==0 );
3934 return SQLITE_OK;
3935}
3936
drhd2cb50b2009-01-09 21:41:17 +00003937#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003938/*
3939** Routine to transform a unixFile into a proxy-locking unixFile.
3940** Implementation in the proxy-lock division, but used by unixOpen()
3941** if SQLITE_PREFER_PROXY_LOCKING is defined.
3942*/
3943static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003944#endif
drhc66d5b62008-12-03 22:48:32 +00003945
dan08da86a2009-08-21 17:18:03 +00003946/*
3947** Search for an unused file descriptor that was opened on the database
3948** file (not a journal or master-journal file) identified by pathname
3949** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3950** argument to this function.
3951**
3952** Such a file descriptor may exist if a database connection was closed
3953** but the associated file descriptor could not be closed because some
3954** other file descriptor open on the same file is holding a file-lock.
3955** Refer to comments in the unixClose() function and the lengthy comment
3956** describing "Posix Advisory Locking" at the start of this file for
3957** further details. Also, ticket #4018.
3958**
3959** If a suitable file descriptor is found, then it is returned. If no
3960** such file descriptor is located, -1 is returned.
3961*/
dane946c392009-08-22 11:39:46 +00003962static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3963 UnixUnusedFd *pUnused = 0;
3964
3965 /* Do not search for an unused file descriptor on vxworks. Not because
3966 ** vxworks would not benefit from the change (it might, we're not sure),
3967 ** but because no way to test it is currently available. It is better
3968 ** not to risk breaking vxworks support for the sake of such an obscure
3969 ** feature. */
3970#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003971 struct stat sStat; /* Results of stat() call */
3972
3973 /* A stat() call may fail for various reasons. If this happens, it is
3974 ** almost certain that an open() call on the same path will also fail.
3975 ** For this reason, if an error occurs in the stat() call here, it is
3976 ** ignored and -1 is returned. The caller will try to open a new file
3977 ** descriptor on the same path, fail, and return an error to SQLite.
3978 **
3979 ** Even if a subsequent open() call does succeed, the consequences of
3980 ** not searching for a resusable file descriptor are not dire. */
3981 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00003982 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00003983
3984 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00003985 pOpen = openList;
3986 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
3987 || pOpen->fileId.ino!=sStat.st_ino) ){
3988 pOpen = pOpen->pNext;
3989 }
3990 if( pOpen ){
dane946c392009-08-22 11:39:46 +00003991 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00003992 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00003993 pUnused = *pp;
3994 if( pUnused ){
3995 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00003996 }
3997 }
3998 unixLeaveMutex();
3999 }
dane946c392009-08-22 11:39:46 +00004000#endif /* if !OS_VXWORKS */
4001 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004002}
danielk197717b90b52008-06-06 11:11:25 +00004003
4004/*
danielk1977ad94b582007-08-20 06:44:22 +00004005** Open the file zPath.
4006**
danielk1977b4b47412007-08-17 15:53:36 +00004007** Previously, the SQLite OS layer used three functions in place of this
4008** one:
4009**
4010** sqlite3OsOpenReadWrite();
4011** sqlite3OsOpenReadOnly();
4012** sqlite3OsOpenExclusive();
4013**
4014** These calls correspond to the following combinations of flags:
4015**
4016** ReadWrite() -> (READWRITE | CREATE)
4017** ReadOnly() -> (READONLY)
4018** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4019**
4020** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4021** true, the file was configured to be automatically deleted when the
4022** file handle closed. To achieve the same effect using this new
4023** interface, add the DELETEONCLOSE flag to those specified above for
4024** OpenExclusive().
4025*/
4026static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004027 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4028 const char *zPath, /* Pathname of file to be opened */
4029 sqlite3_file *pFile, /* The file descriptor to be filled in */
4030 int flags, /* Input flags to control the opening */
4031 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004032){
dan08da86a2009-08-21 17:18:03 +00004033 unixFile *p = (unixFile *)pFile;
4034 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004035 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004036 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004037 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004038 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004039 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004040
4041 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4042 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4043 int isCreate = (flags & SQLITE_OPEN_CREATE);
4044 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4045 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004046#if SQLITE_ENABLE_LOCKING_STYLE
4047 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4048#endif
danielk1977b4b47412007-08-17 15:53:36 +00004049
danielk1977fee2d252007-08-18 10:59:19 +00004050 /* If creating a master or main-file journal, this function will open
4051 ** a file-descriptor on the directory too. The first time unixSync()
4052 ** is called the directory file descriptor will be fsync()ed and close()d.
4053 */
4054 int isOpenDirectory = (isCreate &&
4055 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4056 );
4057
danielk197717b90b52008-06-06 11:11:25 +00004058 /* If argument zPath is a NULL pointer, this function is required to open
4059 ** a temporary file. Use this buffer to store the file name in.
4060 */
4061 char zTmpname[MAX_PATHNAME+1];
4062 const char *zName = zPath;
4063
danielk1977fee2d252007-08-18 10:59:19 +00004064 /* Check the following statements are true:
4065 **
4066 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4067 ** (b) if CREATE is set, then READWRITE must also be set, and
4068 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004069 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004070 */
danielk1977b4b47412007-08-17 15:53:36 +00004071 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004072 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004073 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004074 assert(isDelete==0 || isCreate);
4075
drh33f4e022007-09-03 15:19:34 +00004076 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004077 ** deleted. Nor are they ever temporary files. */
4078 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4079 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4080 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004081
danielk1977fee2d252007-08-18 10:59:19 +00004082 /* Assert that the upper layer has set one of the "file-type" flags. */
4083 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4084 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4085 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004086 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004087 );
4088
dan08da86a2009-08-21 17:18:03 +00004089 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004090
dan08da86a2009-08-21 17:18:03 +00004091 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004092 UnixUnusedFd *pUnused;
4093 pUnused = findReusableFd(zName, flags);
4094 if( pUnused ){
4095 fd = pUnused->fd;
4096 }else{
dan6aa657f2009-08-24 18:57:58 +00004097 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004098 if( !pUnused ){
4099 return SQLITE_NOMEM;
4100 }
4101 }
4102 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004103 }else if( !zName ){
4104 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004105 assert(isDelete && !isOpenDirectory);
4106 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4107 if( rc!=SQLITE_OK ){
4108 return rc;
4109 }
4110 zName = zTmpname;
4111 }
4112
dan08da86a2009-08-21 17:18:03 +00004113 /* Determine the value of the flags parameter passed to POSIX function
4114 ** open(). These must be calculated even if open() is not called, as
4115 ** they may be stored as part of the file handle and used by the
4116 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004117 if( isReadonly ) openFlags |= O_RDONLY;
4118 if( isReadWrite ) openFlags |= O_RDWR;
4119 if( isCreate ) openFlags |= O_CREAT;
4120 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4121 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004122
danielk1977b4b47412007-08-17 15:53:36 +00004123 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004124 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4125 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004126 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
4127 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4128 /* Failed to open the file for read/write access. Try read-only. */
4129 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004130 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004131 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004132 openFlags |= O_RDONLY;
4133 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004134 }
4135 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004136 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004137 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004138 }
danielk1977b4b47412007-08-17 15:53:36 +00004139 }
dan08da86a2009-08-21 17:18:03 +00004140 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004141 if( pOutFlags ){
4142 *pOutFlags = flags;
4143 }
4144
dane946c392009-08-22 11:39:46 +00004145 if( p->pUnused ){
4146 p->pUnused->fd = fd;
4147 p->pUnused->flags = flags;
4148 }
4149
danielk1977b4b47412007-08-17 15:53:36 +00004150 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004151#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004152 zPath = zName;
4153#else
danielk197717b90b52008-06-06 11:11:25 +00004154 unlink(zName);
chw97185482008-11-17 08:05:31 +00004155#endif
danielk1977b4b47412007-08-17 15:53:36 +00004156 }
drh41022642008-11-21 00:24:42 +00004157#if SQLITE_ENABLE_LOCKING_STYLE
4158 else{
dan08da86a2009-08-21 17:18:03 +00004159 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004160 }
4161#endif
4162
danielk1977fee2d252007-08-18 10:59:19 +00004163 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004164 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004165 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004166 /* It is safe to close fd at this point, because it is guaranteed not
4167 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004168 ** it would not be safe to close as this would release any locks held
4169 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004170 assert( eType!=SQLITE_OPEN_MAIN_DB );
4171 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004172 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004173 }
4174 }
danielk1977e339d652008-06-28 11:23:00 +00004175
4176#ifdef FD_CLOEXEC
4177 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4178#endif
4179
drhda0e7682008-07-30 15:27:54 +00004180 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004181
drh7ed97b92010-01-20 13:07:21 +00004182
4183#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4184 struct statfs fsInfo;
4185 if( fstatfs(fd, &fsInfo) == -1 ){
4186 ((unixFile*)pFile)->lastErrno = errno;
4187 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4188 close(fd); /* silently leak if fail, in error */
4189 return SQLITE_IOERR_ACCESS;
4190 }
4191 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4192 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4193 }
4194#endif
4195
4196#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004197#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004198 isAutoProxy = 1;
4199#endif
4200 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004201 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4202 int useProxy = 0;
4203
dan08da86a2009-08-21 17:18:03 +00004204 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4205 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004206 if( envforce!=NULL ){
4207 useProxy = atoi(envforce)>0;
4208 }else{
4209 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004210 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004211 /* In theory, the close(fd) call is sub-optimal. If the file opened
4212 ** with fd is a database file, and there are other connections open
4213 ** on that file that are currently holding advisory locks on it,
4214 ** then the call to close() will cancel those locks. In practice,
4215 ** we're assuming that statfs() doesn't fail very often. At least
4216 ** not while other file descriptors opened by the same process on
4217 ** the same file are working. */
4218 p->lastErrno = errno;
4219 if( dirfd>=0 ){
4220 close(dirfd); /* silently leak if fail, in error */
4221 }
aswiftaebf4132008-11-21 00:10:35 +00004222 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004223 rc = SQLITE_IOERR_ACCESS;
4224 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004225 }
4226 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4227 }
4228 if( useProxy ){
4229 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4230 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004231 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004232 if( rc!=SQLITE_OK ){
4233 /* Use unixClose to clean up the resources added in fillInUnixFile
4234 ** and clear all the structure's references. Specifically,
4235 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4236 */
4237 unixClose(pFile);
4238 return rc;
4239 }
aswiftaebf4132008-11-21 00:10:35 +00004240 }
dane946c392009-08-22 11:39:46 +00004241 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004242 }
4243 }
4244#endif
4245
dane946c392009-08-22 11:39:46 +00004246 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4247open_finished:
4248 if( rc!=SQLITE_OK ){
4249 sqlite3_free(p->pUnused);
4250 }
4251 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004252}
4253
dane946c392009-08-22 11:39:46 +00004254
danielk1977b4b47412007-08-17 15:53:36 +00004255/*
danielk1977fee2d252007-08-18 10:59:19 +00004256** Delete the file at zPath. If the dirSync argument is true, fsync()
4257** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004258*/
drh6b9d6dd2008-12-03 19:34:47 +00004259static int unixDelete(
4260 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4261 const char *zPath, /* Name of file to be deleted */
4262 int dirSync /* If true, fsync() directory after deleting file */
4263){
danielk1977fee2d252007-08-18 10:59:19 +00004264 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004265 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004266 SimulateIOError(return SQLITE_IOERR_DELETE);
4267 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004268#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004269 if( dirSync ){
4270 int fd;
4271 rc = openDirectory(zPath, &fd);
4272 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004273#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004274 if( fsync(fd)==-1 )
4275#else
4276 if( fsync(fd) )
4277#endif
4278 {
danielk1977fee2d252007-08-18 10:59:19 +00004279 rc = SQLITE_IOERR_DIR_FSYNC;
4280 }
aswiftaebf4132008-11-21 00:10:35 +00004281 if( close(fd)&&!rc ){
4282 rc = SQLITE_IOERR_DIR_CLOSE;
4283 }
danielk1977fee2d252007-08-18 10:59:19 +00004284 }
4285 }
danielk1977d138dd82008-10-15 16:02:48 +00004286#endif
danielk1977fee2d252007-08-18 10:59:19 +00004287 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004288}
4289
danielk197790949c22007-08-17 16:50:38 +00004290/*
4291** Test the existance of or access permissions of file zPath. The
4292** test performed depends on the value of flags:
4293**
4294** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4295** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4296** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4297**
4298** Otherwise return 0.
4299*/
danielk1977861f7452008-06-05 11:39:11 +00004300static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004301 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4302 const char *zPath, /* Path of the file to examine */
4303 int flags, /* What do we want to learn about the zPath file? */
4304 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004305){
rse25c0d1a2007-09-20 08:38:14 +00004306 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004307 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004308 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004309 switch( flags ){
4310 case SQLITE_ACCESS_EXISTS:
4311 amode = F_OK;
4312 break;
4313 case SQLITE_ACCESS_READWRITE:
4314 amode = W_OK|R_OK;
4315 break;
drh50d3f902007-08-27 21:10:36 +00004316 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004317 amode = R_OK;
4318 break;
4319
4320 default:
4321 assert(!"Invalid flags argument");
4322 }
danielk1977861f7452008-06-05 11:39:11 +00004323 *pResOut = (access(zPath, amode)==0);
4324 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004325}
4326
danielk1977b4b47412007-08-17 15:53:36 +00004327
4328/*
4329** Turn a relative pathname into a full pathname. The relative path
4330** is stored as a nul-terminated string in the buffer pointed to by
4331** zPath.
4332**
4333** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4334** (in this case, MAX_PATHNAME bytes). The full-path is written to
4335** this buffer before returning.
4336*/
danielk1977adfb9b02007-09-17 07:02:56 +00004337static int unixFullPathname(
4338 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4339 const char *zPath, /* Possibly relative input path */
4340 int nOut, /* Size of output buffer in bytes */
4341 char *zOut /* Output buffer */
4342){
danielk1977843e65f2007-09-01 16:16:15 +00004343
4344 /* It's odd to simulate an io-error here, but really this is just
4345 ** using the io-error infrastructure to test that SQLite handles this
4346 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004347 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004348 */
4349 SimulateIOError( return SQLITE_ERROR );
4350
drh153c62c2007-08-24 03:51:33 +00004351 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004352 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004353
drh3c7f2dc2007-12-06 13:26:20 +00004354 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004355 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004356 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004357 }else{
4358 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004359 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004360 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004361 }
drhea678832008-12-10 19:26:22 +00004362 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004363 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004364 }
4365 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004366}
4367
drh0ccebe72005-06-07 22:22:50 +00004368
drh761df872006-12-21 01:29:22 +00004369#ifndef SQLITE_OMIT_LOAD_EXTENSION
4370/*
4371** Interfaces for opening a shared library, finding entry points
4372** within the shared library, and closing the shared library.
4373*/
4374#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004375static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4376 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004377 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4378}
danielk197795c8a542007-09-01 06:51:27 +00004379
4380/*
4381** SQLite calls this function immediately after a call to unixDlSym() or
4382** unixDlOpen() fails (returns a null pointer). If a more detailed error
4383** message is available, it is written to zBufOut. If no error message
4384** is available, zBufOut is left unmodified and SQLite uses a default
4385** error message.
4386*/
danielk1977397d65f2008-11-19 11:35:39 +00004387static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004388 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004389 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004390 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004391 zErr = dlerror();
4392 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004393 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004394 }
drh6c7d5c52008-11-21 20:32:33 +00004395 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004396}
drh1875f7a2008-12-08 18:19:17 +00004397static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4398 /*
4399 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4400 ** cast into a pointer to a function. And yet the library dlsym() routine
4401 ** returns a void* which is really a pointer to a function. So how do we
4402 ** use dlsym() with -pedantic-errors?
4403 **
4404 ** Variable x below is defined to be a pointer to a function taking
4405 ** parameters void* and const char* and returning a pointer to a function.
4406 ** We initialize x by assigning it a pointer to the dlsym() function.
4407 ** (That assignment requires a cast.) Then we call the function that
4408 ** x points to.
4409 **
4410 ** This work-around is unlikely to work correctly on any system where
4411 ** you really cannot cast a function pointer into void*. But then, on the
4412 ** other hand, dlsym() will not work on such a system either, so we have
4413 ** not really lost anything.
4414 */
4415 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004416 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004417 x = (void(*(*)(void*,const char*))(void))dlsym;
4418 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004419}
danielk1977397d65f2008-11-19 11:35:39 +00004420static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4421 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004422 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004423}
danielk1977b4b47412007-08-17 15:53:36 +00004424#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4425 #define unixDlOpen 0
4426 #define unixDlError 0
4427 #define unixDlSym 0
4428 #define unixDlClose 0
4429#endif
4430
4431/*
danielk197790949c22007-08-17 16:50:38 +00004432** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004433*/
danielk1977397d65f2008-11-19 11:35:39 +00004434static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4435 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004436 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004437
drhbbd42a62004-05-22 17:41:58 +00004438 /* We have to initialize zBuf to prevent valgrind from reporting
4439 ** errors. The reports issued by valgrind are incorrect - we would
4440 ** prefer that the randomness be increased by making use of the
4441 ** uninitialized space in zBuf - but valgrind errors tend to worry
4442 ** some users. Rather than argue, it seems easier just to initialize
4443 ** the whole array and silence valgrind, even if that means less randomness
4444 ** in the random seed.
4445 **
4446 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004447 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004448 ** tests repeatable.
4449 */
danielk1977b4b47412007-08-17 15:53:36 +00004450 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004451#if !defined(SQLITE_TEST)
4452 {
drh842b8642005-01-21 17:53:17 +00004453 int pid, fd;
4454 fd = open("/dev/urandom", O_RDONLY);
4455 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004456 time_t t;
4457 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004458 memcpy(zBuf, &t, sizeof(t));
4459 pid = getpid();
4460 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004461 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004462 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004463 }else{
drh72cbd072008-10-14 17:58:38 +00004464 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004465 close(fd);
4466 }
drhbbd42a62004-05-22 17:41:58 +00004467 }
4468#endif
drh72cbd072008-10-14 17:58:38 +00004469 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004470}
4471
danielk1977b4b47412007-08-17 15:53:36 +00004472
drhbbd42a62004-05-22 17:41:58 +00004473/*
4474** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004475** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004476** The return value is the number of microseconds of sleep actually
4477** requested from the underlying operating system, a number which
4478** might be greater than or equal to the argument, but not less
4479** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004480*/
danielk1977397d65f2008-11-19 11:35:39 +00004481static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004482#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004483 struct timespec sp;
4484
4485 sp.tv_sec = microseconds / 1000000;
4486 sp.tv_nsec = (microseconds % 1000000) * 1000;
4487 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004488 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004489 return microseconds;
4490#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004491 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004492 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004493 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004494#else
danielk1977b4b47412007-08-17 15:53:36 +00004495 int seconds = (microseconds+999999)/1000000;
4496 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004497 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004498 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004499#endif
drh88f474a2006-01-02 20:00:12 +00004500}
4501
4502/*
drh6b9d6dd2008-12-03 19:34:47 +00004503** The following variable, if set to a non-zero value, is interpreted as
4504** the number of seconds since 1970 and is used to set the result of
4505** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004506*/
4507#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004508int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004509#endif
4510
4511/*
4512** Find the current time (in Universal Coordinated Time). Write the
4513** current time and date as a Julian Day number into *prNow and
4514** return 0. Return 1 if the time and date cannot be found.
4515*/
danielk1977397d65f2008-11-19 11:35:39 +00004516static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004517#if defined(SQLITE_OMIT_FLOATING_POINT)
4518 time_t t;
4519 time(&t);
4520 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4521#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004522 time_t t;
4523 time(&t);
4524 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004525#elif OS_VXWORKS
4526 struct timespec sNow;
4527 clock_gettime(CLOCK_REALTIME, &sNow);
4528 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004529#else
4530 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004531 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004532 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4533#endif
danielk1977397d65f2008-11-19 11:35:39 +00004534
drhbbd42a62004-05-22 17:41:58 +00004535#ifdef SQLITE_TEST
4536 if( sqlite3_current_time ){
4537 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4538 }
4539#endif
danielk1977397d65f2008-11-19 11:35:39 +00004540 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004541 return 0;
4542}
danielk1977b4b47412007-08-17 15:53:36 +00004543
drh6b9d6dd2008-12-03 19:34:47 +00004544/*
4545** We added the xGetLastError() method with the intention of providing
4546** better low-level error messages when operating-system problems come up
4547** during SQLite operation. But so far, none of that has been implemented
4548** in the core. So this routine is never called. For now, it is merely
4549** a place-holder.
4550*/
danielk1977397d65f2008-11-19 11:35:39 +00004551static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4552 UNUSED_PARAMETER(NotUsed);
4553 UNUSED_PARAMETER(NotUsed2);
4554 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004555 return 0;
4556}
4557
drh153c62c2007-08-24 03:51:33 +00004558/*
drh734c9862008-11-28 15:37:20 +00004559************************ End of sqlite3_vfs methods ***************************
4560******************************************************************************/
4561
drh715ff302008-12-03 22:32:44 +00004562/******************************************************************************
4563************************** Begin Proxy Locking ********************************
4564**
4565** Proxy locking is a "uber-locking-method" in this sense: It uses the
4566** other locking methods on secondary lock files. Proxy locking is a
4567** meta-layer over top of the primitive locking implemented above. For
4568** this reason, the division that implements of proxy locking is deferred
4569** until late in the file (here) after all of the other I/O methods have
4570** been defined - so that the primitive locking methods are available
4571** as services to help with the implementation of proxy locking.
4572**
4573****
4574**
4575** The default locking schemes in SQLite use byte-range locks on the
4576** database file to coordinate safe, concurrent access by multiple readers
4577** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4578** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4579** as POSIX read & write locks over fixed set of locations (via fsctl),
4580** on AFP and SMB only exclusive byte-range locks are available via fsctl
4581** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4582** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4583** address in the shared range is taken for a SHARED lock, the entire
4584** shared range is taken for an EXCLUSIVE lock):
4585**
4586** PENDING_BYTE 0x40000000
4587** RESERVED_BYTE 0x40000001
4588** SHARED_RANGE 0x40000002 -> 0x40000200
4589**
4590** This works well on the local file system, but shows a nearly 100x
4591** slowdown in read performance on AFP because the AFP client disables
4592** the read cache when byte-range locks are present. Enabling the read
4593** cache exposes a cache coherency problem that is present on all OS X
4594** supported network file systems. NFS and AFP both observe the
4595** close-to-open semantics for ensuring cache coherency
4596** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4597** address the requirements for concurrent database access by multiple
4598** readers and writers
4599** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4600**
4601** To address the performance and cache coherency issues, proxy file locking
4602** changes the way database access is controlled by limiting access to a
4603** single host at a time and moving file locks off of the database file
4604** and onto a proxy file on the local file system.
4605**
4606**
4607** Using proxy locks
4608** -----------------
4609**
4610** C APIs
4611**
4612** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4613** <proxy_path> | ":auto:");
4614** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4615**
4616**
4617** SQL pragmas
4618**
4619** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4620** PRAGMA [database.]lock_proxy_file
4621**
4622** Specifying ":auto:" means that if there is a conch file with a matching
4623** host ID in it, the proxy path in the conch file will be used, otherwise
4624** a proxy path based on the user's temp dir
4625** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4626** actual proxy file name is generated from the name and path of the
4627** database file. For example:
4628**
4629** For database path "/Users/me/foo.db"
4630** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4631**
4632** Once a lock proxy is configured for a database connection, it can not
4633** be removed, however it may be switched to a different proxy path via
4634** the above APIs (assuming the conch file is not being held by another
4635** connection or process).
4636**
4637**
4638** How proxy locking works
4639** -----------------------
4640**
4641** Proxy file locking relies primarily on two new supporting files:
4642**
4643** * conch file to limit access to the database file to a single host
4644** at a time
4645**
4646** * proxy file to act as a proxy for the advisory locks normally
4647** taken on the database
4648**
4649** The conch file - to use a proxy file, sqlite must first "hold the conch"
4650** by taking an sqlite-style shared lock on the conch file, reading the
4651** contents and comparing the host's unique host ID (see below) and lock
4652** proxy path against the values stored in the conch. The conch file is
4653** stored in the same directory as the database file and the file name
4654** is patterned after the database file name as ".<databasename>-conch".
4655** If the conch file does not exist, or it's contents do not match the
4656** host ID and/or proxy path, then the lock is escalated to an exclusive
4657** lock and the conch file contents is updated with the host ID and proxy
4658** path and the lock is downgraded to a shared lock again. If the conch
4659** is held by another process (with a shared lock), the exclusive lock
4660** will fail and SQLITE_BUSY is returned.
4661**
4662** The proxy file - a single-byte file used for all advisory file locks
4663** normally taken on the database file. This allows for safe sharing
4664** of the database file for multiple readers and writers on the same
4665** host (the conch ensures that they all use the same local lock file).
4666**
drh715ff302008-12-03 22:32:44 +00004667** Requesting the lock proxy does not immediately take the conch, it is
4668** only taken when the first request to lock database file is made.
4669** This matches the semantics of the traditional locking behavior, where
4670** opening a connection to a database file does not take a lock on it.
4671** The shared lock and an open file descriptor are maintained until
4672** the connection to the database is closed.
4673**
4674** The proxy file and the lock file are never deleted so they only need
4675** to be created the first time they are used.
4676**
4677** Configuration options
4678** ---------------------
4679**
4680** SQLITE_PREFER_PROXY_LOCKING
4681**
4682** Database files accessed on non-local file systems are
4683** automatically configured for proxy locking, lock files are
4684** named automatically using the same logic as
4685** PRAGMA lock_proxy_file=":auto:"
4686**
4687** SQLITE_PROXY_DEBUG
4688**
4689** Enables the logging of error messages during host id file
4690** retrieval and creation
4691**
drh715ff302008-12-03 22:32:44 +00004692** LOCKPROXYDIR
4693**
4694** Overrides the default directory used for lock proxy files that
4695** are named automatically via the ":auto:" setting
4696**
4697** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4698**
4699** Permissions to use when creating a directory for storing the
4700** lock proxy files, only used when LOCKPROXYDIR is not set.
4701**
4702**
4703** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4704** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4705** force proxy locking to be used for every database file opened, and 0
4706** will force automatic proxy locking to be disabled for all database
4707** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4708** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4709*/
4710
4711/*
4712** Proxy locking is only available on MacOSX
4713*/
drhd2cb50b2009-01-09 21:41:17 +00004714#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004715
drh715ff302008-12-03 22:32:44 +00004716/*
4717** The proxyLockingContext has the path and file structures for the remote
4718** and local proxy files in it
4719*/
4720typedef struct proxyLockingContext proxyLockingContext;
4721struct proxyLockingContext {
4722 unixFile *conchFile; /* Open conch file */
4723 char *conchFilePath; /* Name of the conch file */
4724 unixFile *lockProxy; /* Open proxy lock file */
4725 char *lockProxyPath; /* Name of the proxy lock file */
4726 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00004727 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00004728 void *oldLockingContext; /* Original lockingcontext to restore on close */
4729 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4730};
4731
drh7ed97b92010-01-20 13:07:21 +00004732/*
4733** The proxy lock file path for the database at dbPath is written into lPath,
4734** which must point to valid, writable memory large enough for a maxLen length
4735** file path.
drh715ff302008-12-03 22:32:44 +00004736*/
drh715ff302008-12-03 22:32:44 +00004737static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4738 int len;
4739 int dbLen;
4740 int i;
4741
4742#ifdef LOCKPROXYDIR
4743 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4744#else
4745# ifdef _CS_DARWIN_USER_TEMP_DIR
4746 {
drh7ed97b92010-01-20 13:07:21 +00004747 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
4748 OSTRACE4("GETLOCKPATH failed %s errno=%d pid=%d\n",
4749 lPath, errno, getpid());
4750 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00004751 }
drh7ed97b92010-01-20 13:07:21 +00004752 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00004753 }
4754# else
4755 len = strlcpy(lPath, "/tmp/", maxLen);
4756# endif
4757#endif
4758
4759 if( lPath[len-1]!='/' ){
4760 len = strlcat(lPath, "/", maxLen);
4761 }
4762
4763 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004764 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004765 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4766 char c = dbPath[i];
4767 lPath[i+len] = (c=='/')?'_':c;
4768 }
4769 lPath[i+len]='\0';
4770 strlcat(lPath, ":auto:", maxLen);
drh7ed97b92010-01-20 13:07:21 +00004771 OSTRACE3("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid());
drh715ff302008-12-03 22:32:44 +00004772 return SQLITE_OK;
4773}
4774
drh7ed97b92010-01-20 13:07:21 +00004775/*
4776 ** Creates the lock file and any missing directories in lockPath
4777 */
4778static int proxyCreateLockPath(const char *lockPath){
4779 int i, len;
4780 char buf[MAXPATHLEN];
4781 int start = 0;
4782
4783 assert(lockPath!=NULL);
4784 /* try to create all the intermediate directories */
4785 len = (int)strlen(lockPath);
4786 buf[0] = lockPath[0];
4787 for( i=1; i<len; i++ ){
4788 if( lockPath[i] == '/' && (i - start > 0) ){
4789 /* only mkdir if leaf dir != "." or "/" or ".." */
4790 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
4791 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
4792 buf[i]='\0';
4793 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4794 int err=errno;
4795 if( err!=EEXIST ) {
4796 OSTRACE5("CREATELOCKPATH FAILED creating %s, "
4797 "'%s' proxy lock path=%s pid=%d\n",
4798 buf, strerror(err), lockPath, getpid());
4799 return err;
4800 }
4801 }
4802 }
4803 start=i+1;
4804 }
4805 buf[i] = lockPath[i];
4806 }
4807 OSTRACE3("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid());
4808 return 0;
4809}
4810
drh715ff302008-12-03 22:32:44 +00004811/*
4812** Create a new VFS file descriptor (stored in memory obtained from
4813** sqlite3_malloc) and open the file named "path" in the file descriptor.
4814**
4815** The caller is responsible not only for closing the file descriptor
4816** but also for freeing the memory associated with the file descriptor.
4817*/
drh7ed97b92010-01-20 13:07:21 +00004818static int proxyCreateUnixFile(
4819 const char *path, /* path for the new unixFile */
4820 unixFile **ppFile, /* unixFile created and returned by ref */
4821 int islockfile /* if non zero missing dirs will be created */
4822) {
4823 int fd = -1;
4824 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00004825 unixFile *pNew;
4826 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00004827 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00004828 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00004829 int terrno = 0;
4830 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00004831
drh7ed97b92010-01-20 13:07:21 +00004832 /* 1. first try to open/create the file
4833 ** 2. if that fails, and this is a lock file (not-conch), try creating
4834 ** the parent directories and then try again.
4835 ** 3. if that fails, try to open the file read-only
4836 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
4837 */
4838 pUnused = findReusableFd(path, openFlags);
4839 if( pUnused ){
4840 fd = pUnused->fd;
4841 }else{
4842 pUnused = sqlite3_malloc(sizeof(*pUnused));
4843 if( !pUnused ){
4844 return SQLITE_NOMEM;
4845 }
4846 }
4847 if( fd<0 ){
4848 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4849 terrno = errno;
4850 if( fd<0 && errno==ENOENT && islockfile ){
4851 if( proxyCreateLockPath(path) == SQLITE_OK ){
4852 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4853 }
4854 }
4855 }
4856 if( fd<0 ){
4857 openFlags = O_RDONLY;
4858 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4859 terrno = errno;
4860 }
4861 if( fd<0 ){
4862 if( islockfile ){
4863 return SQLITE_BUSY;
4864 }
4865 switch (terrno) {
4866 case EACCES:
4867 return SQLITE_PERM;
4868 case EIO:
4869 return SQLITE_IOERR_LOCK; /* even though it is the conch */
4870 default:
drh9978c972010-02-23 17:36:32 +00004871 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00004872 }
4873 }
4874
4875 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
4876 if( pNew==NULL ){
4877 rc = SQLITE_NOMEM;
4878 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00004879 }
4880 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00004881 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00004882 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00004883 pUnused->fd = fd;
4884 pUnused->flags = openFlags;
4885 pNew->pUnused = pUnused;
4886
4887 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4888 if( rc==SQLITE_OK ){
4889 *ppFile = pNew;
4890 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00004891 }
drh7ed97b92010-01-20 13:07:21 +00004892end_create_proxy:
4893 close(fd); /* silently leak fd if error, we're already in error */
4894 sqlite3_free(pNew);
4895 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00004896 return rc;
4897}
4898
drh7ed97b92010-01-20 13:07:21 +00004899#ifdef SQLITE_TEST
4900/* simulate multiple hosts by creating unique hostid file paths */
4901int sqlite3_hostid_num = 0;
4902#endif
4903
4904#define PROXY_HOSTIDLEN 16 /* conch file host id length */
4905
4906/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
4907** bytes of writable memory.
4908*/
4909static int proxyGetHostID(unsigned char *pHostID, int *pError){
4910 struct timespec timeout = {1, 0}; /* 1 sec timeout */
4911
4912 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
4913 memset(pHostID, 0, PROXY_HOSTIDLEN);
4914 if( gethostuuid(pHostID, &timeout) ){
4915 int err = errno;
4916 if( pError ){
4917 *pError = err;
4918 }
4919 return SQLITE_IOERR;
4920 }
4921#ifdef SQLITE_TEST
4922 /* simulate multiple hosts by creating unique hostid file paths */
4923 if( sqlite3_hostid_num != 0){
4924 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
4925 }
4926#endif
4927
4928 return SQLITE_OK;
4929}
4930
4931/* The conch file contains the header, host id and lock file path
4932 */
4933#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
4934#define PROXY_HEADERLEN 1 /* conch file header length */
4935#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
4936#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
4937
4938/*
4939** Takes an open conch file, copies the contents to a new path and then moves
4940** it back. The newly created file's file descriptor is assigned to the
4941** conch file structure and finally the original conch file descriptor is
4942** closed. Returns zero if successful.
4943*/
4944static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
4945 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4946 unixFile *conchFile = pCtx->conchFile;
4947 char tPath[MAXPATHLEN];
4948 char buf[PROXY_MAXCONCHLEN];
4949 char *cPath = pCtx->conchFilePath;
4950 size_t readLen = 0;
4951 size_t pathLen = 0;
4952 char errmsg[64] = "";
4953 int fd = -1;
4954 int rc = -1;
4955
4956 /* create a new path by replace the trailing '-conch' with '-break' */
4957 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
4958 if( pathLen>MAXPATHLEN || pathLen<6 ||
4959 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
4960 sprintf(errmsg, "path error (len %d)", (int)pathLen);
4961 goto end_breaklock;
4962 }
4963 /* read the conch content */
4964 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
4965 if( readLen<PROXY_PATHINDEX ){
4966 sprintf(errmsg, "read error (len %d)", (int)readLen);
4967 goto end_breaklock;
4968 }
4969 /* write it out to the temporary break file */
4970 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
4971 if( fd<0 ){
4972 sprintf(errmsg, "create failed (%d)", errno);
4973 goto end_breaklock;
4974 }
4975 if( pwrite(fd, buf, readLen, 0) != readLen ){
4976 sprintf(errmsg, "write failed (%d)", errno);
4977 goto end_breaklock;
4978 }
4979 if( rename(tPath, cPath) ){
4980 sprintf(errmsg, "rename failed (%d)", errno);
4981 goto end_breaklock;
4982 }
4983 rc = 0;
4984 fprintf(stderr, "broke stale lock on %s\n", cPath);
4985 close(conchFile->h);
4986 conchFile->h = fd;
4987 conchFile->openFlags = O_RDWR | O_CREAT;
4988
4989end_breaklock:
4990 if( rc ){
4991 if( fd>=0 ){
4992 unlink(tPath);
4993 close(fd);
4994 }
4995 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
4996 }
4997 return rc;
4998}
4999
5000/* Take the requested lock on the conch file and break a stale lock if the
5001** host id matches.
5002*/
5003static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5004 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5005 unixFile *conchFile = pCtx->conchFile;
5006 int rc = SQLITE_OK;
5007 int nTries = 0;
5008 struct timespec conchModTime;
5009
5010 do {
5011 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5012 nTries ++;
5013 if( rc==SQLITE_BUSY ){
5014 /* If the lock failed (busy):
5015 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5016 * 2nd try: fail if the mod time changed or host id is different, wait
5017 * 10 sec and try again
5018 * 3rd try: break the lock unless the mod time has changed.
5019 */
5020 struct stat buf;
5021 if( fstat(conchFile->h, &buf) ){
5022 pFile->lastErrno = errno;
5023 return SQLITE_IOERR_LOCK;
5024 }
5025
5026 if( nTries==1 ){
5027 conchModTime = buf.st_mtimespec;
5028 usleep(500000); /* wait 0.5 sec and try the lock again*/
5029 continue;
5030 }
5031
5032 assert( nTries>1 );
5033 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5034 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5035 return SQLITE_BUSY;
5036 }
5037
5038 if( nTries==2 ){
5039 char tBuf[PROXY_MAXCONCHLEN];
5040 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5041 if( len<0 ){
5042 pFile->lastErrno = errno;
5043 return SQLITE_IOERR_LOCK;
5044 }
5045 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5046 /* don't break the lock if the host id doesn't match */
5047 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5048 return SQLITE_BUSY;
5049 }
5050 }else{
5051 /* don't break the lock on short read or a version mismatch */
5052 return SQLITE_BUSY;
5053 }
5054 usleep(10000000); /* wait 10 sec and try the lock again */
5055 continue;
5056 }
5057
5058 assert( nTries==3 );
5059 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5060 rc = SQLITE_OK;
5061 if( lockType==EXCLUSIVE_LOCK ){
5062 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5063 }
5064 if( !rc ){
5065 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5066 }
5067 }
5068 }
5069 } while( rc==SQLITE_BUSY && nTries<3 );
5070
5071 return rc;
5072}
5073
5074/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005075** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5076** lockPath means that the lockPath in the conch file will be used if the
5077** host IDs match, or a new lock path will be generated automatically
5078** and written to the conch file.
5079*/
5080static int proxyTakeConch(unixFile *pFile){
5081 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5082
drh7ed97b92010-01-20 13:07:21 +00005083 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005084 return SQLITE_OK;
5085 }else{
5086 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005087 uuid_t myHostID;
5088 int pError = 0;
5089 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005090 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005091 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005092 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005093 int createConch = 0;
5094 int hostIdMatch = 0;
5095 int readLen = 0;
5096 int tryOldLockPath = 0;
5097 int forceNewLockPath = 0;
5098
drh715ff302008-12-03 22:32:44 +00005099 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5100 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
5101
drh7ed97b92010-01-20 13:07:21 +00005102 rc = proxyGetHostID(myHostID, &pError);
5103 if( (rc&0xff)==SQLITE_IOERR ){
5104 pFile->lastErrno = pError;
5105 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005106 }
drh7ed97b92010-01-20 13:07:21 +00005107 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005108 if( rc!=SQLITE_OK ){
5109 goto end_takeconch;
5110 }
drh7ed97b92010-01-20 13:07:21 +00005111 /* read the existing conch file */
5112 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5113 if( readLen<0 ){
5114 /* I/O error: lastErrno set by seekAndRead */
5115 pFile->lastErrno = conchFile->lastErrno;
5116 rc = SQLITE_IOERR_READ;
5117 goto end_takeconch;
5118 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5119 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5120 /* a short read or version format mismatch means we need to create a new
5121 ** conch file.
5122 */
5123 createConch = 1;
5124 }
5125 /* if the host id matches and the lock path already exists in the conch
5126 ** we'll try to use the path there, if we can't open that path, we'll
5127 ** retry with a new auto-generated path
5128 */
5129 do { /* in case we need to try again for an :auto: named lock file */
5130
5131 if( !createConch && !forceNewLockPath ){
5132 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5133 PROXY_HOSTIDLEN);
5134 /* if the conch has data compare the contents */
5135 if( !pCtx->lockProxyPath ){
5136 /* for auto-named local lock file, just check the host ID and we'll
5137 ** use the local lock file path that's already in there
5138 */
5139 if( hostIdMatch ){
5140 size_t pathLen = (readLen - PROXY_PATHINDEX);
5141
5142 if( pathLen>=MAXPATHLEN ){
5143 pathLen=MAXPATHLEN-1;
5144 }
5145 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5146 lockPath[pathLen] = 0;
5147 tempLockPath = lockPath;
5148 tryOldLockPath = 1;
5149 /* create a copy of the lock path if the conch is taken */
5150 goto end_takeconch;
5151 }
5152 }else if( hostIdMatch
5153 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5154 readLen-PROXY_PATHINDEX)
5155 ){
5156 /* conch host and lock path match */
5157 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005158 }
drh7ed97b92010-01-20 13:07:21 +00005159 }
5160
5161 /* if the conch isn't writable and doesn't match, we can't take it */
5162 if( (conchFile->openFlags&O_RDWR) == 0 ){
5163 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005164 goto end_takeconch;
5165 }
drh7ed97b92010-01-20 13:07:21 +00005166
5167 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005168 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005169 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5170 tempLockPath = lockPath;
5171 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005172 }
drh7ed97b92010-01-20 13:07:21 +00005173
5174 /* update conch with host and path (this will fail if other process
5175 ** has a shared lock already), if the host id matches, use the big
5176 ** stick.
drh715ff302008-12-03 22:32:44 +00005177 */
drh7ed97b92010-01-20 13:07:21 +00005178 futimes(conchFile->h, NULL);
5179 if( hostIdMatch && !createConch ){
5180 if( conchFile->pLock && conchFile->pLock->cnt>1 ){
5181 /* We are trying for an exclusive lock but another thread in this
5182 ** same process is still holding a shared lock. */
5183 rc = SQLITE_BUSY;
5184 } else {
5185 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005186 }
drh715ff302008-12-03 22:32:44 +00005187 }else{
drh7ed97b92010-01-20 13:07:21 +00005188 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005189 }
drh7ed97b92010-01-20 13:07:21 +00005190 if( rc==SQLITE_OK ){
5191 char writeBuffer[PROXY_MAXCONCHLEN];
5192 int writeSize = 0;
5193
5194 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5195 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5196 if( pCtx->lockProxyPath!=NULL ){
5197 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5198 }else{
5199 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5200 }
5201 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5202 ftruncate(conchFile->h, writeSize);
5203 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5204 fsync(conchFile->h);
5205 /* If we created a new conch file (not just updated the contents of a
5206 ** valid conch file), try to match the permissions of the database
5207 */
5208 if( rc==SQLITE_OK && createConch ){
5209 struct stat buf;
5210 int err = fstat(pFile->h, &buf);
5211 if( err==0 ){
5212 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5213 S_IROTH|S_IWOTH);
5214 /* try to match the database file R/W permissions, ignore failure */
5215#ifndef SQLITE_PROXY_DEBUG
5216 fchmod(conchFile->h, cmode);
5217#else
5218 if( fchmod(conchFile->h, cmode)!=0 ){
5219 int code = errno;
5220 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5221 cmode, code, strerror(code));
5222 } else {
5223 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5224 }
5225 }else{
5226 int code = errno;
5227 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5228 err, code, strerror(code));
5229#endif
5230 }
drh715ff302008-12-03 22:32:44 +00005231 }
5232 }
drh7ed97b92010-01-20 13:07:21 +00005233 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5234
5235 end_takeconch:
5236 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
5237 if( rc==SQLITE_OK && pFile->openFlags ){
5238 if( pFile->h>=0 ){
5239#ifdef STRICT_CLOSE_ERROR
5240 if( close(pFile->h) ){
5241 pFile->lastErrno = errno;
5242 return SQLITE_IOERR_CLOSE;
5243 }
5244#else
5245 close(pFile->h); /* silently leak fd if fail */
5246#endif
5247 }
5248 pFile->h = -1;
5249 int fd = open(pCtx->dbPath, pFile->openFlags,
5250 SQLITE_DEFAULT_FILE_PERMISSIONS);
5251 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
5252 if( fd>=0 ){
5253 pFile->h = fd;
5254 }else{
drh9978c972010-02-23 17:36:32 +00005255 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005256 during locking */
5257 }
5258 }
5259 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5260 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5261 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5262 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5263 /* we couldn't create the proxy lock file with the old lock file path
5264 ** so try again via auto-naming
5265 */
5266 forceNewLockPath = 1;
5267 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005268 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005269 }
5270 }
5271 if( rc==SQLITE_OK ){
5272 /* Need to make a copy of path if we extracted the value
5273 ** from the conch file or the path was allocated on the stack
5274 */
5275 if( tempLockPath ){
5276 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5277 if( !pCtx->lockProxyPath ){
5278 rc = SQLITE_NOMEM;
5279 }
5280 }
5281 }
5282 if( rc==SQLITE_OK ){
5283 pCtx->conchHeld = 1;
5284
5285 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5286 afpLockingContext *afpCtx;
5287 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5288 afpCtx->dbPath = pCtx->lockProxyPath;
5289 }
5290 } else {
5291 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5292 }
5293 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
5294 return rc;
5295 } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005296 }
5297}
5298
5299/*
5300** If pFile holds a lock on a conch file, then release that lock.
5301*/
5302static int proxyReleaseConch(unixFile *pFile){
5303 int rc; /* Subroutine return code */
5304 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5305 unixFile *conchFile; /* Name of the conch file */
5306
5307 pCtx = (proxyLockingContext *)pFile->lockingContext;
5308 conchFile = pCtx->conchFile;
5309 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
5310 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
5311 getpid());
drh7ed97b92010-01-20 13:07:21 +00005312 if( pCtx->conchHeld>0 ){
5313 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5314 }
drh715ff302008-12-03 22:32:44 +00005315 pCtx->conchHeld = 0;
drh715ff302008-12-03 22:32:44 +00005316 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
5317 (rc==SQLITE_OK ? "ok" : "failed"));
5318 return rc;
5319}
5320
5321/*
5322** Given the name of a database file, compute the name of its conch file.
5323** Store the conch filename in memory obtained from sqlite3_malloc().
5324** Make *pConchPath point to the new name. Return SQLITE_OK on success
5325** or SQLITE_NOMEM if unable to obtain memory.
5326**
5327** The caller is responsible for ensuring that the allocated memory
5328** space is eventually freed.
5329**
5330** *pConchPath is set to NULL if a memory allocation error occurs.
5331*/
5332static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5333 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005334 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005335 char *conchPath; /* buffer in which to construct conch name */
5336
5337 /* Allocate space for the conch filename and initialize the name to
5338 ** the name of the original database file. */
5339 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5340 if( conchPath==0 ){
5341 return SQLITE_NOMEM;
5342 }
5343 memcpy(conchPath, dbPath, len+1);
5344
5345 /* now insert a "." before the last / character */
5346 for( i=(len-1); i>=0; i-- ){
5347 if( conchPath[i]=='/' ){
5348 i++;
5349 break;
5350 }
5351 }
5352 conchPath[i]='.';
5353 while ( i<len ){
5354 conchPath[i+1]=dbPath[i];
5355 i++;
5356 }
5357
5358 /* append the "-conch" suffix to the file */
5359 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005360 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005361
5362 return SQLITE_OK;
5363}
5364
5365
5366/* Takes a fully configured proxy locking-style unix file and switches
5367** the local lock file path
5368*/
5369static int switchLockProxyPath(unixFile *pFile, const char *path) {
5370 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5371 char *oldPath = pCtx->lockProxyPath;
5372 int rc = SQLITE_OK;
5373
5374 if( pFile->locktype!=NO_LOCK ){
5375 return SQLITE_BUSY;
5376 }
5377
5378 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5379 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5380 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5381 return SQLITE_OK;
5382 }else{
5383 unixFile *lockProxy = pCtx->lockProxy;
5384 pCtx->lockProxy=NULL;
5385 pCtx->conchHeld = 0;
5386 if( lockProxy!=NULL ){
5387 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5388 if( rc ) return rc;
5389 sqlite3_free(lockProxy);
5390 }
5391 sqlite3_free(oldPath);
5392 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5393 }
5394
5395 return rc;
5396}
5397
5398/*
5399** pFile is a file that has been opened by a prior xOpen call. dbPath
5400** is a string buffer at least MAXPATHLEN+1 characters in size.
5401**
5402** This routine find the filename associated with pFile and writes it
5403** int dbPath.
5404*/
5405static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005406#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005407 if( pFile->pMethod == &afpIoMethods ){
5408 /* afp style keeps a reference to the db path in the filePath field
5409 ** of the struct */
drhea678832008-12-10 19:26:22 +00005410 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005411 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5412 } else
drh715ff302008-12-03 22:32:44 +00005413#endif
5414 if( pFile->pMethod == &dotlockIoMethods ){
5415 /* dot lock style uses the locking context to store the dot lock
5416 ** file path */
5417 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5418 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5419 }else{
5420 /* all other styles use the locking context to store the db file path */
5421 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005422 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005423 }
5424 return SQLITE_OK;
5425}
5426
5427/*
5428** Takes an already filled in unix file and alters it so all file locking
5429** will be performed on the local proxy lock file. The following fields
5430** are preserved in the locking context so that they can be restored and
5431** the unix structure properly cleaned up at close time:
5432** ->lockingContext
5433** ->pMethod
5434*/
5435static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5436 proxyLockingContext *pCtx;
5437 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5438 char *lockPath=NULL;
5439 int rc = SQLITE_OK;
5440
5441 if( pFile->locktype!=NO_LOCK ){
5442 return SQLITE_BUSY;
5443 }
5444 proxyGetDbPathForUnixFile(pFile, dbPath);
5445 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5446 lockPath=NULL;
5447 }else{
5448 lockPath=(char *)path;
5449 }
5450
5451 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5452 (lockPath ? lockPath : ":auto:"), getpid());
5453
5454 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5455 if( pCtx==0 ){
5456 return SQLITE_NOMEM;
5457 }
5458 memset(pCtx, 0, sizeof(*pCtx));
5459
5460 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5461 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005462 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5463 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5464 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5465 ** (c) the file system is read-only, then enable no-locking access.
5466 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5467 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5468 */
5469 struct statfs fsInfo;
5470 struct stat conchInfo;
5471 int goLockless = 0;
5472
5473 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5474 int err = errno;
5475 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5476 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5477 }
5478 }
5479 if( goLockless ){
5480 pCtx->conchHeld = -1; /* read only FS/ lockless */
5481 rc = SQLITE_OK;
5482 }
5483 }
drh715ff302008-12-03 22:32:44 +00005484 }
5485 if( rc==SQLITE_OK && lockPath ){
5486 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5487 }
5488
5489 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005490 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5491 if( pCtx->dbPath==NULL ){
5492 rc = SQLITE_NOMEM;
5493 }
5494 }
5495 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005496 /* all memory is allocated, proxys are created and assigned,
5497 ** switch the locking context and pMethod then return.
5498 */
drh715ff302008-12-03 22:32:44 +00005499 pCtx->oldLockingContext = pFile->lockingContext;
5500 pFile->lockingContext = pCtx;
5501 pCtx->pOldMethod = pFile->pMethod;
5502 pFile->pMethod = &proxyIoMethods;
5503 }else{
5504 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00005505 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00005506 sqlite3_free(pCtx->conchFile);
5507 }
drh7ed97b92010-01-20 13:07:21 +00005508 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00005509 sqlite3_free(pCtx->conchFilePath);
5510 sqlite3_free(pCtx);
5511 }
5512 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
5513 (rc==SQLITE_OK ? "ok" : "failed"));
5514 return rc;
5515}
5516
5517
5518/*
5519** This routine handles sqlite3_file_control() calls that are specific
5520** to proxy locking.
5521*/
5522static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5523 switch( op ){
5524 case SQLITE_GET_LOCKPROXYFILE: {
5525 unixFile *pFile = (unixFile*)id;
5526 if( pFile->pMethod == &proxyIoMethods ){
5527 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5528 proxyTakeConch(pFile);
5529 if( pCtx->lockProxyPath ){
5530 *(const char **)pArg = pCtx->lockProxyPath;
5531 }else{
5532 *(const char **)pArg = ":auto: (not held)";
5533 }
5534 } else {
5535 *(const char **)pArg = NULL;
5536 }
5537 return SQLITE_OK;
5538 }
5539 case SQLITE_SET_LOCKPROXYFILE: {
5540 unixFile *pFile = (unixFile*)id;
5541 int rc = SQLITE_OK;
5542 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5543 if( pArg==NULL || (const char *)pArg==0 ){
5544 if( isProxyStyle ){
5545 /* turn off proxy locking - not supported */
5546 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5547 }else{
5548 /* turn off proxy locking - already off - NOOP */
5549 rc = SQLITE_OK;
5550 }
5551 }else{
5552 const char *proxyPath = (const char *)pArg;
5553 if( isProxyStyle ){
5554 proxyLockingContext *pCtx =
5555 (proxyLockingContext*)pFile->lockingContext;
5556 if( !strcmp(pArg, ":auto:")
5557 || (pCtx->lockProxyPath &&
5558 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5559 ){
5560 rc = SQLITE_OK;
5561 }else{
5562 rc = switchLockProxyPath(pFile, proxyPath);
5563 }
5564 }else{
5565 /* turn on proxy file locking */
5566 rc = proxyTransformUnixFile(pFile, proxyPath);
5567 }
5568 }
5569 return rc;
5570 }
5571 default: {
5572 assert( 0 ); /* The call assures that only valid opcodes are sent */
5573 }
5574 }
5575 /*NOTREACHED*/
5576 return SQLITE_ERROR;
5577}
5578
5579/*
5580** Within this division (the proxying locking implementation) the procedures
5581** above this point are all utilities. The lock-related methods of the
5582** proxy-locking sqlite3_io_method object follow.
5583*/
5584
5585
5586/*
5587** This routine checks if there is a RESERVED lock held on the specified
5588** file by this or any other process. If such a lock is held, set *pResOut
5589** to a non-zero value otherwise *pResOut is set to zero. The return value
5590** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5591*/
5592static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5593 unixFile *pFile = (unixFile*)id;
5594 int rc = proxyTakeConch(pFile);
5595 if( rc==SQLITE_OK ){
5596 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005597 if( pCtx->conchHeld>0 ){
5598 unixFile *proxy = pCtx->lockProxy;
5599 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5600 }else{ /* conchHeld < 0 is lockless */
5601 pResOut=0;
5602 }
drh715ff302008-12-03 22:32:44 +00005603 }
5604 return rc;
5605}
5606
5607/*
5608** Lock the file with the lock specified by parameter locktype - one
5609** of the following:
5610**
5611** (1) SHARED_LOCK
5612** (2) RESERVED_LOCK
5613** (3) PENDING_LOCK
5614** (4) EXCLUSIVE_LOCK
5615**
5616** Sometimes when requesting one lock state, additional lock states
5617** are inserted in between. The locking might fail on one of the later
5618** transitions leaving the lock state different from what it started but
5619** still short of its goal. The following chart shows the allowed
5620** transitions and the inserted intermediate states:
5621**
5622** UNLOCKED -> SHARED
5623** SHARED -> RESERVED
5624** SHARED -> (PENDING) -> EXCLUSIVE
5625** RESERVED -> (PENDING) -> EXCLUSIVE
5626** PENDING -> EXCLUSIVE
5627**
5628** This routine will only increase a lock. Use the sqlite3OsUnlock()
5629** routine to lower a locking level.
5630*/
5631static int proxyLock(sqlite3_file *id, int locktype) {
5632 unixFile *pFile = (unixFile*)id;
5633 int rc = proxyTakeConch(pFile);
5634 if( rc==SQLITE_OK ){
5635 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005636 if( pCtx->conchHeld>0 ){
5637 unixFile *proxy = pCtx->lockProxy;
5638 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
5639 pFile->locktype = proxy->locktype;
5640 }else{
5641 /* conchHeld < 0 is lockless */
5642 }
drh715ff302008-12-03 22:32:44 +00005643 }
5644 return rc;
5645}
5646
5647
5648/*
5649** Lower the locking level on file descriptor pFile to locktype. locktype
5650** must be either NO_LOCK or SHARED_LOCK.
5651**
5652** If the locking level of the file descriptor is already at or below
5653** the requested locking level, this routine is a no-op.
5654*/
5655static int proxyUnlock(sqlite3_file *id, int locktype) {
5656 unixFile *pFile = (unixFile*)id;
5657 int rc = proxyTakeConch(pFile);
5658 if( rc==SQLITE_OK ){
5659 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005660 if( pCtx->conchHeld>0 ){
5661 unixFile *proxy = pCtx->lockProxy;
5662 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5663 pFile->locktype = proxy->locktype;
5664 }else{
5665 /* conchHeld < 0 is lockless */
5666 }
drh715ff302008-12-03 22:32:44 +00005667 }
5668 return rc;
5669}
5670
5671/*
5672** Close a file that uses proxy locks.
5673*/
5674static int proxyClose(sqlite3_file *id) {
5675 if( id ){
5676 unixFile *pFile = (unixFile*)id;
5677 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5678 unixFile *lockProxy = pCtx->lockProxy;
5679 unixFile *conchFile = pCtx->conchFile;
5680 int rc = SQLITE_OK;
5681
5682 if( lockProxy ){
5683 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5684 if( rc ) return rc;
5685 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5686 if( rc ) return rc;
5687 sqlite3_free(lockProxy);
5688 pCtx->lockProxy = 0;
5689 }
5690 if( conchFile ){
5691 if( pCtx->conchHeld ){
5692 rc = proxyReleaseConch(pFile);
5693 if( rc ) return rc;
5694 }
5695 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5696 if( rc ) return rc;
5697 sqlite3_free(conchFile);
5698 }
5699 sqlite3_free(pCtx->lockProxyPath);
5700 sqlite3_free(pCtx->conchFilePath);
5701 sqlite3_free(pCtx->dbPath);
5702 /* restore the original locking context and pMethod then close it */
5703 pFile->lockingContext = pCtx->oldLockingContext;
5704 pFile->pMethod = pCtx->pOldMethod;
5705 sqlite3_free(pCtx);
5706 return pFile->pMethod->xClose(id);
5707 }
5708 return SQLITE_OK;
5709}
5710
5711
5712
drhd2cb50b2009-01-09 21:41:17 +00005713#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005714/*
5715** The proxy locking style is intended for use with AFP filesystems.
5716** And since AFP is only supported on MacOSX, the proxy locking is also
5717** restricted to MacOSX.
5718**
5719**
5720******************* End of the proxy lock implementation **********************
5721******************************************************************************/
5722
drh734c9862008-11-28 15:37:20 +00005723/*
danielk1977e339d652008-06-28 11:23:00 +00005724** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005725**
5726** This routine registers all VFS implementations for unix-like operating
5727** systems. This routine, and the sqlite3_os_end() routine that follows,
5728** should be the only routines in this file that are visible from other
5729** files.
drh6b9d6dd2008-12-03 19:34:47 +00005730**
5731** This routine is called once during SQLite initialization and by a
5732** single thread. The memory allocation and mutex subsystems have not
5733** necessarily been initialized when this routine is called, and so they
5734** should not be used.
drh153c62c2007-08-24 03:51:33 +00005735*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005736int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005737 /*
5738 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005739 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5740 ** to the "finder" function. (pAppData is a pointer to a pointer because
5741 ** silly C90 rules prohibit a void* from being cast to a function pointer
5742 ** and so we have to go through the intermediate pointer to avoid problems
5743 ** when compiling with -pedantic-errors on GCC.)
5744 **
5745 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005746 ** finder-function. The finder-function returns a pointer to the
5747 ** sqlite_io_methods object that implements the desired locking
5748 ** behaviors. See the division above that contains the IOMETHODS
5749 ** macro for addition information on finder-functions.
5750 **
5751 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5752 ** object. But the "autolockIoFinder" available on MacOSX does a little
5753 ** more than that; it looks at the filesystem type that hosts the
5754 ** database file and tries to choose an locking method appropriate for
5755 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005756 */
drh7708e972008-11-29 00:56:52 +00005757 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005758 1, /* iVersion */ \
5759 sizeof(unixFile), /* szOsFile */ \
5760 MAX_PATHNAME, /* mxPathname */ \
5761 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005762 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005763 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005764 unixOpen, /* xOpen */ \
5765 unixDelete, /* xDelete */ \
5766 unixAccess, /* xAccess */ \
5767 unixFullPathname, /* xFullPathname */ \
5768 unixDlOpen, /* xDlOpen */ \
5769 unixDlError, /* xDlError */ \
5770 unixDlSym, /* xDlSym */ \
5771 unixDlClose, /* xDlClose */ \
5772 unixRandomness, /* xRandomness */ \
5773 unixSleep, /* xSleep */ \
5774 unixCurrentTime, /* xCurrentTime */ \
5775 unixGetLastError /* xGetLastError */ \
5776 }
5777
drh6b9d6dd2008-12-03 19:34:47 +00005778 /*
5779 ** All default VFSes for unix are contained in the following array.
5780 **
5781 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5782 ** by the SQLite core when the VFS is registered. So the following
5783 ** array cannot be const.
5784 */
danielk1977e339d652008-06-28 11:23:00 +00005785 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005786#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005787 UNIXVFS("unix", autolockIoFinder ),
5788#else
5789 UNIXVFS("unix", posixIoFinder ),
5790#endif
5791 UNIXVFS("unix-none", nolockIoFinder ),
5792 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005793#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005794 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005795#endif
5796#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005797 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005798#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005799 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005800#endif
chw78a13182009-04-07 05:35:03 +00005801#endif
drhd2cb50b2009-01-09 21:41:17 +00005802#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005803 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00005804 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00005805 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005806#endif
drh153c62c2007-08-24 03:51:33 +00005807 };
drh6b9d6dd2008-12-03 19:34:47 +00005808 unsigned int i; /* Loop counter */
5809
5810 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005811 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005812 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005813 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005814 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005815}
danielk1977e339d652008-06-28 11:23:00 +00005816
5817/*
drh6b9d6dd2008-12-03 19:34:47 +00005818** Shutdown the operating system interface.
5819**
5820** Some operating systems might need to do some cleanup in this routine,
5821** to release dynamically allocated objects. But not on unix.
5822** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005823*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005824int sqlite3_os_end(void){
5825 return SQLITE_OK;
5826}
drhdce8bdb2007-08-16 13:01:44 +00005827
danielk197729bafea2008-06-26 10:41:19 +00005828#endif /* SQLITE_OS_UNIX */