blob: e4bc1dec91cb104f29364128c592f6aaed52dc67 [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>
131# include <sys/mount.h>
132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
drh84a2bf62010-03-05 13:41:06 +0000135#if defined(__APPLE__)
136# include <sys/mount.h>
137#endif
138
drh9cbe6352005-11-29 03:13:21 +0000139/*
drh7ed97b92010-01-20 13:07:21 +0000140** Allowed values of unixFile.fsFlags
141*/
142#define SQLITE_FSFLAGS_IS_MSDOS 0x1
143
144/*
drhf1a221e2006-01-15 17:27:17 +0000145** If we are to be thread-safe, include the pthreads header and define
146** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000147*/
drhd677b3d2007-08-20 22:48:41 +0000148#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000149# include <pthread.h>
150# define SQLITE_UNIX_THREADS 1
151#endif
152
153/*
154** Default permissions when creating a new file
155*/
156#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
157# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
158#endif
159
danielk1977b4b47412007-08-17 15:53:36 +0000160/*
aswiftaebf4132008-11-21 00:10:35 +0000161 ** Default permissions when creating auto proxy dir
162 */
163#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
164# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
165#endif
166
167/*
danielk1977b4b47412007-08-17 15:53:36 +0000168** Maximum supported path-length.
169*/
170#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000171
drh734c9862008-11-28 15:37:20 +0000172/*
drh734c9862008-11-28 15:37:20 +0000173** Only set the lastErrno if the error code is a real error and not
174** a normal expected return code of SQLITE_BUSY or SQLITE_OK
175*/
176#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
177
drh9cbe6352005-11-29 03:13:21 +0000178
179/*
dane946c392009-08-22 11:39:46 +0000180** Sometimes, after a file handle is closed by SQLite, the file descriptor
181** cannot be closed immediately. In these cases, instances of the following
182** structure are used to store the file descriptor while waiting for an
183** opportunity to either close or reuse it.
184*/
185typedef struct UnixUnusedFd UnixUnusedFd;
186struct UnixUnusedFd {
187 int fd; /* File descriptor to close */
188 int flags; /* Flags this file descriptor was opened with */
189 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
190};
191
192/*
drh9b35ea62008-11-29 02:20:26 +0000193** The unixFile structure is subclass of sqlite3_file specific to the unix
194** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000195*/
drh054889e2005-11-30 03:20:31 +0000196typedef struct unixFile unixFile;
197struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000198 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000199 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
200 struct unixLockInfo *pLock; /* Info about locks on this inode */
201 int h; /* The file descriptor */
202 int dirfd; /* File descriptor for the directory */
203 unsigned char locktype; /* The type of lock held on this fd */
204 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000205 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000206 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000207 int fileFlags; /* Miscellanous flags */
drh08c6d442009-02-09 17:34:07 +0000208#if SQLITE_ENABLE_LOCKING_STYLE
209 int openFlags; /* The flags specified at open() */
210#endif
drh7ed97b92010-01-20 13:07:21 +0000211#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
212 unsigned fsFlags; /* cached details from statfs() */
213#endif
drh734c9862008-11-28 15:37:20 +0000214#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000215 pthread_t tid; /* The thread that "owns" this unixFile */
216#endif
217#if OS_VXWORKS
218 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000219 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000220#endif
drh8f941bc2009-01-14 23:03:40 +0000221#ifndef NDEBUG
222 /* The next group of variables are used to track whether or not the
223 ** transaction counter in bytes 24-27 of database files are updated
224 ** whenever any part of the database changes. An assertion fault will
225 ** occur if a file is updated without also updating the transaction
226 ** counter. This test is made to avoid new problems similar to the
227 ** one described by ticket #3584.
228 */
229 unsigned char transCntrChng; /* True if the transaction counter changed */
230 unsigned char dbUpdate; /* True if any part of database file changed */
231 unsigned char inNormalWrite; /* True if in a normal write operation */
232#endif
danielk1977967a4a12007-08-20 14:23:44 +0000233#ifdef SQLITE_TEST
234 /* In test mode, increase the size of this structure a bit so that
235 ** it is larger than the struct CrashFile defined in test6.c.
236 */
237 char aPadding[32];
238#endif
drh9cbe6352005-11-29 03:13:21 +0000239};
240
drh0ccebe72005-06-07 22:22:50 +0000241/*
drh0c2694b2009-09-03 16:23:44 +0000242** The following macros define bits in unixFile.fileFlags
243*/
244#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
245
246/*
drh198bf392006-01-06 21:52:49 +0000247** Include code that is common to all os_*.c files
248*/
249#include "os_common.h"
250
251/*
drh0ccebe72005-06-07 22:22:50 +0000252** Define various macros that are missing from some systems.
253*/
drhbbd42a62004-05-22 17:41:58 +0000254#ifndef O_LARGEFILE
255# define O_LARGEFILE 0
256#endif
257#ifdef SQLITE_DISABLE_LFS
258# undef O_LARGEFILE
259# define O_LARGEFILE 0
260#endif
261#ifndef O_NOFOLLOW
262# define O_NOFOLLOW 0
263#endif
264#ifndef O_BINARY
265# define O_BINARY 0
266#endif
267
268/*
269** The DJGPP compiler environment looks mostly like Unix, but it
270** lacks the fcntl() system call. So redefine fcntl() to be something
271** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000272** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000273*/
274#ifdef __DJGPP__
275# define fcntl(A,B,C) 0
276#endif
277
278/*
drh2b4b5962005-06-15 17:47:55 +0000279** The threadid macro resolves to the thread-id or to 0. Used for
280** testing and debugging only.
281*/
drhd677b3d2007-08-20 22:48:41 +0000282#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000283#define threadid pthread_self()
284#else
285#define threadid 0
286#endif
287
danielk197713adf8a2004-06-03 16:08:41 +0000288
drh107886a2008-11-21 22:21:50 +0000289/*
dan9359c7b2009-08-21 08:29:10 +0000290** Helper functions to obtain and relinquish the global mutex. The
291** global mutex is used to protect the unixOpenCnt, unixLockInfo and
292** vxworksFileId objects used by this file, all of which may be
293** shared by multiple threads.
294**
295** Function unixMutexHeld() is used to assert() that the global mutex
296** is held when required. This function is only used as part of assert()
297** statements. e.g.
298**
299** unixEnterMutex()
300** assert( unixMutexHeld() );
301** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000302*/
303static void unixEnterMutex(void){
304 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
305}
306static void unixLeaveMutex(void){
307 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
308}
dan9359c7b2009-08-21 08:29:10 +0000309#ifdef SQLITE_DEBUG
310static int unixMutexHeld(void) {
311 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
312}
313#endif
drh107886a2008-11-21 22:21:50 +0000314
drh734c9862008-11-28 15:37:20 +0000315
316#ifdef SQLITE_DEBUG
317/*
318** Helper function for printing out trace information from debugging
319** binaries. This returns the string represetation of the supplied
320** integer lock-type.
321*/
322static const char *locktypeName(int locktype){
323 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000324 case NO_LOCK: return "NONE";
325 case SHARED_LOCK: return "SHARED";
326 case RESERVED_LOCK: return "RESERVED";
327 case PENDING_LOCK: return "PENDING";
328 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000329 }
330 return "ERROR";
331}
332#endif
333
334#ifdef SQLITE_LOCK_TRACE
335/*
336** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000337**
drh734c9862008-11-28 15:37:20 +0000338** This routine is used for troubleshooting locks on multithreaded
339** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
340** command-line option on the compiler. This code is normally
341** turned off.
342*/
343static int lockTrace(int fd, int op, struct flock *p){
344 char *zOpName, *zType;
345 int s;
346 int savedErrno;
347 if( op==F_GETLK ){
348 zOpName = "GETLK";
349 }else if( op==F_SETLK ){
350 zOpName = "SETLK";
351 }else{
352 s = fcntl(fd, op, p);
353 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
354 return s;
355 }
356 if( p->l_type==F_RDLCK ){
357 zType = "RDLCK";
358 }else if( p->l_type==F_WRLCK ){
359 zType = "WRLCK";
360 }else if( p->l_type==F_UNLCK ){
361 zType = "UNLCK";
362 }else{
363 assert( 0 );
364 }
365 assert( p->l_whence==SEEK_SET );
366 s = fcntl(fd, op, p);
367 savedErrno = errno;
368 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
369 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
370 (int)p->l_pid, s);
371 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
372 struct flock l2;
373 l2 = *p;
374 fcntl(fd, F_GETLK, &l2);
375 if( l2.l_type==F_RDLCK ){
376 zType = "RDLCK";
377 }else if( l2.l_type==F_WRLCK ){
378 zType = "WRLCK";
379 }else if( l2.l_type==F_UNLCK ){
380 zType = "UNLCK";
381 }else{
382 assert( 0 );
383 }
384 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
385 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
386 }
387 errno = savedErrno;
388 return s;
389}
390#define fcntl lockTrace
391#endif /* SQLITE_LOCK_TRACE */
392
393
394
395/*
396** This routine translates a standard POSIX errno code into something
397** useful to the clients of the sqlite3 functions. Specifically, it is
398** intended to translate a variety of "try again" errors into SQLITE_BUSY
399** and a variety of "please close the file descriptor NOW" errors into
400** SQLITE_IOERR
401**
402** Errors during initialization of locks, or file system support for locks,
403** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
404*/
405static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
406 switch (posixError) {
407 case 0:
408 return SQLITE_OK;
409
410 case EAGAIN:
411 case ETIMEDOUT:
412 case EBUSY:
413 case EINTR:
414 case ENOLCK:
415 /* random NFS retry error, unless during file system support
416 * introspection, in which it actually means what it says */
417 return SQLITE_BUSY;
418
419 case EACCES:
420 /* EACCES is like EAGAIN during locking operations, but not any other time*/
421 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
422 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
423 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
424 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
425 return SQLITE_BUSY;
426 }
427 /* else fall through */
428 case EPERM:
429 return SQLITE_PERM;
430
431 case EDEADLK:
432 return SQLITE_IOERR_BLOCKED;
433
434#if EOPNOTSUPP!=ENOTSUP
435 case EOPNOTSUPP:
436 /* something went terribly awry, unless during file system support
437 * introspection, in which it actually means what it says */
438#endif
439#ifdef ENOTSUP
440 case ENOTSUP:
441 /* invalid fd, unless during file system support introspection, in which
442 * it actually means what it says */
443#endif
444 case EIO:
445 case EBADF:
446 case EINVAL:
447 case ENOTCONN:
448 case ENODEV:
449 case ENXIO:
450 case ENOENT:
451 case ESTALE:
452 case ENOSYS:
453 /* these should force the client to close the file and reconnect */
454
455 default:
456 return sqliteIOErr;
457 }
458}
459
460
461
462/******************************************************************************
463****************** Begin Unique File ID Utility Used By VxWorks ***************
464**
465** On most versions of unix, we can get a unique ID for a file by concatenating
466** the device number and the inode number. But this does not work on VxWorks.
467** On VxWorks, a unique file id must be based on the canonical filename.
468**
469** A pointer to an instance of the following structure can be used as a
470** unique file ID in VxWorks. Each instance of this structure contains
471** a copy of the canonical filename. There is also a reference count.
472** The structure is reclaimed when the number of pointers to it drops to
473** zero.
474**
475** There are never very many files open at one time and lookups are not
476** a performance-critical path, so it is sufficient to put these
477** structures on a linked list.
478*/
479struct vxworksFileId {
480 struct vxworksFileId *pNext; /* Next in a list of them all */
481 int nRef; /* Number of references to this one */
482 int nName; /* Length of the zCanonicalName[] string */
483 char *zCanonicalName; /* Canonical filename */
484};
485
486#if OS_VXWORKS
487/*
drh9b35ea62008-11-29 02:20:26 +0000488** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000489** variable:
490*/
491static struct vxworksFileId *vxworksFileList = 0;
492
493/*
494** Simplify a filename into its canonical form
495** by making the following changes:
496**
497** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000498** * convert /./ into just /
499** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000500**
501** Changes are made in-place. Return the new name length.
502**
503** The original filename is in z[0..n-1]. Return the number of
504** characters in the simplified name.
505*/
506static int vxworksSimplifyName(char *z, int n){
507 int i, j;
508 while( n>1 && z[n-1]=='/' ){ n--; }
509 for(i=j=0; i<n; i++){
510 if( z[i]=='/' ){
511 if( z[i+1]=='/' ) continue;
512 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
513 i += 1;
514 continue;
515 }
516 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
517 while( j>0 && z[j-1]!='/' ){ j--; }
518 if( j>0 ){ j--; }
519 i += 2;
520 continue;
521 }
522 }
523 z[j++] = z[i];
524 }
525 z[j] = 0;
526 return j;
527}
528
529/*
530** Find a unique file ID for the given absolute pathname. Return
531** a pointer to the vxworksFileId object. This pointer is the unique
532** file ID.
533**
534** The nRef field of the vxworksFileId object is incremented before
535** the object is returned. A new vxworksFileId object is created
536** and added to the global list if necessary.
537**
538** If a memory allocation error occurs, return NULL.
539*/
540static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
541 struct vxworksFileId *pNew; /* search key and new file ID */
542 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
543 int n; /* Length of zAbsoluteName string */
544
545 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000546 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000547 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
548 if( pNew==0 ) return 0;
549 pNew->zCanonicalName = (char*)&pNew[1];
550 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
551 n = vxworksSimplifyName(pNew->zCanonicalName, n);
552
553 /* Search for an existing entry that matching the canonical name.
554 ** If found, increment the reference count and return a pointer to
555 ** the existing file ID.
556 */
557 unixEnterMutex();
558 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
559 if( pCandidate->nName==n
560 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
561 ){
562 sqlite3_free(pNew);
563 pCandidate->nRef++;
564 unixLeaveMutex();
565 return pCandidate;
566 }
567 }
568
569 /* No match was found. We will make a new file ID */
570 pNew->nRef = 1;
571 pNew->nName = n;
572 pNew->pNext = vxworksFileList;
573 vxworksFileList = pNew;
574 unixLeaveMutex();
575 return pNew;
576}
577
578/*
579** Decrement the reference count on a vxworksFileId object. Free
580** the object when the reference count reaches zero.
581*/
582static void vxworksReleaseFileId(struct vxworksFileId *pId){
583 unixEnterMutex();
584 assert( pId->nRef>0 );
585 pId->nRef--;
586 if( pId->nRef==0 ){
587 struct vxworksFileId **pp;
588 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
589 assert( *pp==pId );
590 *pp = pId->pNext;
591 sqlite3_free(pId);
592 }
593 unixLeaveMutex();
594}
595#endif /* OS_VXWORKS */
596/*************** End of Unique File ID Utility Used By VxWorks ****************
597******************************************************************************/
598
599
600/******************************************************************************
601*************************** Posix Advisory Locking ****************************
602**
drh9b35ea62008-11-29 02:20:26 +0000603** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000604** section 6.5.2.2 lines 483 through 490 specify that when a process
605** sets or clears a lock, that operation overrides any prior locks set
606** by the same process. It does not explicitly say so, but this implies
607** that it overrides locks set by the same process using a different
608** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000609**
610** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000611** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
612**
613** Suppose ./file1 and ./file2 are really the same file (because
614** one is a hard or symbolic link to the other) then if you set
615** an exclusive lock on fd1, then try to get an exclusive lock
616** on fd2, it works. I would have expected the second lock to
617** fail since there was already a lock on the file due to fd1.
618** But not so. Since both locks came from the same process, the
619** second overrides the first, even though they were on different
620** file descriptors opened on different file names.
621**
drh734c9862008-11-28 15:37:20 +0000622** This means that we cannot use POSIX locks to synchronize file access
623** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000624** to synchronize access for threads in separate processes, but not
625** threads within the same process.
626**
627** To work around the problem, SQLite has to manage file locks internally
628** on its own. Whenever a new database is opened, we have to find the
629** specific inode of the database file (the inode is determined by the
630** st_dev and st_ino fields of the stat structure that fstat() fills in)
631** and check for locks already existing on that inode. When locks are
632** created or removed, we have to look at our own internal record of the
633** locks to see if another thread has previously set a lock on that same
634** inode.
635**
drh9b35ea62008-11-29 02:20:26 +0000636** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
637** For VxWorks, we have to use the alternative unique ID system based on
638** canonical filename and implemented in the previous division.)
639**
danielk1977ad94b582007-08-20 06:44:22 +0000640** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000641** descriptor. It is now a structure that holds the integer file
642** descriptor and a pointer to a structure that describes the internal
643** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000644** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000645** point to the same locking structure. The locking structure keeps
646** a reference count (so we will know when to delete it) and a "cnt"
647** field that tells us its internal lock status. cnt==0 means the
648** file is unlocked. cnt==-1 means the file has an exclusive lock.
649** cnt>0 means there are cnt shared locks on the file.
650**
651** Any attempt to lock or unlock a file first checks the locking
652** structure. The fcntl() system call is only invoked to set a
653** POSIX lock if the internal lock structure transitions between
654** a locked and an unlocked state.
655**
drh734c9862008-11-28 15:37:20 +0000656** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000657**
658** If you close a file descriptor that points to a file that has locks,
659** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000660** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000661** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000662** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000663** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000664** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000665** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000666** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000667** be closed and that list is walked (and cleared) when the last lock
668** clears.
669**
drh9b35ea62008-11-29 02:20:26 +0000670** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000671**
drh9b35ea62008-11-29 02:20:26 +0000672** Many older versions of linux use the LinuxThreads library which is
673** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000674** A cannot be modified or overridden by a different thread B.
675** Only thread A can modify the lock. Locking behavior is correct
676** if the appliation uses the newer Native Posix Thread Library (NPTL)
677** on linux - with NPTL a lock created by thread A can override locks
678** in thread B. But there is no way to know at compile-time which
679** threading library is being used. So there is no way to know at
680** compile-time whether or not thread A can override locks on thread B.
681** We have to do a run-time check to discover the behavior of the
682** current process.
drh5fdae772004-06-29 03:29:00 +0000683**
drh734c9862008-11-28 15:37:20 +0000684** On systems where thread A is unable to modify locks created by
685** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000686** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000687** structure to record this information. And on those systems it
688** is illegal to begin a transaction in one thread and finish it
689** in another. For this latter restriction, there is no work-around.
690** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000691*/
692
693/*
drh6c7d5c52008-11-21 20:32:33 +0000694** Set or check the unixFile.tid field. This field is set when an unixFile
695** is first opened. All subsequent uses of the unixFile verify that the
696** same thread is operating on the unixFile. Some operating systems do
697** not allow locks to be overridden by other threads and that restriction
698** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000699** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000700**
701** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
702** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000703** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000704** or if no locks are held. But the unixFile.pLock field needs to be
705** recomputed because its key includes the thread-id. See the
706** transferOwnership() function below for additional information
707*/
drh734c9862008-11-28 15:37:20 +0000708#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000709# define SET_THREADID(X) (X)->tid = pthread_self()
710# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
711 !pthread_equal((X)->tid, pthread_self()))
712#else
713# define SET_THREADID(X)
714# define CHECK_THREADID(X) 0
715#endif
716
717/*
drhbbd42a62004-05-22 17:41:58 +0000718** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000719** to locate a particular unixOpenCnt structure given its inode. This
720** is the same as the unixLockKey except that the thread ID is omitted.
721*/
722struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000723 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000724#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000725 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000726#else
drh107886a2008-11-21 22:21:50 +0000727 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000728#endif
729};
730
731/*
732** An instance of the following structure serves as the key used
733** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000734**
drh734c9862008-11-28 15:37:20 +0000735** If threads cannot override each others locks (LinuxThreads), then we
736** set the unixLockKey.tid field to the thread ID. If threads can override
737** each others locks (Posix and NPTL) then tid is always set to zero.
738** tid is omitted if we compile without threading support or on an OS
739** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000740*/
drh6c7d5c52008-11-21 20:32:33 +0000741struct unixLockKey {
742 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000743#if SQLITE_THREADSAFE && defined(__linux__)
744 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000745#endif
drhbbd42a62004-05-22 17:41:58 +0000746};
747
748/*
749** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000750** inode. Or, on LinuxThreads, there is one of these structures for
751** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000752**
danielk1977ad94b582007-08-20 06:44:22 +0000753** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000754** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000755** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000756*/
drh6c7d5c52008-11-21 20:32:33 +0000757struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000758 struct unixLockKey lockKey; /* The lookup key */
759 int cnt; /* Number of SHARED locks held */
760 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
761 int nRef; /* Number of pointers to this structure */
drh7ed97b92010-01-20 13:07:21 +0000762#if defined(SQLITE_ENABLE_LOCKING_STYLE)
763 unsigned long long sharedByte; /* for AFP simulated shared lock */
764#endif
drh734c9862008-11-28 15:37:20 +0000765 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
766 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000767};
768
769/*
770** An instance of the following structure is allocated for each open
771** inode. This structure keeps track of the number of locks on that
772** inode. If a close is attempted against an inode that is holding
773** locks, the close is deferred until all locks clear by adding the
774** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000775**
776** TODO: Consider changing this so that there is only a single file
777** descriptor for each open file, even when it is opened multiple times.
778** The close() system call would only occur when the last database
779** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000780*/
drh6c7d5c52008-11-21 20:32:33 +0000781struct unixOpenCnt {
782 struct unixFileId fileId; /* The lookup key */
783 int nRef; /* Number of pointers to this structure */
784 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000785 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000786#if OS_VXWORKS
787 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000788 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000789#endif
drh6c7d5c52008-11-21 20:32:33 +0000790 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000791};
792
drhda0e7682008-07-30 15:27:54 +0000793/*
drh9b35ea62008-11-29 02:20:26 +0000794** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
795** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000796** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000797** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000798*/
drh6c7d5c52008-11-21 20:32:33 +0000799static struct unixLockInfo *lockList = 0;
800static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000801
drh5fdae772004-06-29 03:29:00 +0000802/*
drh9b35ea62008-11-29 02:20:26 +0000803** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000804** locks.
805**
drh9b35ea62008-11-29 02:20:26 +0000806** 0: No. Threads cannot override each others locks. (LinuxThreads)
807** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000808** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000809**
drh5062d3a2006-01-31 23:03:35 +0000810** On some systems, we know at compile-time if threads can override each
811** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
812** will be set appropriately. On other systems, we have to check at
813** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
814** undefined.
815**
drhf1a221e2006-01-15 17:27:17 +0000816** This variable normally has file scope only. But during testing, we make
817** it a global so that the test code can change its value in order to verify
818** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000819*/
drh715ff302008-12-03 22:32:44 +0000820#if SQLITE_THREADSAFE && defined(__linux__)
821# ifndef SQLITE_THREAD_OVERRIDE_LOCK
822# define SQLITE_THREAD_OVERRIDE_LOCK -1
823# endif
824# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000825int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000826# else
drh5062d3a2006-01-31 23:03:35 +0000827static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000828# endif
drh029b44b2006-01-15 00:13:15 +0000829#endif
drh5fdae772004-06-29 03:29:00 +0000830
831/*
832** This structure holds information passed into individual test
833** threads by the testThreadLockingBehavior() routine.
834*/
835struct threadTestData {
836 int fd; /* File to be locked */
837 struct flock lock; /* The locking operation */
838 int result; /* Result of the locking operation */
839};
840
drh6c7d5c52008-11-21 20:32:33 +0000841#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000842/*
danielk197741a6a612008-11-11 18:34:35 +0000843** This function is used as the main routine for a thread launched by
844** testThreadLockingBehavior(). It tests whether the shared-lock obtained
845** by the main thread in testThreadLockingBehavior() conflicts with a
846** hypothetical write-lock obtained by this thread on the same file.
847**
848** The write-lock is not actually acquired, as this is not possible if
849** the file is open in read-only mode (see ticket #3472).
850*/
drh5fdae772004-06-29 03:29:00 +0000851static void *threadLockingTest(void *pArg){
852 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000853 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000854 return pArg;
855}
drh6c7d5c52008-11-21 20:32:33 +0000856#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000857
drh6c7d5c52008-11-21 20:32:33 +0000858
859#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000860/*
861** This procedure attempts to determine whether or not threads
862** can override each others locks then sets the
863** threadsOverrideEachOthersLocks variable appropriately.
864*/
danielk19774d5238f2006-01-27 06:32:00 +0000865static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000866 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000867 int rc;
868 struct threadTestData d;
869 struct flock l;
870 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000871
872 fd = dup(fd_orig);
873 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000874 memset(&l, 0, sizeof(l));
875 l.l_type = F_RDLCK;
876 l.l_len = 1;
877 l.l_start = 0;
878 l.l_whence = SEEK_SET;
879 rc = fcntl(fd_orig, F_SETLK, &l);
880 if( rc!=0 ) return;
881 memset(&d, 0, sizeof(d));
882 d.fd = fd;
883 d.lock = l;
884 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000885 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
886 pthread_join(t, 0);
887 }
drh5fdae772004-06-29 03:29:00 +0000888 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000889 if( d.result!=0 ) return;
890 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000891}
drh06150f92009-07-03 12:57:58 +0000892#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000893
drhbbd42a62004-05-22 17:41:58 +0000894/*
drh6c7d5c52008-11-21 20:32:33 +0000895** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000896**
897** The mutex entered using the unixEnterMutex() function must be held
898** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000899*/
900static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000901 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000902 if( pLock ){
903 pLock->nRef--;
904 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000905 if( pLock->pPrev ){
906 assert( pLock->pPrev->pNext==pLock );
907 pLock->pPrev->pNext = pLock->pNext;
908 }else{
909 assert( lockList==pLock );
910 lockList = pLock->pNext;
911 }
912 if( pLock->pNext ){
913 assert( pLock->pNext->pPrev==pLock );
914 pLock->pNext->pPrev = pLock->pPrev;
915 }
danielk1977e339d652008-06-28 11:23:00 +0000916 sqlite3_free(pLock);
917 }
drhbbd42a62004-05-22 17:41:58 +0000918 }
919}
920
921/*
drh6c7d5c52008-11-21 20:32:33 +0000922** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000923**
924** The mutex entered using the unixEnterMutex() function must be held
925** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000926*/
drh6c7d5c52008-11-21 20:32:33 +0000927static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000928 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000929 if( pOpen ){
930 pOpen->nRef--;
931 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000932 if( pOpen->pPrev ){
933 assert( pOpen->pPrev->pNext==pOpen );
934 pOpen->pPrev->pNext = pOpen->pNext;
935 }else{
936 assert( openList==pOpen );
937 openList = pOpen->pNext;
938 }
939 if( pOpen->pNext ){
940 assert( pOpen->pNext->pPrev==pOpen );
941 pOpen->pNext->pPrev = pOpen->pPrev;
942 }
drh08da4bb2009-09-10 19:20:03 +0000943#if SQLITE_THREADSAFE && defined(__linux__)
dan11b38792009-09-09 18:46:52 +0000944 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
drh08da4bb2009-09-10 19:20:03 +0000945#endif
dan11b38792009-09-09 18:46:52 +0000946
947 /* If pOpen->pUnused is not null, then memory and file-descriptors
948 ** are leaked.
949 **
950 ** This will only happen if, under Linuxthreads, the user has opened
951 ** a transaction in one thread, then attempts to close the database
952 ** handle from another thread (without first unlocking the db file).
953 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000954 sqlite3_free(pOpen);
955 }
drhbbd42a62004-05-22 17:41:58 +0000956 }
957}
958
drh6c7d5c52008-11-21 20:32:33 +0000959/*
960** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
961** describes that file descriptor. Create new ones if necessary. The
962** return values might be uninitialized if an error occurs.
963**
dan9359c7b2009-08-21 08:29:10 +0000964** The mutex entered using the unixEnterMutex() function must be held
965** when this function is called.
966**
drh6c7d5c52008-11-21 20:32:33 +0000967** Return an appropriate error code.
968*/
969static int findLockInfo(
970 unixFile *pFile, /* Unix file with file desc used in the key */
971 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
972 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
973){
974 int rc; /* System call return code */
975 int fd; /* The file descriptor for pFile */
976 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
977 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
978 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000979 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000980 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
981
dan9359c7b2009-08-21 08:29:10 +0000982 assert( unixMutexHeld() );
983
drh6c7d5c52008-11-21 20:32:33 +0000984 /* Get low-level information about the file that we can used to
985 ** create a unique name for the file.
986 */
987 fd = pFile->h;
988 rc = fstat(fd, &statbuf);
989 if( rc!=0 ){
990 pFile->lastErrno = errno;
991#ifdef EOVERFLOW
992 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
993#endif
994 return SQLITE_IOERR;
995 }
996
drheb0d74f2009-02-03 15:27:02 +0000997#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000998 /* On OS X on an msdos filesystem, the inode number is reported
999 ** incorrectly for zero-size files. See ticket #3260. To work
1000 ** around this problem (we consider it a bug in OS X, not SQLite)
1001 ** we always increase the file size to 1 by writing a single byte
1002 ** prior to accessing the inode number. The one byte written is
1003 ** an ASCII 'S' character which also happens to be the first byte
1004 ** in the header of every SQLite database. In this way, if there
1005 ** is a race condition such that another thread has already populated
1006 ** the first page of the database, no damage is done.
1007 */
drh7ed97b92010-01-20 13:07:21 +00001008 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +00001009 rc = write(fd, "S", 1);
1010 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001011 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001012 return SQLITE_IOERR;
1013 }
drh6c7d5c52008-11-21 20:32:33 +00001014 rc = fstat(fd, &statbuf);
1015 if( rc!=0 ){
1016 pFile->lastErrno = errno;
1017 return SQLITE_IOERR;
1018 }
1019 }
drheb0d74f2009-02-03 15:27:02 +00001020#endif
drh6c7d5c52008-11-21 20:32:33 +00001021
1022 memset(&lockKey, 0, sizeof(lockKey));
1023 lockKey.fid.dev = statbuf.st_dev;
1024#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001025 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001026#else
1027 lockKey.fid.ino = statbuf.st_ino;
1028#endif
drh734c9862008-11-28 15:37:20 +00001029#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001030 if( threadsOverrideEachOthersLocks<0 ){
1031 testThreadLockingBehavior(fd);
1032 }
1033 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1034#endif
1035 fileId = lockKey.fid;
1036 if( ppLock!=0 ){
1037 pLock = lockList;
1038 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1039 pLock = pLock->pNext;
1040 }
1041 if( pLock==0 ){
1042 pLock = sqlite3_malloc( sizeof(*pLock) );
1043 if( pLock==0 ){
1044 rc = SQLITE_NOMEM;
1045 goto exit_findlockinfo;
1046 }
drh9b5db1d2009-10-07 23:42:25 +00001047 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
drh6c7d5c52008-11-21 20:32:33 +00001048 pLock->nRef = 1;
1049 pLock->cnt = 0;
1050 pLock->locktype = 0;
drh7ed97b92010-01-20 13:07:21 +00001051#if defined(SQLITE_ENABLE_LOCKING_STYLE)
1052 pLock->sharedByte = 0;
1053#endif
drh6c7d5c52008-11-21 20:32:33 +00001054 pLock->pNext = lockList;
1055 pLock->pPrev = 0;
1056 if( lockList ) lockList->pPrev = pLock;
1057 lockList = pLock;
1058 }else{
1059 pLock->nRef++;
1060 }
1061 *ppLock = pLock;
1062 }
1063 if( ppOpen!=0 ){
1064 pOpen = openList;
1065 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1066 pOpen = pOpen->pNext;
1067 }
1068 if( pOpen==0 ){
1069 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1070 if( pOpen==0 ){
1071 releaseLockInfo(pLock);
1072 rc = SQLITE_NOMEM;
1073 goto exit_findlockinfo;
1074 }
dane946c392009-08-22 11:39:46 +00001075 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001076 pOpen->fileId = fileId;
1077 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001078 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001079 if( openList ) openList->pPrev = pOpen;
1080 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001081 }else{
1082 pOpen->nRef++;
1083 }
1084 *ppOpen = pOpen;
1085 }
1086
1087exit_findlockinfo:
1088 return rc;
1089}
drh6c7d5c52008-11-21 20:32:33 +00001090
drh7708e972008-11-29 00:56:52 +00001091/*
1092** If we are currently in a different thread than the thread that the
1093** unixFile argument belongs to, then transfer ownership of the unixFile
1094** over to the current thread.
1095**
1096** A unixFile is only owned by a thread on systems that use LinuxThreads.
1097**
1098** Ownership transfer is only allowed if the unixFile is currently unlocked.
1099** If the unixFile is locked and an ownership is wrong, then return
1100** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1101*/
1102#if SQLITE_THREADSAFE && defined(__linux__)
1103static int transferOwnership(unixFile *pFile){
1104 int rc;
1105 pthread_t hSelf;
1106 if( threadsOverrideEachOthersLocks ){
1107 /* Ownership transfers not needed on this system */
1108 return SQLITE_OK;
1109 }
1110 hSelf = pthread_self();
1111 if( pthread_equal(pFile->tid, hSelf) ){
1112 /* We are still in the same thread */
1113 OSTRACE1("No-transfer, same thread\n");
1114 return SQLITE_OK;
1115 }
1116 if( pFile->locktype!=NO_LOCK ){
1117 /* We cannot change ownership while we are holding a lock! */
drh413c3d32010-02-23 20:11:56 +00001118 return SQLITE_MISUSE_BKPT;
drh7708e972008-11-29 00:56:52 +00001119 }
1120 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1121 pFile->h, pFile->tid, hSelf);
1122 pFile->tid = hSelf;
1123 if (pFile->pLock != NULL) {
1124 releaseLockInfo(pFile->pLock);
1125 rc = findLockInfo(pFile, &pFile->pLock, 0);
1126 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1127 locktypeName(pFile->locktype),
1128 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1129 return rc;
1130 } else {
1131 return SQLITE_OK;
1132 }
1133}
1134#else /* if not SQLITE_THREADSAFE */
1135 /* On single-threaded builds, ownership transfer is a no-op */
1136# define transferOwnership(X) SQLITE_OK
1137#endif /* SQLITE_THREADSAFE */
1138
aswift5b1a2562008-08-22 00:22:35 +00001139
1140/*
danielk197713adf8a2004-06-03 16:08:41 +00001141** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001142** file by this or any other process. If such a lock is held, set *pResOut
1143** to a non-zero value otherwise *pResOut is set to zero. The return value
1144** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001145*/
danielk1977861f7452008-06-05 11:39:11 +00001146static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001147 int rc = SQLITE_OK;
1148 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001149 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001150
danielk1977861f7452008-06-05 11:39:11 +00001151 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1152
drh054889e2005-11-30 03:20:31 +00001153 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001154 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001155
1156 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001157 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001158 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001159 }
1160
drh2ac3ee92004-06-07 16:27:46 +00001161 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001162 */
danielk197709480a92009-02-09 05:32:32 +00001163#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001164 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001165 struct flock lock;
1166 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001167 lock.l_start = RESERVED_BYTE;
1168 lock.l_len = 1;
1169 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001170 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1171 int tErrno = errno;
1172 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1173 pFile->lastErrno = tErrno;
1174 } else if( lock.l_type!=F_UNLCK ){
1175 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001176 }
1177 }
danielk197709480a92009-02-09 05:32:32 +00001178#endif
danielk197713adf8a2004-06-03 16:08:41 +00001179
drh6c7d5c52008-11-21 20:32:33 +00001180 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001181 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001182
aswift5b1a2562008-08-22 00:22:35 +00001183 *pResOut = reserved;
1184 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001185}
1186
1187/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001188** Lock the file with the lock specified by parameter locktype - one
1189** of the following:
1190**
drh2ac3ee92004-06-07 16:27:46 +00001191** (1) SHARED_LOCK
1192** (2) RESERVED_LOCK
1193** (3) PENDING_LOCK
1194** (4) EXCLUSIVE_LOCK
1195**
drhb3e04342004-06-08 00:47:47 +00001196** Sometimes when requesting one lock state, additional lock states
1197** are inserted in between. The locking might fail on one of the later
1198** transitions leaving the lock state different from what it started but
1199** still short of its goal. The following chart shows the allowed
1200** transitions and the inserted intermediate states:
1201**
1202** UNLOCKED -> SHARED
1203** SHARED -> RESERVED
1204** SHARED -> (PENDING) -> EXCLUSIVE
1205** RESERVED -> (PENDING) -> EXCLUSIVE
1206** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001207**
drha6abd042004-06-09 17:37:22 +00001208** This routine will only increase a lock. Use the sqlite3OsUnlock()
1209** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001210*/
danielk197762079062007-08-15 17:08:46 +00001211static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001212 /* The following describes the implementation of the various locks and
1213 ** lock transitions in terms of the POSIX advisory shared and exclusive
1214 ** lock primitives (called read-locks and write-locks below, to avoid
1215 ** confusion with SQLite lock names). The algorithms are complicated
1216 ** slightly in order to be compatible with windows systems simultaneously
1217 ** accessing the same database file, in case that is ever required.
1218 **
1219 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1220 ** byte', each single bytes at well known offsets, and the 'shared byte
1221 ** range', a range of 510 bytes at a well known offset.
1222 **
1223 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1224 ** byte'. If this is successful, a random byte from the 'shared byte
1225 ** range' is read-locked and the lock on the 'pending byte' released.
1226 **
danielk197790ba3bd2004-06-25 08:32:25 +00001227 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1228 ** A RESERVED lock is implemented by grabbing a write-lock on the
1229 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001230 **
1231 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001232 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1233 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1234 ** obtained, but existing SHARED locks are allowed to persist. A process
1235 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1236 ** This property is used by the algorithm for rolling back a journal file
1237 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001238 **
danielk197790ba3bd2004-06-25 08:32:25 +00001239 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1240 ** implemented by obtaining a write-lock on the entire 'shared byte
1241 ** range'. Since all other locks require a read-lock on one of the bytes
1242 ** within this range, this ensures that no other locks are held on the
1243 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001244 **
1245 ** The reason a single byte cannot be used instead of the 'shared byte
1246 ** range' is that some versions of windows do not support read-locks. By
1247 ** locking a random byte from a range, concurrent SHARED locks may exist
1248 ** even if the locking primitive used is always a write-lock.
1249 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001250 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001251 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001252 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001253 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001254 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001255 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001256
drh054889e2005-11-30 03:20:31 +00001257 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001258 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001259 locktypeName(locktype), locktypeName(pFile->locktype),
1260 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001261
1262 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001263 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001264 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001265 */
drh054889e2005-11-30 03:20:31 +00001266 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00001267 OSTRACE3("LOCK %d %s ok (already held) (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001268 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001269 return SQLITE_OK;
1270 }
1271
drh0c2694b2009-09-03 16:23:44 +00001272 /* Make sure the locking sequence is correct.
1273 ** (1) We never move from unlocked to anything higher than shared lock.
1274 ** (2) SQLite never explicitly requests a pendig lock.
1275 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001276 */
drh054889e2005-11-30 03:20:31 +00001277 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001278 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001279 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001280
drh054889e2005-11-30 03:20:31 +00001281 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001282 */
drh6c7d5c52008-11-21 20:32:33 +00001283 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001284
drh029b44b2006-01-15 00:13:15 +00001285 /* Make sure the current thread owns the pFile.
1286 */
1287 rc = transferOwnership(pFile);
1288 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001289 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001290 return rc;
1291 }
drh64b1bea2006-01-15 02:30:57 +00001292 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001293
danielk1977ad94b582007-08-20 06:44:22 +00001294 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 ** handle that precludes the requested lock, return BUSY.
1296 */
drh054889e2005-11-30 03:20:31 +00001297 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001298 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 ){
1300 rc = SQLITE_BUSY;
1301 goto end_lock;
1302 }
1303
1304 /* If a SHARED lock is requested, and some thread using this PID already
1305 ** has a SHARED or RESERVED lock, then increment reference counts and
1306 ** return SQLITE_OK.
1307 */
1308 if( locktype==SHARED_LOCK &&
1309 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1310 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001311 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001312 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001313 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001314 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001315 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 goto end_lock;
1317 }
1318
danielk19779a1d0ab2004-06-01 14:09:28 +00001319
drh3cde3bb2004-06-12 02:17:14 +00001320 /* A PENDING lock is needed before acquiring a SHARED lock and before
1321 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1322 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 */
drh0c2694b2009-09-03 16:23:44 +00001324 lock.l_len = 1L;
1325 lock.l_whence = SEEK_SET;
drh3cde3bb2004-06-12 02:17:14 +00001326 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001327 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001328 ){
danielk1977489468c2004-06-28 08:25:47 +00001329 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001330 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001331 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001332 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001333 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001334 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1335 if( IS_LOCK_ERROR(rc) ){
1336 pFile->lastErrno = tErrno;
1337 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001338 goto end_lock;
1339 }
drh3cde3bb2004-06-12 02:17:14 +00001340 }
1341
1342
1343 /* If control gets to this point, then actually go ahead and make
1344 ** operating system calls for the specified lock.
1345 */
1346 if( locktype==SHARED_LOCK ){
1347 assert( pLock->cnt==0 );
1348 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001349
drh2ac3ee92004-06-07 16:27:46 +00001350 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001351 lock.l_start = SHARED_FIRST;
1352 lock.l_len = SHARED_SIZE;
1353 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1354 tErrno = errno;
1355 }
drh2ac3ee92004-06-07 16:27:46 +00001356 /* Drop the temporary PENDING lock */
1357 lock.l_start = PENDING_BYTE;
1358 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001359 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001360 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001361 if( s != -1 ){
1362 /* This could happen with a network mount */
1363 tErrno = errno;
1364 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1365 if( IS_LOCK_ERROR(rc) ){
1366 pFile->lastErrno = tErrno;
1367 }
1368 goto end_lock;
1369 }
drh2b4b5962005-06-15 17:47:55 +00001370 }
drhe2396a12007-03-29 20:19:58 +00001371 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001372 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1373 if( IS_LOCK_ERROR(rc) ){
1374 pFile->lastErrno = tErrno;
1375 }
drhbbd42a62004-05-22 17:41:58 +00001376 }else{
drh054889e2005-11-30 03:20:31 +00001377 pFile->locktype = SHARED_LOCK;
1378 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001379 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001380 }
drh3cde3bb2004-06-12 02:17:14 +00001381 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1382 /* We are trying for an exclusive lock but another thread in this
1383 ** same process is still holding a shared lock. */
1384 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001385 }else{
drh3cde3bb2004-06-12 02:17:14 +00001386 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001387 ** assumed that there is a SHARED or greater lock on the file
1388 ** already.
1389 */
drh054889e2005-11-30 03:20:31 +00001390 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 lock.l_type = F_WRLCK;
1392 switch( locktype ){
1393 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001394 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001395 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001397 lock.l_start = SHARED_FIRST;
1398 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001399 break;
1400 default:
1401 assert(0);
1402 }
drh7ed97b92010-01-20 13:07:21 +00001403 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001404 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001405 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1407 if( IS_LOCK_ERROR(rc) ){
1408 pFile->lastErrno = tErrno;
1409 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001410 }
drhbbd42a62004-05-22 17:41:58 +00001411 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001412
drh8f941bc2009-01-14 23:03:40 +00001413
1414#ifndef NDEBUG
1415 /* Set up the transaction-counter change checking flags when
1416 ** transitioning from a SHARED to a RESERVED lock. The change
1417 ** from SHARED to RESERVED marks the beginning of a normal
1418 ** write operation (not a hot journal rollback).
1419 */
1420 if( rc==SQLITE_OK
1421 && pFile->locktype<=SHARED_LOCK
1422 && locktype==RESERVED_LOCK
1423 ){
1424 pFile->transCntrChng = 0;
1425 pFile->dbUpdate = 0;
1426 pFile->inNormalWrite = 1;
1427 }
1428#endif
1429
1430
danielk1977ecb2a962004-06-02 06:30:16 +00001431 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001432 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001433 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001434 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001435 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001436 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001437 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001438
1439end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001440 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001441 OSTRACE4("LOCK %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001442 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001443 return rc;
1444}
1445
1446/*
dane946c392009-08-22 11:39:46 +00001447** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1448** If all such file descriptors are closed without error, the list is
1449** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001450**
1451** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001452** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001453** not deleted and SQLITE_IOERR_CLOSE returned.
1454*/
1455static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001456 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001457 struct unixOpenCnt *pOpen = pFile->pOpen;
1458 UnixUnusedFd *pError = 0;
1459 UnixUnusedFd *p;
1460 UnixUnusedFd *pNext;
1461 for(p=pOpen->pUnused; p; p=pNext){
1462 pNext = p->pNext;
1463 if( close(p->fd) ){
1464 pFile->lastErrno = errno;
1465 rc = SQLITE_IOERR_CLOSE;
1466 p->pNext = pError;
1467 pError = p;
dane946c392009-08-22 11:39:46 +00001468 }else{
1469 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001470 }
1471 }
dane946c392009-08-22 11:39:46 +00001472 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001473 return rc;
1474}
1475
1476/*
1477** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001478** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001479*/
1480static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001481 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001482 UnixUnusedFd *p = pFile->pUnused;
1483 p->pNext = pOpen->pUnused;
1484 pOpen->pUnused = p;
1485 pFile->h = -1;
1486 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001487}
1488
1489/*
drh054889e2005-11-30 03:20:31 +00001490** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001491** must be either NO_LOCK or SHARED_LOCK.
1492**
1493** If the locking level of the file descriptor is already at or below
1494** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001495**
1496** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1497** the byte range is divided into 2 parts and the first part is unlocked then
1498** set to a read lock, then the other part is simply unlocked. This works
1499** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1500** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001501*/
drh7ed97b92010-01-20 13:07:21 +00001502static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
1503 unixFile *pFile = (unixFile*)id;
1504 struct unixLockInfo *pLock;
1505 struct flock lock;
1506 int rc = SQLITE_OK;
1507 int h;
drh0c2694b2009-09-03 16:23:44 +00001508 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001509
drh054889e2005-11-30 03:20:31 +00001510 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001511 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001512 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001513
1514 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001515 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001516 return SQLITE_OK;
1517 }
drhf1a221e2006-01-15 17:27:17 +00001518 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00001519 return SQLITE_MISUSE_BKPT;
drhf1a221e2006-01-15 17:27:17 +00001520 }
drh6c7d5c52008-11-21 20:32:33 +00001521 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001522 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001523 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001524 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001525 if( pFile->locktype>SHARED_LOCK ){
1526 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001527 SimulateIOErrorBenign(1);
1528 SimulateIOError( h=(-1) )
1529 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001530
1531#ifndef NDEBUG
1532 /* When reducing a lock such that other processes can start
1533 ** reading the database file again, make sure that the
1534 ** transaction counter was updated if any part of the database
1535 ** file changed. If the transaction counter is not updated,
1536 ** other connections to the same file might not realize that
1537 ** the file has changed and hence might not know to flush their
1538 ** cache. The use of a stale cache can lead to database corruption.
1539 */
1540 assert( pFile->inNormalWrite==0
1541 || pFile->dbUpdate==0
1542 || pFile->transCntrChng==1 );
1543 pFile->inNormalWrite = 0;
1544#endif
1545
drh7ed97b92010-01-20 13:07:21 +00001546 /* downgrading to a shared lock on NFS involves clearing the write lock
1547 ** before establishing the readlock - to avoid a race condition we downgrade
1548 ** the lock in 2 blocks, so that part of the range will be covered by a
1549 ** write lock until the rest is covered by a read lock:
1550 ** 1: [WWWWW]
1551 ** 2: [....W]
1552 ** 3: [RRRRW]
1553 ** 4: [RRRR.]
1554 */
drh9c105bb2004-10-02 20:38:28 +00001555 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001556 if( handleNFSUnlock ){
1557 off_t divSize = SHARED_SIZE - 1;
1558
1559 lock.l_type = F_UNLCK;
1560 lock.l_whence = SEEK_SET;
1561 lock.l_start = SHARED_FIRST;
1562 lock.l_len = divSize;
1563 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001564 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001565 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1566 if( IS_LOCK_ERROR(rc) ){
1567 pFile->lastErrno = tErrno;
1568 }
1569 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001570 }
drh7ed97b92010-01-20 13:07:21 +00001571 lock.l_type = F_RDLCK;
1572 lock.l_whence = SEEK_SET;
1573 lock.l_start = SHARED_FIRST;
1574 lock.l_len = divSize;
1575 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001576 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001577 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1578 if( IS_LOCK_ERROR(rc) ){
1579 pFile->lastErrno = tErrno;
1580 }
1581 goto end_unlock;
1582 }
1583 lock.l_type = F_UNLCK;
1584 lock.l_whence = SEEK_SET;
1585 lock.l_start = SHARED_FIRST+divSize;
1586 lock.l_len = SHARED_SIZE-divSize;
1587 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001588 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001589 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1590 if( IS_LOCK_ERROR(rc) ){
1591 pFile->lastErrno = tErrno;
1592 }
1593 goto end_unlock;
1594 }
1595 }else{
1596 lock.l_type = F_RDLCK;
1597 lock.l_whence = SEEK_SET;
1598 lock.l_start = SHARED_FIRST;
1599 lock.l_len = SHARED_SIZE;
1600 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001601 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001602 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1603 if( IS_LOCK_ERROR(rc) ){
1604 pFile->lastErrno = tErrno;
1605 }
1606 goto end_unlock;
1607 }
drh9c105bb2004-10-02 20:38:28 +00001608 }
1609 }
drhbbd42a62004-05-22 17:41:58 +00001610 lock.l_type = F_UNLCK;
1611 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001612 lock.l_start = PENDING_BYTE;
1613 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001614 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001615 pLock->locktype = SHARED_LOCK;
1616 }else{
drh0c2694b2009-09-03 16:23:44 +00001617 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001618 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1619 if( IS_LOCK_ERROR(rc) ){
1620 pFile->lastErrno = tErrno;
1621 }
drhcd731cf2009-03-28 23:23:02 +00001622 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001623 }
drhbbd42a62004-05-22 17:41:58 +00001624 }
drha6abd042004-06-09 17:37:22 +00001625 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001626 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001627
drha6abd042004-06-09 17:37:22 +00001628 /* Decrement the shared lock counter. Release the lock using an
1629 ** OS call only when all threads in this same process have released
1630 ** the lock.
1631 */
1632 pLock->cnt--;
1633 if( pLock->cnt==0 ){
1634 lock.l_type = F_UNLCK;
1635 lock.l_whence = SEEK_SET;
1636 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001637 SimulateIOErrorBenign(1);
1638 SimulateIOError( h=(-1) )
1639 SimulateIOErrorBenign(0);
1640 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001641 pLock->locktype = NO_LOCK;
1642 }else{
drh0c2694b2009-09-03 16:23:44 +00001643 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001644 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001645 if( IS_LOCK_ERROR(rc) ){
1646 pFile->lastErrno = tErrno;
1647 }
drhf48f9ca2009-03-28 23:47:10 +00001648 pLock->locktype = NO_LOCK;
1649 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001650 }
drha6abd042004-06-09 17:37:22 +00001651 }
1652
drhbbd42a62004-05-22 17:41:58 +00001653 /* Decrement the count of locks against this same file. When the
1654 ** count reaches zero, close any other file descriptors whose close
1655 ** was deferred because of outstanding locks.
1656 */
danielk197764a54c52009-03-30 07:39:35 +00001657 pOpen = pFile->pOpen;
1658 pOpen->nLock--;
1659 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001660 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001661 int rc2 = closePendingFds(pFile);
1662 if( rc==SQLITE_OK ){
1663 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001664 }
drhbbd42a62004-05-22 17:41:58 +00001665 }
1666 }
aswift5b1a2562008-08-22 00:22:35 +00001667
1668end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001669 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001670 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001671 return rc;
drhbbd42a62004-05-22 17:41:58 +00001672}
1673
1674/*
drh7ed97b92010-01-20 13:07:21 +00001675** Lower the locking level on file descriptor pFile to locktype. locktype
1676** must be either NO_LOCK or SHARED_LOCK.
1677**
1678** If the locking level of the file descriptor is already at or below
1679** the requested locking level, this routine is a no-op.
1680*/
1681static int unixUnlock(sqlite3_file *id, int locktype){
1682 return _posixUnlock(id, locktype, 0);
1683}
1684
1685/*
danielk1977e339d652008-06-28 11:23:00 +00001686** This function performs the parts of the "close file" operation
1687** common to all locking schemes. It closes the directory and file
1688** handles, if they are valid, and sets all fields of the unixFile
1689** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001690**
1691** It is *not* necessary to hold the mutex when this routine is called,
1692** even on VxWorks. A mutex will be acquired on VxWorks by the
1693** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001694*/
1695static int closeUnixFile(sqlite3_file *id){
1696 unixFile *pFile = (unixFile*)id;
1697 if( pFile ){
1698 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001699 int err = close(pFile->dirfd);
1700 if( err ){
1701 pFile->lastErrno = errno;
1702 return SQLITE_IOERR_DIR_CLOSE;
1703 }else{
1704 pFile->dirfd=-1;
1705 }
danielk1977e339d652008-06-28 11:23:00 +00001706 }
1707 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001708 int err = close(pFile->h);
1709 if( err ){
1710 pFile->lastErrno = errno;
1711 return SQLITE_IOERR_CLOSE;
1712 }
danielk1977e339d652008-06-28 11:23:00 +00001713 }
drh6c7d5c52008-11-21 20:32:33 +00001714#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001715 if( pFile->pId ){
1716 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001717 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001718 }
drh107886a2008-11-21 22:21:50 +00001719 vxworksReleaseFileId(pFile->pId);
1720 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001721 }
1722#endif
danielk1977e339d652008-06-28 11:23:00 +00001723 OSTRACE2("CLOSE %-3d\n", pFile->h);
1724 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001725 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001726 memset(pFile, 0, sizeof(unixFile));
1727 }
1728 return SQLITE_OK;
1729}
1730
1731/*
danielk1977e3026632004-06-22 11:29:02 +00001732** Close a file.
1733*/
danielk197762079062007-08-15 17:08:46 +00001734static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001735 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001736 if( id ){
1737 unixFile *pFile = (unixFile *)id;
1738 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001739 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001740 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001741 /* If there are outstanding locks, do not actually close the file just
1742 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001743 ** descriptor to pOpen->pUnused list. It will be automatically closed
1744 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001745 */
dan08da86a2009-08-21 17:18:03 +00001746 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001747 }
danielk1977e339d652008-06-28 11:23:00 +00001748 releaseLockInfo(pFile->pLock);
1749 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001750 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001751 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001752 }
aswiftaebf4132008-11-21 00:10:35 +00001753 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001754}
1755
drh734c9862008-11-28 15:37:20 +00001756/************** End of the posix advisory lock implementation *****************
1757******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001758
drh734c9862008-11-28 15:37:20 +00001759/******************************************************************************
1760****************************** No-op Locking **********************************
1761**
1762** Of the various locking implementations available, this is by far the
1763** simplest: locking is ignored. No attempt is made to lock the database
1764** file for reading or writing.
1765**
1766** This locking mode is appropriate for use on read-only databases
1767** (ex: databases that are burned into CD-ROM, for example.) It can
1768** also be used if the application employs some external mechanism to
1769** prevent simultaneous access of the same database by two or more
1770** database connections. But there is a serious risk of database
1771** corruption if this locking mode is used in situations where multiple
1772** database connections are accessing the same database file at the same
1773** time and one or more of those connections are writing.
1774*/
drhbfe66312006-10-03 17:40:40 +00001775
drh734c9862008-11-28 15:37:20 +00001776static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1777 UNUSED_PARAMETER(NotUsed);
1778 *pResOut = 0;
1779 return SQLITE_OK;
1780}
drh734c9862008-11-28 15:37:20 +00001781static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1782 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1783 return SQLITE_OK;
1784}
drh734c9862008-11-28 15:37:20 +00001785static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1786 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1787 return SQLITE_OK;
1788}
1789
1790/*
drh9b35ea62008-11-29 02:20:26 +00001791** Close the file.
drh734c9862008-11-28 15:37:20 +00001792*/
1793static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001794 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001795}
1796
1797/******************* End of the no-op lock implementation *********************
1798******************************************************************************/
1799
1800/******************************************************************************
1801************************* Begin dot-file Locking ******************************
1802**
drh0c2694b2009-09-03 16:23:44 +00001803** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001804** files in order to control access to the database. This works on just
1805** about every filesystem imaginable. But there are serious downsides:
1806**
1807** (1) There is zero concurrency. A single reader blocks all other
1808** connections from reading or writing the database.
1809**
1810** (2) An application crash or power loss can leave stale lock files
1811** sitting around that need to be cleared manually.
1812**
1813** Nevertheless, a dotlock is an appropriate locking mode for use if no
1814** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001815**
1816** Dotfile locking works by creating a file in the same directory as the
1817** database and with the same name but with a ".lock" extension added.
1818** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1819** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001820*/
1821
1822/*
1823** The file suffix added to the data base filename in order to create the
1824** lock file.
1825*/
1826#define DOTLOCK_SUFFIX ".lock"
1827
drh7708e972008-11-29 00:56:52 +00001828/*
1829** This routine checks if there is a RESERVED lock held on the specified
1830** file by this or any other process. If such a lock is held, set *pResOut
1831** to a non-zero value otherwise *pResOut is set to zero. The return value
1832** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1833**
1834** In dotfile locking, either a lock exists or it does not. So in this
1835** variation of CheckReservedLock(), *pResOut is set to true if any lock
1836** is held on the file and false if the file is unlocked.
1837*/
drh734c9862008-11-28 15:37:20 +00001838static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1839 int rc = SQLITE_OK;
1840 int reserved = 0;
1841 unixFile *pFile = (unixFile*)id;
1842
1843 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1844
1845 assert( pFile );
1846
1847 /* Check if a thread in this process holds such a lock */
1848 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001849 /* Either this connection or some other connection in the same process
1850 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001851 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001852 }else{
1853 /* The lock is held if and only if the lockfile exists */
1854 const char *zLockFile = (const char*)pFile->lockingContext;
1855 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001856 }
drh476bda72009-12-04 14:25:18 +00001857 OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001858 *pResOut = reserved;
1859 return rc;
1860}
1861
drh7708e972008-11-29 00:56:52 +00001862/*
1863** Lock the file with the lock specified by parameter locktype - one
1864** of the following:
1865**
1866** (1) SHARED_LOCK
1867** (2) RESERVED_LOCK
1868** (3) PENDING_LOCK
1869** (4) EXCLUSIVE_LOCK
1870**
1871** Sometimes when requesting one lock state, additional lock states
1872** are inserted in between. The locking might fail on one of the later
1873** transitions leaving the lock state different from what it started but
1874** still short of its goal. The following chart shows the allowed
1875** transitions and the inserted intermediate states:
1876**
1877** UNLOCKED -> SHARED
1878** SHARED -> RESERVED
1879** SHARED -> (PENDING) -> EXCLUSIVE
1880** RESERVED -> (PENDING) -> EXCLUSIVE
1881** PENDING -> EXCLUSIVE
1882**
1883** This routine will only increase a lock. Use the sqlite3OsUnlock()
1884** routine to lower a locking level.
1885**
1886** With dotfile locking, we really only support state (4): EXCLUSIVE.
1887** But we track the other locking levels internally.
1888*/
drh734c9862008-11-28 15:37:20 +00001889static int dotlockLock(sqlite3_file *id, int locktype) {
1890 unixFile *pFile = (unixFile*)id;
1891 int fd;
1892 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001893 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001894
drh7708e972008-11-29 00:56:52 +00001895
1896 /* If we have any lock, then the lock file already exists. All we have
1897 ** to do is adjust our internal record of the lock level.
1898 */
1899 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001900 pFile->locktype = locktype;
1901#if !OS_VXWORKS
1902 /* Always update the timestamp on the old file */
1903 utimes(zLockFile, NULL);
1904#endif
drh7708e972008-11-29 00:56:52 +00001905 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001906 }
1907
1908 /* grab an exclusive lock */
1909 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1910 if( fd<0 ){
1911 /* failed to open/create the file, someone else may have stolen the lock */
1912 int tErrno = errno;
1913 if( EEXIST == tErrno ){
1914 rc = SQLITE_BUSY;
1915 } else {
1916 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1917 if( IS_LOCK_ERROR(rc) ){
1918 pFile->lastErrno = tErrno;
1919 }
1920 }
drh7708e972008-11-29 00:56:52 +00001921 return rc;
drh734c9862008-11-28 15:37:20 +00001922 }
1923 if( close(fd) ){
1924 pFile->lastErrno = errno;
1925 rc = SQLITE_IOERR_CLOSE;
1926 }
1927
1928 /* got it, set the type and return ok */
1929 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001930 return rc;
1931}
1932
drh7708e972008-11-29 00:56:52 +00001933/*
1934** Lower the locking level on file descriptor pFile to locktype. locktype
1935** must be either NO_LOCK or SHARED_LOCK.
1936**
1937** If the locking level of the file descriptor is already at or below
1938** the requested locking level, this routine is a no-op.
1939**
1940** When the locking level reaches NO_LOCK, delete the lock file.
1941*/
drh734c9862008-11-28 15:37:20 +00001942static int dotlockUnlock(sqlite3_file *id, int locktype) {
1943 unixFile *pFile = (unixFile*)id;
1944 char *zLockFile = (char *)pFile->lockingContext;
1945
1946 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001947 OSTRACE5("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00001948 pFile->locktype, getpid());
1949 assert( locktype<=SHARED_LOCK );
1950
1951 /* no-op if possible */
1952 if( pFile->locktype==locktype ){
1953 return SQLITE_OK;
1954 }
drh7708e972008-11-29 00:56:52 +00001955
1956 /* To downgrade to shared, simply update our internal notion of the
1957 ** lock state. No need to mess with the file on disk.
1958 */
1959 if( locktype==SHARED_LOCK ){
1960 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001961 return SQLITE_OK;
1962 }
1963
drh7708e972008-11-29 00:56:52 +00001964 /* To fully unlock the database, delete the lock file */
1965 assert( locktype==NO_LOCK );
1966 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001967 int rc = 0;
1968 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001969 if( ENOENT != tErrno ){
1970 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1971 }
1972 if( IS_LOCK_ERROR(rc) ){
1973 pFile->lastErrno = tErrno;
1974 }
1975 return rc;
1976 }
1977 pFile->locktype = NO_LOCK;
1978 return SQLITE_OK;
1979}
1980
1981/*
drh9b35ea62008-11-29 02:20:26 +00001982** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001983*/
1984static int dotlockClose(sqlite3_file *id) {
1985 int rc;
1986 if( id ){
1987 unixFile *pFile = (unixFile*)id;
1988 dotlockUnlock(id, NO_LOCK);
1989 sqlite3_free(pFile->lockingContext);
1990 }
drh734c9862008-11-28 15:37:20 +00001991 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001992 return rc;
1993}
1994/****************** End of the dot-file lock implementation *******************
1995******************************************************************************/
1996
1997/******************************************************************************
1998************************** Begin flock Locking ********************************
1999**
2000** Use the flock() system call to do file locking.
2001**
drh6b9d6dd2008-12-03 19:34:47 +00002002** flock() locking is like dot-file locking in that the various
2003** fine-grain locking levels supported by SQLite are collapsed into
2004** a single exclusive lock. In other words, SHARED, RESERVED, and
2005** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2006** still works when you do this, but concurrency is reduced since
2007** only a single process can be reading the database at a time.
2008**
drh734c9862008-11-28 15:37:20 +00002009** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2010** compiling for VXWORKS.
2011*/
2012#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002013
drh6b9d6dd2008-12-03 19:34:47 +00002014/*
2015** This routine checks if there is a RESERVED lock held on the specified
2016** file by this or any other process. If such a lock is held, set *pResOut
2017** to a non-zero value otherwise *pResOut is set to zero. The return value
2018** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2019*/
drh734c9862008-11-28 15:37:20 +00002020static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2021 int rc = SQLITE_OK;
2022 int reserved = 0;
2023 unixFile *pFile = (unixFile*)id;
2024
2025 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2026
2027 assert( pFile );
2028
2029 /* Check if a thread in this process holds such a lock */
2030 if( pFile->locktype>SHARED_LOCK ){
2031 reserved = 1;
2032 }
2033
2034 /* Otherwise see if some other process holds it. */
2035 if( !reserved ){
2036 /* attempt to get the lock */
2037 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2038 if( !lrc ){
2039 /* got the lock, unlock it */
2040 lrc = flock(pFile->h, LOCK_UN);
2041 if ( lrc ) {
2042 int tErrno = errno;
2043 /* unlock failed with an error */
2044 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2045 if( IS_LOCK_ERROR(lrc) ){
2046 pFile->lastErrno = tErrno;
2047 rc = lrc;
2048 }
2049 }
2050 } else {
2051 int tErrno = errno;
2052 reserved = 1;
2053 /* someone else might have it reserved */
2054 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2055 if( IS_LOCK_ERROR(lrc) ){
2056 pFile->lastErrno = tErrno;
2057 rc = lrc;
2058 }
2059 }
2060 }
drh476bda72009-12-04 14:25:18 +00002061 OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002062
2063#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2064 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2065 rc = SQLITE_OK;
2066 reserved=1;
2067 }
2068#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2069 *pResOut = reserved;
2070 return rc;
2071}
2072
drh6b9d6dd2008-12-03 19:34:47 +00002073/*
2074** Lock the file with the lock specified by parameter locktype - one
2075** of the following:
2076**
2077** (1) SHARED_LOCK
2078** (2) RESERVED_LOCK
2079** (3) PENDING_LOCK
2080** (4) EXCLUSIVE_LOCK
2081**
2082** Sometimes when requesting one lock state, additional lock states
2083** are inserted in between. The locking might fail on one of the later
2084** transitions leaving the lock state different from what it started but
2085** still short of its goal. The following chart shows the allowed
2086** transitions and the inserted intermediate states:
2087**
2088** UNLOCKED -> SHARED
2089** SHARED -> RESERVED
2090** SHARED -> (PENDING) -> EXCLUSIVE
2091** RESERVED -> (PENDING) -> EXCLUSIVE
2092** PENDING -> EXCLUSIVE
2093**
2094** flock() only really support EXCLUSIVE locks. We track intermediate
2095** lock states in the sqlite3_file structure, but all locks SHARED or
2096** above are really EXCLUSIVE locks and exclude all other processes from
2097** access the file.
2098**
2099** This routine will only increase a lock. Use the sqlite3OsUnlock()
2100** routine to lower a locking level.
2101*/
drh734c9862008-11-28 15:37:20 +00002102static int flockLock(sqlite3_file *id, int locktype) {
2103 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002104 unixFile *pFile = (unixFile*)id;
2105
2106 assert( pFile );
2107
2108 /* if we already have a lock, it is exclusive.
2109 ** Just adjust level and punt on outta here. */
2110 if (pFile->locktype > NO_LOCK) {
2111 pFile->locktype = locktype;
2112 return SQLITE_OK;
2113 }
2114
2115 /* grab an exclusive lock */
2116
2117 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2118 int tErrno = errno;
2119 /* didn't get, must be busy */
2120 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2121 if( IS_LOCK_ERROR(rc) ){
2122 pFile->lastErrno = tErrno;
2123 }
2124 } else {
2125 /* got it, set the type and return ok */
2126 pFile->locktype = locktype;
2127 }
drh476bda72009-12-04 14:25:18 +00002128 OSTRACE4("LOCK %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
drh734c9862008-11-28 15:37:20 +00002129 rc==SQLITE_OK ? "ok" : "failed");
2130#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2131 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2132 rc = SQLITE_BUSY;
2133 }
2134#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2135 return rc;
2136}
2137
drh6b9d6dd2008-12-03 19:34:47 +00002138
2139/*
2140** Lower the locking level on file descriptor pFile to locktype. locktype
2141** must be either NO_LOCK or SHARED_LOCK.
2142**
2143** If the locking level of the file descriptor is already at or below
2144** the requested locking level, this routine is a no-op.
2145*/
drh734c9862008-11-28 15:37:20 +00002146static int flockUnlock(sqlite3_file *id, int locktype) {
2147 unixFile *pFile = (unixFile*)id;
2148
2149 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002150 OSTRACE5("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002151 pFile->locktype, getpid());
2152 assert( locktype<=SHARED_LOCK );
2153
2154 /* no-op if possible */
2155 if( pFile->locktype==locktype ){
2156 return SQLITE_OK;
2157 }
2158
2159 /* shared can just be set because we always have an exclusive */
2160 if (locktype==SHARED_LOCK) {
2161 pFile->locktype = locktype;
2162 return SQLITE_OK;
2163 }
2164
2165 /* no, really, unlock. */
2166 int rc = flock(pFile->h, LOCK_UN);
2167 if (rc) {
2168 int r, tErrno = errno;
2169 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2170 if( IS_LOCK_ERROR(r) ){
2171 pFile->lastErrno = tErrno;
2172 }
2173#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2174 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2175 r = SQLITE_BUSY;
2176 }
2177#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2178
2179 return r;
2180 } else {
2181 pFile->locktype = NO_LOCK;
2182 return SQLITE_OK;
2183 }
2184}
2185
2186/*
2187** Close a file.
2188*/
2189static int flockClose(sqlite3_file *id) {
2190 if( id ){
2191 flockUnlock(id, NO_LOCK);
2192 }
2193 return closeUnixFile(id);
2194}
2195
2196#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2197
2198/******************* End of the flock lock implementation *********************
2199******************************************************************************/
2200
2201/******************************************************************************
2202************************ Begin Named Semaphore Locking ************************
2203**
2204** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002205**
2206** Semaphore locking is like dot-lock and flock in that it really only
2207** supports EXCLUSIVE locking. Only a single process can read or write
2208** the database file at a time. This reduces potential concurrency, but
2209** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002210*/
2211#if OS_VXWORKS
2212
drh6b9d6dd2008-12-03 19:34:47 +00002213/*
2214** This routine checks if there is a RESERVED lock held on the specified
2215** file by this or any other process. If such a lock is held, set *pResOut
2216** to a non-zero value otherwise *pResOut is set to zero. The return value
2217** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2218*/
drh734c9862008-11-28 15:37:20 +00002219static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2220 int rc = SQLITE_OK;
2221 int reserved = 0;
2222 unixFile *pFile = (unixFile*)id;
2223
2224 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2225
2226 assert( pFile );
2227
2228 /* Check if a thread in this process holds such a lock */
2229 if( pFile->locktype>SHARED_LOCK ){
2230 reserved = 1;
2231 }
2232
2233 /* Otherwise see if some other process holds it. */
2234 if( !reserved ){
2235 sem_t *pSem = pFile->pOpen->pSem;
2236 struct stat statBuf;
2237
2238 if( sem_trywait(pSem)==-1 ){
2239 int tErrno = errno;
2240 if( EAGAIN != tErrno ){
2241 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2242 pFile->lastErrno = tErrno;
2243 } else {
2244 /* someone else has the lock when we are in NO_LOCK */
2245 reserved = (pFile->locktype < SHARED_LOCK);
2246 }
2247 }else{
2248 /* we could have it if we want it */
2249 sem_post(pSem);
2250 }
2251 }
drh476bda72009-12-04 14:25:18 +00002252 OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002253
2254 *pResOut = reserved;
2255 return rc;
2256}
2257
drh6b9d6dd2008-12-03 19:34:47 +00002258/*
2259** Lock the file with the lock specified by parameter locktype - one
2260** of the following:
2261**
2262** (1) SHARED_LOCK
2263** (2) RESERVED_LOCK
2264** (3) PENDING_LOCK
2265** (4) EXCLUSIVE_LOCK
2266**
2267** Sometimes when requesting one lock state, additional lock states
2268** are inserted in between. The locking might fail on one of the later
2269** transitions leaving the lock state different from what it started but
2270** still short of its goal. The following chart shows the allowed
2271** transitions and the inserted intermediate states:
2272**
2273** UNLOCKED -> SHARED
2274** SHARED -> RESERVED
2275** SHARED -> (PENDING) -> EXCLUSIVE
2276** RESERVED -> (PENDING) -> EXCLUSIVE
2277** PENDING -> EXCLUSIVE
2278**
2279** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2280** lock states in the sqlite3_file structure, but all locks SHARED or
2281** above are really EXCLUSIVE locks and exclude all other processes from
2282** access the file.
2283**
2284** This routine will only increase a lock. Use the sqlite3OsUnlock()
2285** routine to lower a locking level.
2286*/
drh734c9862008-11-28 15:37:20 +00002287static int semLock(sqlite3_file *id, int locktype) {
2288 unixFile *pFile = (unixFile*)id;
2289 int fd;
2290 sem_t *pSem = pFile->pOpen->pSem;
2291 int rc = SQLITE_OK;
2292
2293 /* if we already have a lock, it is exclusive.
2294 ** Just adjust level and punt on outta here. */
2295 if (pFile->locktype > NO_LOCK) {
2296 pFile->locktype = locktype;
2297 rc = SQLITE_OK;
2298 goto sem_end_lock;
2299 }
2300
2301 /* lock semaphore now but bail out when already locked. */
2302 if( sem_trywait(pSem)==-1 ){
2303 rc = SQLITE_BUSY;
2304 goto sem_end_lock;
2305 }
2306
2307 /* got it, set the type and return ok */
2308 pFile->locktype = locktype;
2309
2310 sem_end_lock:
2311 return rc;
2312}
2313
drh6b9d6dd2008-12-03 19:34:47 +00002314/*
2315** Lower the locking level on file descriptor pFile to locktype. locktype
2316** must be either NO_LOCK or SHARED_LOCK.
2317**
2318** If the locking level of the file descriptor is already at or below
2319** the requested locking level, this routine is a no-op.
2320*/
drh734c9862008-11-28 15:37:20 +00002321static int semUnlock(sqlite3_file *id, int locktype) {
2322 unixFile *pFile = (unixFile*)id;
2323 sem_t *pSem = pFile->pOpen->pSem;
2324
2325 assert( pFile );
2326 assert( pSem );
drh476bda72009-12-04 14:25:18 +00002327 OSTRACE5("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002328 pFile->locktype, getpid());
2329 assert( locktype<=SHARED_LOCK );
2330
2331 /* no-op if possible */
2332 if( pFile->locktype==locktype ){
2333 return SQLITE_OK;
2334 }
2335
2336 /* shared can just be set because we always have an exclusive */
2337 if (locktype==SHARED_LOCK) {
2338 pFile->locktype = locktype;
2339 return SQLITE_OK;
2340 }
2341
2342 /* no, really unlock. */
2343 if ( sem_post(pSem)==-1 ) {
2344 int rc, tErrno = errno;
2345 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2346 if( IS_LOCK_ERROR(rc) ){
2347 pFile->lastErrno = tErrno;
2348 }
2349 return rc;
2350 }
2351 pFile->locktype = NO_LOCK;
2352 return SQLITE_OK;
2353}
2354
2355/*
2356 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002357 */
drh734c9862008-11-28 15:37:20 +00002358static int semClose(sqlite3_file *id) {
2359 if( id ){
2360 unixFile *pFile = (unixFile*)id;
2361 semUnlock(id, NO_LOCK);
2362 assert( pFile );
2363 unixEnterMutex();
2364 releaseLockInfo(pFile->pLock);
2365 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002366 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002367 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002368 }
2369 return SQLITE_OK;
2370}
2371
2372#endif /* OS_VXWORKS */
2373/*
2374** Named semaphore locking is only available on VxWorks.
2375**
2376*************** End of the named semaphore lock implementation ****************
2377******************************************************************************/
2378
2379
2380/******************************************************************************
2381*************************** Begin AFP Locking *********************************
2382**
2383** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2384** on Apple Macintosh computers - both OS9 and OSX.
2385**
2386** Third-party implementations of AFP are available. But this code here
2387** only works on OSX.
2388*/
2389
drhd2cb50b2009-01-09 21:41:17 +00002390#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002391/*
2392** The afpLockingContext structure contains all afp lock specific state
2393*/
drhbfe66312006-10-03 17:40:40 +00002394typedef struct afpLockingContext afpLockingContext;
2395struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002396 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002397 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002398};
2399
2400struct ByteRangeLockPB2
2401{
2402 unsigned long long offset; /* offset to first byte to lock */
2403 unsigned long long length; /* nbr of bytes to lock */
2404 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2405 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2406 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2407 int fd; /* file desc to assoc this lock with */
2408};
2409
drhfd131da2007-08-07 17:13:03 +00002410#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002411
drh6b9d6dd2008-12-03 19:34:47 +00002412/*
2413** This is a utility for setting or clearing a bit-range lock on an
2414** AFP filesystem.
2415**
2416** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2417*/
2418static int afpSetLock(
2419 const char *path, /* Name of the file to be locked or unlocked */
2420 unixFile *pFile, /* Open file descriptor on path */
2421 unsigned long long offset, /* First byte to be locked */
2422 unsigned long long length, /* Number of bytes to lock */
2423 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002424){
drh6b9d6dd2008-12-03 19:34:47 +00002425 struct ByteRangeLockPB2 pb;
2426 int err;
drhbfe66312006-10-03 17:40:40 +00002427
2428 pb.unLockFlag = setLockFlag ? 0 : 1;
2429 pb.startEndFlag = 0;
2430 pb.offset = offset;
2431 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002432 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002433
2434 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002435 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2436 offset, length);
drhbfe66312006-10-03 17:40:40 +00002437 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2438 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002439 int rc;
2440 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002441 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2442 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002443#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2444 rc = SQLITE_BUSY;
2445#else
drh734c9862008-11-28 15:37:20 +00002446 rc = sqliteErrorFromPosixError(tErrno,
2447 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002448#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002449 if( IS_LOCK_ERROR(rc) ){
2450 pFile->lastErrno = tErrno;
2451 }
2452 return rc;
drhbfe66312006-10-03 17:40:40 +00002453 } else {
aswift5b1a2562008-08-22 00:22:35 +00002454 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002455 }
2456}
2457
drh6b9d6dd2008-12-03 19:34:47 +00002458/*
2459** This routine checks if there is a RESERVED lock held on the specified
2460** file by this or any other process. If such a lock is held, set *pResOut
2461** to a non-zero value otherwise *pResOut is set to zero. The return value
2462** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2463*/
danielk1977e339d652008-06-28 11:23:00 +00002464static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002465 int rc = SQLITE_OK;
2466 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002467 unixFile *pFile = (unixFile*)id;
2468
aswift5b1a2562008-08-22 00:22:35 +00002469 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2470
2471 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002472 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002473 if( context->reserved ){
2474 *pResOut = 1;
2475 return SQLITE_OK;
2476 }
2477 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002478
2479 /* Check if a thread in this process holds such a lock */
drh7ed97b92010-01-20 13:07:21 +00002480 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002481 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002482 }
2483
2484 /* Otherwise see if some other process holds it.
2485 */
aswift5b1a2562008-08-22 00:22:35 +00002486 if( !reserved ){
2487 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002488 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002489 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002490 /* if we succeeded in taking the reserved lock, unlock it to restore
2491 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002492 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002493 } else {
2494 /* if we failed to get the lock then someone else must have it */
2495 reserved = 1;
2496 }
2497 if( IS_LOCK_ERROR(lrc) ){
2498 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002499 }
2500 }
drhbfe66312006-10-03 17:40:40 +00002501
drh7ed97b92010-01-20 13:07:21 +00002502 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002503 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
aswift5b1a2562008-08-22 00:22:35 +00002504
2505 *pResOut = reserved;
2506 return rc;
drhbfe66312006-10-03 17:40:40 +00002507}
2508
drh6b9d6dd2008-12-03 19:34:47 +00002509/*
2510** Lock the file with the lock specified by parameter locktype - one
2511** of the following:
2512**
2513** (1) SHARED_LOCK
2514** (2) RESERVED_LOCK
2515** (3) PENDING_LOCK
2516** (4) EXCLUSIVE_LOCK
2517**
2518** Sometimes when requesting one lock state, additional lock states
2519** are inserted in between. The locking might fail on one of the later
2520** transitions leaving the lock state different from what it started but
2521** still short of its goal. The following chart shows the allowed
2522** transitions and the inserted intermediate states:
2523**
2524** UNLOCKED -> SHARED
2525** SHARED -> RESERVED
2526** SHARED -> (PENDING) -> EXCLUSIVE
2527** RESERVED -> (PENDING) -> EXCLUSIVE
2528** PENDING -> EXCLUSIVE
2529**
2530** This routine will only increase a lock. Use the sqlite3OsUnlock()
2531** routine to lower a locking level.
2532*/
danielk1977e339d652008-06-28 11:23:00 +00002533static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002534 int rc = SQLITE_OK;
2535 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002536 struct unixLockInfo *pLock = pFile->pLock;
drhbfe66312006-10-03 17:40:40 +00002537 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002538
2539 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002540 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2541 locktypeName(locktype), locktypeName(pFile->locktype),
2542 locktypeName(pLock->locktype), pLock->cnt , getpid());
drh339eb0b2008-03-07 15:34:11 +00002543
drhbfe66312006-10-03 17:40:40 +00002544 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002545 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002546 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002547 */
drhbfe66312006-10-03 17:40:40 +00002548 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00002549 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002550 locktypeName(locktype));
2551 return SQLITE_OK;
2552 }
2553
2554 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002555 ** (1) We never move from unlocked to anything higher than shared lock.
2556 ** (2) SQLite never explicitly requests a pendig lock.
2557 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002558 */
drhbfe66312006-10-03 17:40:40 +00002559 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2560 assert( locktype!=PENDING_LOCK );
2561 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2562
2563 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002564 */
drh6c7d5c52008-11-21 20:32:33 +00002565 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002566
2567 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002568 */
drhbfe66312006-10-03 17:40:40 +00002569 rc = transferOwnership(pFile);
2570 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002571 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002572 return rc;
2573 }
drh7ed97b92010-01-20 13:07:21 +00002574 pLock = pFile->pLock;
2575
2576 /* If some thread using this PID has a lock via a different unixFile*
2577 ** handle that precludes the requested lock, return BUSY.
2578 */
2579 if( (pFile->locktype!=pLock->locktype &&
2580 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
2581 ){
2582 rc = SQLITE_BUSY;
2583 goto afp_end_lock;
2584 }
2585
2586 /* If a SHARED lock is requested, and some thread using this PID already
2587 ** has a SHARED or RESERVED lock, then increment reference counts and
2588 ** return SQLITE_OK.
2589 */
2590 if( locktype==SHARED_LOCK &&
2591 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
2592 assert( locktype==SHARED_LOCK );
2593 assert( pFile->locktype==0 );
2594 assert( pLock->cnt>0 );
2595 pFile->locktype = SHARED_LOCK;
2596 pLock->cnt++;
2597 pFile->pOpen->nLock++;
2598 goto afp_end_lock;
2599 }
drhbfe66312006-10-03 17:40:40 +00002600
2601 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002602 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2603 ** be released.
2604 */
drhbfe66312006-10-03 17:40:40 +00002605 if( locktype==SHARED_LOCK
2606 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002607 ){
2608 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002609 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002610 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002611 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002612 goto afp_end_lock;
2613 }
2614 }
2615
2616 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002617 ** operating system calls for the specified lock.
2618 */
drhbfe66312006-10-03 17:40:40 +00002619 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002620 int lrc1, lrc2, lrc1Errno;
2621 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002622
drh7ed97b92010-01-20 13:07:21 +00002623 assert( pLock->cnt==0 );
2624 assert( pLock->locktype==0 );
2625
2626 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002627 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002628 /* note that the quality of the randomness doesn't matter that much */
2629 lk = random();
drh7ed97b92010-01-20 13:07:21 +00002630 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002631 lrc1 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002632 SHARED_FIRST+pLock->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002633 if( IS_LOCK_ERROR(lrc1) ){
2634 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002635 }
aswift5b1a2562008-08-22 00:22:35 +00002636 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002637 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002638
aswift5b1a2562008-08-22 00:22:35 +00002639 if( IS_LOCK_ERROR(lrc1) ) {
2640 pFile->lastErrno = lrc1Errno;
2641 rc = lrc1;
2642 goto afp_end_lock;
2643 } else if( IS_LOCK_ERROR(lrc2) ){
2644 rc = lrc2;
2645 goto afp_end_lock;
2646 } else if( lrc1 != SQLITE_OK ) {
2647 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002648 } else {
2649 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002650 pFile->pOpen->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002651 pLock->cnt = 1;
drhbfe66312006-10-03 17:40:40 +00002652 }
drh7ed97b92010-01-20 13:07:21 +00002653 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
2654 /* We are trying for an exclusive lock but another thread in this
2655 ** same process is still holding a shared lock. */
2656 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002657 }else{
2658 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2659 ** assumed that there is a SHARED or greater lock on the file
2660 ** already.
2661 */
2662 int failed = 0;
2663 assert( 0!=pFile->locktype );
2664 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2665 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002666 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002667 if( !failed ){
2668 context->reserved = 1;
2669 }
drhbfe66312006-10-03 17:40:40 +00002670 }
2671 if (!failed && locktype == EXCLUSIVE_LOCK) {
2672 /* Acquire an EXCLUSIVE lock */
2673
2674 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002675 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002676 */
drh6b9d6dd2008-12-03 19:34:47 +00002677 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh7ed97b92010-01-20 13:07:21 +00002678 pLock->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002679 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002680 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002681 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002682 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002683 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002684 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002685 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2686 ** a critical I/O error
2687 */
2688 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2689 SQLITE_IOERR_LOCK;
2690 goto afp_end_lock;
2691 }
2692 }else{
aswift5b1a2562008-08-22 00:22:35 +00002693 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002694 }
2695 }
aswift5b1a2562008-08-22 00:22:35 +00002696 if( failed ){
2697 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002698 }
2699 }
2700
2701 if( rc==SQLITE_OK ){
2702 pFile->locktype = locktype;
drh7ed97b92010-01-20 13:07:21 +00002703 pLock->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002704 }else if( locktype==EXCLUSIVE_LOCK ){
2705 pFile->locktype = PENDING_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002706 pLock->locktype = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002707 }
2708
2709afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002710 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002711 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002712 rc==SQLITE_OK ? "ok" : "failed");
2713 return rc;
2714}
2715
2716/*
drh339eb0b2008-03-07 15:34:11 +00002717** Lower the locking level on file descriptor pFile to locktype. locktype
2718** must be either NO_LOCK or SHARED_LOCK.
2719**
2720** If the locking level of the file descriptor is already at or below
2721** the requested locking level, this routine is a no-op.
2722*/
danielk1977e339d652008-06-28 11:23:00 +00002723static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002724 int rc = SQLITE_OK;
2725 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002726 struct unixLockInfo *pLock;
2727 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2728 int skipShared = 0;
2729#ifdef SQLITE_TEST
2730 int h = pFile->h;
2731#endif
drhbfe66312006-10-03 17:40:40 +00002732
2733 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002734 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
2735 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002736
drhbfe66312006-10-03 17:40:40 +00002737 assert( locktype<=SHARED_LOCK );
2738 if( pFile->locktype<=locktype ){
2739 return SQLITE_OK;
2740 }
2741 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00002742 return SQLITE_MISUSE_BKPT;
drhbfe66312006-10-03 17:40:40 +00002743 }
drh6c7d5c52008-11-21 20:32:33 +00002744 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00002745 pLock = pFile->pLock;
2746 assert( pLock->cnt!=0 );
drhbfe66312006-10-03 17:40:40 +00002747 if( pFile->locktype>SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002748 assert( pLock->locktype==pFile->locktype );
2749 SimulateIOErrorBenign(1);
2750 SimulateIOError( h=(-1) )
2751 SimulateIOErrorBenign(0);
2752
2753#ifndef NDEBUG
2754 /* When reducing a lock such that other processes can start
2755 ** reading the database file again, make sure that the
2756 ** transaction counter was updated if any part of the database
2757 ** file changed. If the transaction counter is not updated,
2758 ** other connections to the same file might not realize that
2759 ** the file has changed and hence might not know to flush their
2760 ** cache. The use of a stale cache can lead to database corruption.
2761 */
2762 assert( pFile->inNormalWrite==0
2763 || pFile->dbUpdate==0
2764 || pFile->transCntrChng==1 );
2765 pFile->inNormalWrite = 0;
2766#endif
aswiftaebf4132008-11-21 00:10:35 +00002767
2768 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002769 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2770 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002771 /* only re-establish the shared lock if necessary */
drh7ed97b92010-01-20 13:07:21 +00002772 int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2773 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2774 } else {
2775 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002776 }
2777 }
2778 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002779 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002780 }
drh7ed97b92010-01-20 13:07:21 +00002781 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
2782 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2783 if( !rc ){
2784 context->reserved = 0;
2785 }
aswiftaebf4132008-11-21 00:10:35 +00002786 }
drh7ed97b92010-01-20 13:07:21 +00002787 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
2788 pLock->locktype = SHARED_LOCK;
2789 }
aswiftaebf4132008-11-21 00:10:35 +00002790 }
drh7ed97b92010-01-20 13:07:21 +00002791 if( rc==SQLITE_OK && locktype==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002792
drh7ed97b92010-01-20 13:07:21 +00002793 /* Decrement the shared lock counter. Release the lock using an
2794 ** OS call only when all threads in this same process have released
2795 ** the lock.
2796 */
2797 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2798 pLock->cnt--;
2799 if( pLock->cnt==0 ){
2800 SimulateIOErrorBenign(1);
2801 SimulateIOError( h=(-1) )
2802 SimulateIOErrorBenign(0);
2803 if( !skipShared ){
2804 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2805 }
2806 if( !rc ){
2807 pLock->locktype = NO_LOCK;
2808 pFile->locktype = NO_LOCK;
2809 }
2810 }
2811 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002812 struct unixOpenCnt *pOpen = pFile->pOpen;
drh7ed97b92010-01-20 13:07:21 +00002813
aswiftaebf4132008-11-21 00:10:35 +00002814 pOpen->nLock--;
2815 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002816 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002817 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002818 }
2819 }
drhbfe66312006-10-03 17:40:40 +00002820 }
drh7ed97b92010-01-20 13:07:21 +00002821
drh6c7d5c52008-11-21 20:32:33 +00002822 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00002823 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002824 return rc;
2825}
2826
2827/*
drh339eb0b2008-03-07 15:34:11 +00002828** Close a file & cleanup AFP specific locking context
2829*/
danielk1977e339d652008-06-28 11:23:00 +00002830static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002831 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002832 if( id ){
2833 unixFile *pFile = (unixFile*)id;
2834 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002835 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002836 if( pFile->pOpen && pFile->pOpen->nLock ){
2837 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002838 ** yet because that would clear those locks. Instead, add the file
2839 ** descriptor to pOpen->aPending. It will be automatically closed when
2840 ** the last lock is cleared.
2841 */
dan08da86a2009-08-21 17:18:03 +00002842 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002843 }
drh7ed97b92010-01-20 13:07:21 +00002844 releaseLockInfo(pFile->pLock);
aswiftaebf4132008-11-21 00:10:35 +00002845 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002846 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002847 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002848 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002849 }
drh7ed97b92010-01-20 13:07:21 +00002850 return rc;
drhbfe66312006-10-03 17:40:40 +00002851}
2852
drhd2cb50b2009-01-09 21:41:17 +00002853#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002854/*
2855** The code above is the AFP lock implementation. The code is specific
2856** to MacOSX and does not work on other unix platforms. No alternative
2857** is available. If you don't compile for a mac, then the "unix-afp"
2858** VFS is not available.
2859**
2860********************* End of the AFP lock implementation **********************
2861******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002862
drh7ed97b92010-01-20 13:07:21 +00002863/******************************************************************************
2864*************************** Begin NFS Locking ********************************/
2865
2866#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2867/*
2868 ** Lower the locking level on file descriptor pFile to locktype. locktype
2869 ** must be either NO_LOCK or SHARED_LOCK.
2870 **
2871 ** If the locking level of the file descriptor is already at or below
2872 ** the requested locking level, this routine is a no-op.
2873 */
2874static int nfsUnlock(sqlite3_file *id, int locktype){
2875 return _posixUnlock(id, locktype, 1);
2876}
2877
2878#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2879/*
2880** The code above is the NFS lock implementation. The code is specific
2881** to MacOSX and does not work on other unix platforms. No alternative
2882** is available.
2883**
2884********************* End of the NFS lock implementation **********************
2885******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002886
2887/******************************************************************************
2888**************** Non-locking sqlite3_file methods *****************************
2889**
2890** The next division contains implementations for all methods of the
2891** sqlite3_file object other than the locking methods. The locking
2892** methods were defined in divisions above (one locking method per
2893** division). Those methods that are common to all locking modes
2894** are gather together into this division.
2895*/
drhbfe66312006-10-03 17:40:40 +00002896
2897/*
drh734c9862008-11-28 15:37:20 +00002898** Seek to the offset passed as the second argument, then read cnt
2899** bytes into pBuf. Return the number of bytes actually read.
2900**
2901** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2902** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2903** one system to another. Since SQLite does not define USE_PREAD
2904** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2905** See tickets #2741 and #2681.
2906**
2907** To avoid stomping the errno value on a failed read the lastErrno value
2908** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002909*/
drh734c9862008-11-28 15:37:20 +00002910static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2911 int got;
drh7ed97b92010-01-20 13:07:21 +00002912#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002913 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002914#endif
drh734c9862008-11-28 15:37:20 +00002915 TIMER_START;
2916#if defined(USE_PREAD)
2917 got = pread(id->h, pBuf, cnt, offset);
2918 SimulateIOError( got = -1 );
2919#elif defined(USE_PREAD64)
2920 got = pread64(id->h, pBuf, cnt, offset);
2921 SimulateIOError( got = -1 );
2922#else
2923 newOffset = lseek(id->h, offset, SEEK_SET);
2924 SimulateIOError( newOffset-- );
2925 if( newOffset!=offset ){
2926 if( newOffset == -1 ){
2927 ((unixFile*)id)->lastErrno = errno;
2928 }else{
2929 ((unixFile*)id)->lastErrno = 0;
2930 }
2931 return -1;
2932 }
2933 got = read(id->h, pBuf, cnt);
2934#endif
2935 TIMER_END;
2936 if( got<0 ){
2937 ((unixFile*)id)->lastErrno = errno;
2938 }
2939 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2940 return got;
drhbfe66312006-10-03 17:40:40 +00002941}
2942
2943/*
drh734c9862008-11-28 15:37:20 +00002944** Read data from a file into a buffer. Return SQLITE_OK if all
2945** bytes were read successfully and SQLITE_IOERR if anything goes
2946** wrong.
drh339eb0b2008-03-07 15:34:11 +00002947*/
drh734c9862008-11-28 15:37:20 +00002948static int unixRead(
2949 sqlite3_file *id,
2950 void *pBuf,
2951 int amt,
2952 sqlite3_int64 offset
2953){
dan08da86a2009-08-21 17:18:03 +00002954 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002955 int got;
2956 assert( id );
drh08c6d442009-02-09 17:34:07 +00002957
dan08da86a2009-08-21 17:18:03 +00002958 /* If this is a database file (not a journal, master-journal or temp
2959 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002960 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002961 || offset>=PENDING_BYTE+512
2962 || offset+amt<=PENDING_BYTE
2963 );
drh08c6d442009-02-09 17:34:07 +00002964
dan08da86a2009-08-21 17:18:03 +00002965 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002966 if( got==amt ){
2967 return SQLITE_OK;
2968 }else if( got<0 ){
2969 /* lastErrno set by seekAndRead */
2970 return SQLITE_IOERR_READ;
2971 }else{
dan08da86a2009-08-21 17:18:03 +00002972 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002973 /* Unread parts of the buffer must be zero-filled */
2974 memset(&((char*)pBuf)[got], 0, amt-got);
2975 return SQLITE_IOERR_SHORT_READ;
2976 }
2977}
2978
2979/*
2980** Seek to the offset in id->offset then read cnt bytes into pBuf.
2981** Return the number of bytes actually read. Update the offset.
2982**
2983** To avoid stomping the errno value on a failed write the lastErrno value
2984** is set before returning.
2985*/
2986static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2987 int got;
drh7ed97b92010-01-20 13:07:21 +00002988#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002989 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002990#endif
drh734c9862008-11-28 15:37:20 +00002991 TIMER_START;
2992#if defined(USE_PREAD)
2993 got = pwrite(id->h, pBuf, cnt, offset);
2994#elif defined(USE_PREAD64)
2995 got = pwrite64(id->h, pBuf, cnt, offset);
2996#else
2997 newOffset = lseek(id->h, offset, SEEK_SET);
2998 if( newOffset!=offset ){
2999 if( newOffset == -1 ){
3000 ((unixFile*)id)->lastErrno = errno;
3001 }else{
3002 ((unixFile*)id)->lastErrno = 0;
3003 }
3004 return -1;
3005 }
3006 got = write(id->h, pBuf, cnt);
3007#endif
3008 TIMER_END;
3009 if( got<0 ){
3010 ((unixFile*)id)->lastErrno = errno;
3011 }
3012
3013 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3014 return got;
3015}
3016
3017
3018/*
3019** Write data from a buffer into a file. Return SQLITE_OK on success
3020** or some other error code on failure.
3021*/
3022static int unixWrite(
3023 sqlite3_file *id,
3024 const void *pBuf,
3025 int amt,
3026 sqlite3_int64 offset
3027){
dan08da86a2009-08-21 17:18:03 +00003028 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003029 int wrote = 0;
3030 assert( id );
3031 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003032
dan08da86a2009-08-21 17:18:03 +00003033 /* If this is a database file (not a journal, master-journal or temp
3034 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00003035 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003036 || offset>=PENDING_BYTE+512
3037 || offset+amt<=PENDING_BYTE
3038 );
drh08c6d442009-02-09 17:34:07 +00003039
drh8f941bc2009-01-14 23:03:40 +00003040#ifndef NDEBUG
3041 /* If we are doing a normal write to a database file (as opposed to
3042 ** doing a hot-journal rollback or a write to some file other than a
3043 ** normal database file) then record the fact that the database
3044 ** has changed. If the transaction counter is modified, record that
3045 ** fact too.
3046 */
dan08da86a2009-08-21 17:18:03 +00003047 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003048 pFile->dbUpdate = 1; /* The database has been modified */
3049 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003050 int rc;
drh8f941bc2009-01-14 23:03:40 +00003051 char oldCntr[4];
3052 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003053 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003054 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003055 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003056 pFile->transCntrChng = 1; /* The transaction counter has changed */
3057 }
3058 }
3059 }
3060#endif
3061
dan08da86a2009-08-21 17:18:03 +00003062 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003063 amt -= wrote;
3064 offset += wrote;
3065 pBuf = &((char*)pBuf)[wrote];
3066 }
3067 SimulateIOError(( wrote=(-1), amt=1 ));
3068 SimulateDiskfullError(( wrote=0, amt=1 ));
3069 if( amt>0 ){
3070 if( wrote<0 ){
3071 /* lastErrno set by seekAndWrite */
3072 return SQLITE_IOERR_WRITE;
3073 }else{
dan08da86a2009-08-21 17:18:03 +00003074 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003075 return SQLITE_FULL;
3076 }
3077 }
3078 return SQLITE_OK;
3079}
3080
3081#ifdef SQLITE_TEST
3082/*
3083** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003084** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003085*/
3086int sqlite3_sync_count = 0;
3087int sqlite3_fullsync_count = 0;
3088#endif
3089
3090/*
drh89240432009-03-25 01:06:01 +00003091** We do not trust systems to provide a working fdatasync(). Some do.
3092** Others do no. To be safe, we will stick with the (slower) fsync().
3093** If you know that your system does support fdatasync() correctly,
3094** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003095*/
drh89240432009-03-25 01:06:01 +00003096#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003097# define fdatasync fsync
3098#endif
3099
3100/*
3101** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3102** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3103** only available on Mac OS X. But that could change.
3104*/
3105#ifdef F_FULLFSYNC
3106# define HAVE_FULLFSYNC 1
3107#else
3108# define HAVE_FULLFSYNC 0
3109#endif
3110
3111
3112/*
3113** The fsync() system call does not work as advertised on many
3114** unix systems. The following procedure is an attempt to make
3115** it work better.
3116**
3117** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3118** for testing when we want to run through the test suite quickly.
3119** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3120** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3121** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003122**
3123** SQLite sets the dataOnly flag if the size of the file is unchanged.
3124** The idea behind dataOnly is that it should only write the file content
3125** to disk, not the inode. We only set dataOnly if the file size is
3126** unchanged since the file size is part of the inode. However,
3127** Ted Ts'o tells us that fdatasync() will also write the inode if the
3128** file size has changed. The only real difference between fdatasync()
3129** and fsync(), Ted tells us, is that fdatasync() will not flush the
3130** inode if the mtime or owner or other inode attributes have changed.
3131** We only care about the file size, not the other file attributes, so
3132** as far as SQLite is concerned, an fdatasync() is always adequate.
3133** So, we always use fdatasync() if it is available, regardless of
3134** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003135*/
3136static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003137 int rc;
drh734c9862008-11-28 15:37:20 +00003138
3139 /* The following "ifdef/elif/else/" block has the same structure as
3140 ** the one below. It is replicated here solely to avoid cluttering
3141 ** up the real code with the UNUSED_PARAMETER() macros.
3142 */
3143#ifdef SQLITE_NO_SYNC
3144 UNUSED_PARAMETER(fd);
3145 UNUSED_PARAMETER(fullSync);
3146 UNUSED_PARAMETER(dataOnly);
3147#elif HAVE_FULLFSYNC
3148 UNUSED_PARAMETER(dataOnly);
3149#else
3150 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003151 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003152#endif
3153
3154 /* Record the number of times that we do a normal fsync() and
3155 ** FULLSYNC. This is used during testing to verify that this procedure
3156 ** gets called with the correct arguments.
3157 */
3158#ifdef SQLITE_TEST
3159 if( fullSync ) sqlite3_fullsync_count++;
3160 sqlite3_sync_count++;
3161#endif
3162
3163 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3164 ** no-op
3165 */
3166#ifdef SQLITE_NO_SYNC
3167 rc = SQLITE_OK;
3168#elif HAVE_FULLFSYNC
3169 if( fullSync ){
3170 rc = fcntl(fd, F_FULLFSYNC, 0);
3171 }else{
3172 rc = 1;
3173 }
3174 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003175 ** It shouldn't be possible for fullfsync to fail on the local
3176 ** file system (on OSX), so failure indicates that FULLFSYNC
3177 ** isn't supported for this file system. So, attempt an fsync
3178 ** and (for now) ignore the overhead of a superfluous fcntl call.
3179 ** It'd be better to detect fullfsync support once and avoid
3180 ** the fcntl call every time sync is called.
3181 */
drh734c9862008-11-28 15:37:20 +00003182 if( rc ) rc = fsync(fd);
3183
drh7ed97b92010-01-20 13:07:21 +00003184#elif defined(__APPLE__)
3185 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3186 ** so currently we default to the macro that redefines fdatasync to fsync
3187 */
3188 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003189#else
drh0b647ff2009-03-21 14:41:04 +00003190 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003191#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003192 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003193 rc = fsync(fd);
3194 }
drh0b647ff2009-03-21 14:41:04 +00003195#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003196#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3197
3198 if( OS_VXWORKS && rc!= -1 ){
3199 rc = 0;
3200 }
chw97185482008-11-17 08:05:31 +00003201 return rc;
drhbfe66312006-10-03 17:40:40 +00003202}
3203
drh734c9862008-11-28 15:37:20 +00003204/*
3205** Make sure all writes to a particular file are committed to disk.
3206**
3207** If dataOnly==0 then both the file itself and its metadata (file
3208** size, access time, etc) are synced. If dataOnly!=0 then only the
3209** file data is synced.
3210**
3211** Under Unix, also make sure that the directory entry for the file
3212** has been created by fsync-ing the directory that contains the file.
3213** If we do not do this and we encounter a power failure, the directory
3214** entry for the journal might not exist after we reboot. The next
3215** SQLite to access the file will not know that the journal exists (because
3216** the directory entry for the journal was never created) and the transaction
3217** will not roll back - possibly leading to database corruption.
3218*/
3219static int unixSync(sqlite3_file *id, int flags){
3220 int rc;
3221 unixFile *pFile = (unixFile*)id;
3222
3223 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3224 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3225
3226 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3227 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3228 || (flags&0x0F)==SQLITE_SYNC_FULL
3229 );
3230
3231 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3232 ** line is to test that doing so does not cause any problems.
3233 */
3234 SimulateDiskfullError( return SQLITE_FULL );
3235
3236 assert( pFile );
3237 OSTRACE2("SYNC %-3d\n", pFile->h);
3238 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3239 SimulateIOError( rc=1 );
3240 if( rc ){
3241 pFile->lastErrno = errno;
3242 return SQLITE_IOERR_FSYNC;
3243 }
3244 if( pFile->dirfd>=0 ){
3245 int err;
3246 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3247 HAVE_FULLFSYNC, isFullsync);
3248#ifndef SQLITE_DISABLE_DIRSYNC
3249 /* The directory sync is only attempted if full_fsync is
3250 ** turned off or unavailable. If a full_fsync occurred above,
3251 ** then the directory sync is superfluous.
3252 */
3253 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3254 /*
3255 ** We have received multiple reports of fsync() returning
3256 ** errors when applied to directories on certain file systems.
3257 ** A failed directory sync is not a big deal. So it seems
3258 ** better to ignore the error. Ticket #1657
3259 */
3260 /* pFile->lastErrno = errno; */
3261 /* return SQLITE_IOERR; */
3262 }
3263#endif
3264 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3265 if( err==0 ){ /* directory when we are done */
3266 pFile->dirfd = -1;
3267 }else{
3268 pFile->lastErrno = errno;
3269 rc = SQLITE_IOERR_DIR_CLOSE;
3270 }
3271 }
3272 return rc;
3273}
3274
3275/*
3276** Truncate an open file to a specified size
3277*/
3278static int unixTruncate(sqlite3_file *id, i64 nByte){
3279 int rc;
3280 assert( id );
3281 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3282 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3283 if( rc ){
3284 ((unixFile*)id)->lastErrno = errno;
3285 return SQLITE_IOERR_TRUNCATE;
3286 }else{
drh3313b142009-11-06 04:13:18 +00003287#ifndef NDEBUG
3288 /* If we are doing a normal write to a database file (as opposed to
3289 ** doing a hot-journal rollback or a write to some file other than a
3290 ** normal database file) and we truncate the file to zero length,
3291 ** that effectively updates the change counter. This might happen
3292 ** when restoring a database using the backup API from a zero-length
3293 ** source.
3294 */
3295 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3296 ((unixFile*)id)->transCntrChng = 1;
3297 }
3298#endif
3299
drh734c9862008-11-28 15:37:20 +00003300 return SQLITE_OK;
3301 }
3302}
3303
3304/*
3305** Determine the current size of a file in bytes
3306*/
3307static int unixFileSize(sqlite3_file *id, i64 *pSize){
3308 int rc;
3309 struct stat buf;
3310 assert( id );
3311 rc = fstat(((unixFile*)id)->h, &buf);
3312 SimulateIOError( rc=1 );
3313 if( rc!=0 ){
3314 ((unixFile*)id)->lastErrno = errno;
3315 return SQLITE_IOERR_FSTAT;
3316 }
3317 *pSize = buf.st_size;
3318
3319 /* When opening a zero-size database, the findLockInfo() procedure
3320 ** writes a single byte into that file in order to work around a bug
3321 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3322 ** layers, we need to report this file size as zero even though it is
3323 ** really 1. Ticket #3260.
3324 */
3325 if( *pSize==1 ) *pSize = 0;
3326
3327
3328 return SQLITE_OK;
3329}
3330
drhd2cb50b2009-01-09 21:41:17 +00003331#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003332/*
3333** Handler for proxy-locking file-control verbs. Defined below in the
3334** proxying locking division.
3335*/
3336static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003337#endif
drh715ff302008-12-03 22:32:44 +00003338
danielk1977ad94b582007-08-20 06:44:22 +00003339
danielk1977e3026632004-06-22 11:29:02 +00003340/*
drh9e33c2c2007-08-31 18:34:59 +00003341** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003342*/
drhcc6bb3e2007-08-31 16:11:35 +00003343static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003344 switch( op ){
3345 case SQLITE_FCNTL_LOCKSTATE: {
3346 *(int*)pArg = ((unixFile*)id)->locktype;
3347 return SQLITE_OK;
3348 }
drh7708e972008-11-29 00:56:52 +00003349 case SQLITE_LAST_ERRNO: {
3350 *(int*)pArg = ((unixFile*)id)->lastErrno;
3351 return SQLITE_OK;
3352 }
drh8f941bc2009-01-14 23:03:40 +00003353#ifndef NDEBUG
3354 /* The pager calls this method to signal that it has done
3355 ** a rollback and that the database is therefore unchanged and
3356 ** it hence it is OK for the transaction change counter to be
3357 ** unchanged.
3358 */
3359 case SQLITE_FCNTL_DB_UNCHANGED: {
3360 ((unixFile*)id)->dbUpdate = 0;
3361 return SQLITE_OK;
3362 }
3363#endif
drhd2cb50b2009-01-09 21:41:17 +00003364#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003365 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003366 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003367 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003368 }
drhd2cb50b2009-01-09 21:41:17 +00003369#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003370 }
drhcc6bb3e2007-08-31 16:11:35 +00003371 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003372}
3373
3374/*
danielk1977a3d4c882007-03-23 10:08:38 +00003375** Return the sector size in bytes of the underlying block device for
3376** the specified file. This is almost always 512 bytes, but may be
3377** larger for some devices.
3378**
3379** SQLite code assumes this function cannot fail. It also assumes that
3380** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003381** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003382** same for both.
3383*/
danielk1977397d65f2008-11-19 11:35:39 +00003384static int unixSectorSize(sqlite3_file *NotUsed){
3385 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003386 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003387}
3388
danielk197790949c22007-08-17 16:50:38 +00003389/*
danielk1977397d65f2008-11-19 11:35:39 +00003390** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003391*/
danielk1977397d65f2008-11-19 11:35:39 +00003392static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3393 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003394 return 0;
3395}
3396
drh734c9862008-11-28 15:37:20 +00003397/*
3398** Here ends the implementation of all sqlite3_file methods.
3399**
3400********************** End sqlite3_file Methods *******************************
3401******************************************************************************/
3402
3403/*
drh6b9d6dd2008-12-03 19:34:47 +00003404** This division contains definitions of sqlite3_io_methods objects that
3405** implement various file locking strategies. It also contains definitions
3406** of "finder" functions. A finder-function is used to locate the appropriate
3407** sqlite3_io_methods object for a particular database file. The pAppData
3408** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3409** the correct finder-function for that VFS.
3410**
3411** Most finder functions return a pointer to a fixed sqlite3_io_methods
3412** object. The only interesting finder-function is autolockIoFinder, which
3413** looks at the filesystem type and tries to guess the best locking
3414** strategy from that.
3415**
drh1875f7a2008-12-08 18:19:17 +00003416** For finder-funtion F, two objects are created:
3417**
3418** (1) The real finder-function named "FImpt()".
3419**
dane946c392009-08-22 11:39:46 +00003420** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003421**
3422**
3423** A pointer to the F pointer is used as the pAppData value for VFS
3424** objects. We have to do this instead of letting pAppData point
3425** directly at the finder-function since C90 rules prevent a void*
3426** from be cast into a function pointer.
3427**
drh6b9d6dd2008-12-03 19:34:47 +00003428**
drh7708e972008-11-29 00:56:52 +00003429** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003430**
drh7708e972008-11-29 00:56:52 +00003431** * A constant sqlite3_io_methods object call METHOD that has locking
3432** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3433**
3434** * An I/O method finder function called FINDER that returns a pointer
3435** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003436*/
drh7708e972008-11-29 00:56:52 +00003437#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3438static const sqlite3_io_methods METHOD = { \
3439 1, /* iVersion */ \
3440 CLOSE, /* xClose */ \
3441 unixRead, /* xRead */ \
3442 unixWrite, /* xWrite */ \
3443 unixTruncate, /* xTruncate */ \
3444 unixSync, /* xSync */ \
3445 unixFileSize, /* xFileSize */ \
3446 LOCK, /* xLock */ \
3447 UNLOCK, /* xUnlock */ \
3448 CKLOCK, /* xCheckReservedLock */ \
3449 unixFileControl, /* xFileControl */ \
3450 unixSectorSize, /* xSectorSize */ \
3451 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3452}; \
drh0c2694b2009-09-03 16:23:44 +00003453static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3454 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003455 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003456} \
drh0c2694b2009-09-03 16:23:44 +00003457static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003458 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003459
3460/*
3461** Here are all of the sqlite3_io_methods objects for each of the
3462** locking strategies. Functions that return pointers to these methods
3463** are also created.
3464*/
3465IOMETHODS(
3466 posixIoFinder, /* Finder function name */
3467 posixIoMethods, /* sqlite3_io_methods object name */
3468 unixClose, /* xClose method */
3469 unixLock, /* xLock method */
3470 unixUnlock, /* xUnlock method */
3471 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003472)
drh7708e972008-11-29 00:56:52 +00003473IOMETHODS(
3474 nolockIoFinder, /* Finder function name */
3475 nolockIoMethods, /* sqlite3_io_methods object name */
3476 nolockClose, /* xClose method */
3477 nolockLock, /* xLock method */
3478 nolockUnlock, /* xUnlock method */
3479 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003480)
drh7708e972008-11-29 00:56:52 +00003481IOMETHODS(
3482 dotlockIoFinder, /* Finder function name */
3483 dotlockIoMethods, /* sqlite3_io_methods object name */
3484 dotlockClose, /* xClose method */
3485 dotlockLock, /* xLock method */
3486 dotlockUnlock, /* xUnlock method */
3487 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003488)
drh7708e972008-11-29 00:56:52 +00003489
chw78a13182009-04-07 05:35:03 +00003490#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003491IOMETHODS(
3492 flockIoFinder, /* Finder function name */
3493 flockIoMethods, /* sqlite3_io_methods object name */
3494 flockClose, /* xClose method */
3495 flockLock, /* xLock method */
3496 flockUnlock, /* xUnlock method */
3497 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003498)
drh7708e972008-11-29 00:56:52 +00003499#endif
3500
drh6c7d5c52008-11-21 20:32:33 +00003501#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003502IOMETHODS(
3503 semIoFinder, /* Finder function name */
3504 semIoMethods, /* sqlite3_io_methods object name */
3505 semClose, /* xClose method */
3506 semLock, /* xLock method */
3507 semUnlock, /* xUnlock method */
3508 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003509)
aswiftaebf4132008-11-21 00:10:35 +00003510#endif
drh7708e972008-11-29 00:56:52 +00003511
drhd2cb50b2009-01-09 21:41:17 +00003512#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003513IOMETHODS(
3514 afpIoFinder, /* Finder function name */
3515 afpIoMethods, /* sqlite3_io_methods object name */
3516 afpClose, /* xClose method */
3517 afpLock, /* xLock method */
3518 afpUnlock, /* xUnlock method */
3519 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003520)
drh715ff302008-12-03 22:32:44 +00003521#endif
3522
3523/*
3524** The proxy locking method is a "super-method" in the sense that it
3525** opens secondary file descriptors for the conch and lock files and
3526** it uses proxy, dot-file, AFP, and flock() locking methods on those
3527** secondary files. For this reason, the division that implements
3528** proxy locking is located much further down in the file. But we need
3529** to go ahead and define the sqlite3_io_methods and finder function
3530** for proxy locking here. So we forward declare the I/O methods.
3531*/
drhd2cb50b2009-01-09 21:41:17 +00003532#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003533static int proxyClose(sqlite3_file*);
3534static int proxyLock(sqlite3_file*, int);
3535static int proxyUnlock(sqlite3_file*, int);
3536static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003537IOMETHODS(
3538 proxyIoFinder, /* Finder function name */
3539 proxyIoMethods, /* sqlite3_io_methods object name */
3540 proxyClose, /* xClose method */
3541 proxyLock, /* xLock method */
3542 proxyUnlock, /* xUnlock method */
3543 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003544)
aswiftaebf4132008-11-21 00:10:35 +00003545#endif
drh7708e972008-11-29 00:56:52 +00003546
drh7ed97b92010-01-20 13:07:21 +00003547/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3548#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3549IOMETHODS(
3550 nfsIoFinder, /* Finder function name */
3551 nfsIoMethods, /* sqlite3_io_methods object name */
3552 unixClose, /* xClose method */
3553 unixLock, /* xLock method */
3554 nfsUnlock, /* xUnlock method */
3555 unixCheckReservedLock /* xCheckReservedLock method */
3556)
3557#endif
drh7708e972008-11-29 00:56:52 +00003558
drhd2cb50b2009-01-09 21:41:17 +00003559#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003560/*
drh6b9d6dd2008-12-03 19:34:47 +00003561** This "finder" function attempts to determine the best locking strategy
3562** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003563** object that implements that strategy.
3564**
3565** This is for MacOSX only.
3566*/
drh1875f7a2008-12-08 18:19:17 +00003567static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003568 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003569 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003570){
3571 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003572 const char *zFilesystem; /* Filesystem type name */
3573 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003574 } aMap[] = {
3575 { "hfs", &posixIoMethods },
3576 { "ufs", &posixIoMethods },
3577 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003578 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003579 { "webdav", &nolockIoMethods },
3580 { 0, 0 }
3581 };
3582 int i;
3583 struct statfs fsInfo;
3584 struct flock lockInfo;
3585
3586 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003587 /* If filePath==NULL that means we are dealing with a transient file
3588 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003589 return &nolockIoMethods;
3590 }
3591 if( statfs(filePath, &fsInfo) != -1 ){
3592 if( fsInfo.f_flags & MNT_RDONLY ){
3593 return &nolockIoMethods;
3594 }
3595 for(i=0; aMap[i].zFilesystem; i++){
3596 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3597 return aMap[i].pMethods;
3598 }
3599 }
3600 }
3601
3602 /* Default case. Handles, amongst others, "nfs".
3603 ** Test byte-range lock using fcntl(). If the call succeeds,
3604 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003605 */
drh7708e972008-11-29 00:56:52 +00003606 lockInfo.l_len = 1;
3607 lockInfo.l_start = 0;
3608 lockInfo.l_whence = SEEK_SET;
3609 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003610 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003611 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3612 return &nfsIoMethods;
3613 } else {
3614 return &posixIoMethods;
3615 }
drh7708e972008-11-29 00:56:52 +00003616 }else{
3617 return &dotlockIoMethods;
3618 }
3619}
drh0c2694b2009-09-03 16:23:44 +00003620static const sqlite3_io_methods
3621 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003622
drhd2cb50b2009-01-09 21:41:17 +00003623#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003624
chw78a13182009-04-07 05:35:03 +00003625#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3626/*
3627** This "finder" function attempts to determine the best locking strategy
3628** for the database file "filePath". It then returns the sqlite3_io_methods
3629** object that implements that strategy.
3630**
3631** This is for VXWorks only.
3632*/
3633static const sqlite3_io_methods *autolockIoFinderImpl(
3634 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003635 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003636){
3637 struct flock lockInfo;
3638
3639 if( !filePath ){
3640 /* If filePath==NULL that means we are dealing with a transient file
3641 ** that does not need to be locked. */
3642 return &nolockIoMethods;
3643 }
3644
3645 /* Test if fcntl() is supported and use POSIX style locks.
3646 ** Otherwise fall back to the named semaphore method.
3647 */
3648 lockInfo.l_len = 1;
3649 lockInfo.l_start = 0;
3650 lockInfo.l_whence = SEEK_SET;
3651 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003652 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003653 return &posixIoMethods;
3654 }else{
3655 return &semIoMethods;
3656 }
3657}
drh0c2694b2009-09-03 16:23:44 +00003658static const sqlite3_io_methods
3659 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003660
3661#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3662
drh7708e972008-11-29 00:56:52 +00003663/*
3664** An abstract type for a pointer to a IO method finder function:
3665*/
drh0c2694b2009-09-03 16:23:44 +00003666typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003667
aswiftaebf4132008-11-21 00:10:35 +00003668
drh734c9862008-11-28 15:37:20 +00003669/****************************************************************************
3670**************************** sqlite3_vfs methods ****************************
3671**
3672** This division contains the implementation of methods on the
3673** sqlite3_vfs object.
3674*/
3675
danielk1977a3d4c882007-03-23 10:08:38 +00003676/*
danielk1977e339d652008-06-28 11:23:00 +00003677** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003678*/
3679static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003680 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003681 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003682 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003683 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003684 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003685 int noLock, /* Omit locking if true */
3686 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003687){
drh7708e972008-11-29 00:56:52 +00003688 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003689 unixFile *pNew = (unixFile *)pId;
3690 int rc = SQLITE_OK;
3691
danielk197717b90b52008-06-06 11:11:25 +00003692 assert( pNew->pLock==NULL );
3693 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003694
dane946c392009-08-22 11:39:46 +00003695 /* Parameter isDelete is only used on vxworks. Express this explicitly
3696 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003697 */
drh7708e972008-11-29 00:56:52 +00003698 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003699
drh218c5082008-03-07 00:27:10 +00003700 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003701 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003702 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003703 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00003704 pNew->fileFlags = 0;
drh339eb0b2008-03-07 15:34:11 +00003705
drh6c7d5c52008-11-21 20:32:33 +00003706#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003707 pNew->pId = vxworksFindFileId(zFilename);
3708 if( pNew->pId==0 ){
3709 noLock = 1;
3710 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003711 }
3712#endif
3713
drhda0e7682008-07-30 15:27:54 +00003714 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003715 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003716 }else{
drh0c2694b2009-09-03 16:23:44 +00003717 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003718#if SQLITE_ENABLE_LOCKING_STYLE
3719 /* Cache zFilename in the locking context (AFP and dotlock override) for
3720 ** proxyLock activation is possible (remote proxy is based on db name)
3721 ** zFilename remains valid until file is closed, to support */
3722 pNew->lockingContext = (void*)zFilename;
3723#endif
drhda0e7682008-07-30 15:27:54 +00003724 }
danielk1977e339d652008-06-28 11:23:00 +00003725
drh7ed97b92010-01-20 13:07:21 +00003726 if( pLockingStyle == &posixIoMethods
3727#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3728 || pLockingStyle == &nfsIoMethods
3729#endif
3730 ){
drh7708e972008-11-29 00:56:52 +00003731 unixEnterMutex();
3732 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003733 if( rc!=SQLITE_OK ){
3734 /* If an error occured in findLockInfo(), close the file descriptor
3735 ** immediately, before releasing the mutex. findLockInfo() may fail
3736 ** in two scenarios:
3737 **
3738 ** (a) A call to fstat() failed.
3739 ** (b) A malloc failed.
3740 **
3741 ** Scenario (b) may only occur if the process is holding no other
3742 ** file descriptors open on the same file. If there were other file
3743 ** descriptors on this file, then no malloc would be required by
3744 ** findLockInfo(). If this is the case, it is quite safe to close
3745 ** handle h - as it is guaranteed that no posix locks will be released
3746 ** by doing so.
3747 **
3748 ** If scenario (a) caused the error then things are not so safe. The
3749 ** implicit assumption here is that if fstat() fails, things are in
3750 ** such bad shape that dropping a lock or two doesn't matter much.
3751 */
3752 close(h);
3753 h = -1;
3754 }
drh7708e972008-11-29 00:56:52 +00003755 unixLeaveMutex();
3756 }
danielk1977e339d652008-06-28 11:23:00 +00003757
drhd2cb50b2009-01-09 21:41:17 +00003758#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003759 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003760 /* AFP locking uses the file path so it needs to be included in
3761 ** the afpLockingContext.
3762 */
3763 afpLockingContext *pCtx;
3764 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3765 if( pCtx==0 ){
3766 rc = SQLITE_NOMEM;
3767 }else{
3768 /* NB: zFilename exists and remains valid until the file is closed
3769 ** according to requirement F11141. So we do not need to make a
3770 ** copy of the filename. */
3771 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00003772 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00003773 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003774 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00003775 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3776 if( rc!=SQLITE_OK ){
3777 sqlite3_free(pNew->lockingContext);
3778 close(h);
3779 h = -1;
3780 }
drh7708e972008-11-29 00:56:52 +00003781 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003782 }
drh7708e972008-11-29 00:56:52 +00003783 }
3784#endif
danielk1977e339d652008-06-28 11:23:00 +00003785
drh7708e972008-11-29 00:56:52 +00003786 else if( pLockingStyle == &dotlockIoMethods ){
3787 /* Dotfile locking uses the file path so it needs to be included in
3788 ** the dotlockLockingContext
3789 */
3790 char *zLockFile;
3791 int nFilename;
drhea678832008-12-10 19:26:22 +00003792 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003793 zLockFile = (char *)sqlite3_malloc(nFilename);
3794 if( zLockFile==0 ){
3795 rc = SQLITE_NOMEM;
3796 }else{
3797 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003798 }
drh7708e972008-11-29 00:56:52 +00003799 pNew->lockingContext = zLockFile;
3800 }
danielk1977e339d652008-06-28 11:23:00 +00003801
drh6c7d5c52008-11-21 20:32:33 +00003802#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003803 else if( pLockingStyle == &semIoMethods ){
3804 /* Named semaphore locking uses the file path so it needs to be
3805 ** included in the semLockingContext
3806 */
3807 unixEnterMutex();
3808 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3809 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3810 char *zSemName = pNew->pOpen->aSemName;
3811 int n;
drh2238dcc2009-08-27 17:56:20 +00003812 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003813 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003814 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003815 if( zSemName[n]=='/' ) zSemName[n] = '_';
3816 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3817 if( pNew->pOpen->pSem == SEM_FAILED ){
3818 rc = SQLITE_NOMEM;
3819 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003820 }
chw97185482008-11-17 08:05:31 +00003821 }
drh7708e972008-11-29 00:56:52 +00003822 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003823 }
drh7708e972008-11-29 00:56:52 +00003824#endif
aswift5b1a2562008-08-22 00:22:35 +00003825
3826 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003827#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003828 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00003829 if( h>=0 ) close(h);
3830 h = -1;
chw97185482008-11-17 08:05:31 +00003831 unlink(zFilename);
3832 isDelete = 0;
3833 }
3834 pNew->isDelete = isDelete;
3835#endif
danielk1977e339d652008-06-28 11:23:00 +00003836 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003837 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003838 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003839 }else{
drh7708e972008-11-29 00:56:52 +00003840 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003841 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003842 }
danielk1977e339d652008-06-28 11:23:00 +00003843 return rc;
drh054889e2005-11-30 03:20:31 +00003844}
drh9c06c952005-11-26 00:25:00 +00003845
danielk1977ad94b582007-08-20 06:44:22 +00003846/*
3847** Open a file descriptor to the directory containing file zFilename.
3848** If successful, *pFd is set to the opened file descriptor and
3849** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3850** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3851** value.
3852**
3853** If SQLITE_OK is returned, the caller is responsible for closing
3854** the file descriptor *pFd using close().
3855*/
danielk1977fee2d252007-08-18 10:59:19 +00003856static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003857 int ii;
drh777b17a2007-09-20 10:02:54 +00003858 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003859 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003860
drh153c62c2007-08-24 03:51:33 +00003861 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003862 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003863 if( ii>0 ){
3864 zDirname[ii] = '\0';
3865 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003866 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003867#ifdef FD_CLOEXEC
3868 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3869#endif
3870 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3871 }
3872 }
danielk1977fee2d252007-08-18 10:59:19 +00003873 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00003874 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00003875}
3876
danielk1977b4b47412007-08-17 15:53:36 +00003877/*
danielk197717b90b52008-06-06 11:11:25 +00003878** Create a temporary file name in zBuf. zBuf must be allocated
3879** by the calling process and must be big enough to hold at least
3880** pVfs->mxPathname bytes.
3881*/
3882static int getTempname(int nBuf, char *zBuf){
3883 static const char *azDirs[] = {
3884 0,
aswiftaebf4132008-11-21 00:10:35 +00003885 0,
danielk197717b90b52008-06-06 11:11:25 +00003886 "/var/tmp",
3887 "/usr/tmp",
3888 "/tmp",
3889 ".",
3890 };
3891 static const unsigned char zChars[] =
3892 "abcdefghijklmnopqrstuvwxyz"
3893 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3894 "0123456789";
drh41022642008-11-21 00:24:42 +00003895 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003896 struct stat buf;
3897 const char *zDir = ".";
3898
3899 /* It's odd to simulate an io-error here, but really this is just
3900 ** using the io-error infrastructure to test that SQLite handles this
3901 ** function failing.
3902 */
3903 SimulateIOError( return SQLITE_IOERR );
3904
3905 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003906 if (NULL == azDirs[1]) {
3907 azDirs[1] = getenv("TMPDIR");
3908 }
3909
3910 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003911 if( azDirs[i]==0 ) continue;
3912 if( stat(azDirs[i], &buf) ) continue;
3913 if( !S_ISDIR(buf.st_mode) ) continue;
3914 if( access(azDirs[i], 07) ) continue;
3915 zDir = azDirs[i];
3916 break;
3917 }
3918
3919 /* Check that the output buffer is large enough for the temporary file
3920 ** name. If it is not, return SQLITE_ERROR.
3921 */
danielk197700e13612008-11-17 19:18:54 +00003922 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003923 return SQLITE_ERROR;
3924 }
3925
3926 do{
3927 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003928 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003929 sqlite3_randomness(15, &zBuf[j]);
3930 for(i=0; i<15; i++, j++){
3931 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3932 }
3933 zBuf[j] = 0;
3934 }while( access(zBuf,0)==0 );
3935 return SQLITE_OK;
3936}
3937
drhd2cb50b2009-01-09 21:41:17 +00003938#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003939/*
3940** Routine to transform a unixFile into a proxy-locking unixFile.
3941** Implementation in the proxy-lock division, but used by unixOpen()
3942** if SQLITE_PREFER_PROXY_LOCKING is defined.
3943*/
3944static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003945#endif
drhc66d5b62008-12-03 22:48:32 +00003946
dan08da86a2009-08-21 17:18:03 +00003947/*
3948** Search for an unused file descriptor that was opened on the database
3949** file (not a journal or master-journal file) identified by pathname
3950** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3951** argument to this function.
3952**
3953** Such a file descriptor may exist if a database connection was closed
3954** but the associated file descriptor could not be closed because some
3955** other file descriptor open on the same file is holding a file-lock.
3956** Refer to comments in the unixClose() function and the lengthy comment
3957** describing "Posix Advisory Locking" at the start of this file for
3958** further details. Also, ticket #4018.
3959**
3960** If a suitable file descriptor is found, then it is returned. If no
3961** such file descriptor is located, -1 is returned.
3962*/
dane946c392009-08-22 11:39:46 +00003963static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3964 UnixUnusedFd *pUnused = 0;
3965
3966 /* Do not search for an unused file descriptor on vxworks. Not because
3967 ** vxworks would not benefit from the change (it might, we're not sure),
3968 ** but because no way to test it is currently available. It is better
3969 ** not to risk breaking vxworks support for the sake of such an obscure
3970 ** feature. */
3971#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003972 struct stat sStat; /* Results of stat() call */
3973
3974 /* A stat() call may fail for various reasons. If this happens, it is
3975 ** almost certain that an open() call on the same path will also fail.
3976 ** For this reason, if an error occurs in the stat() call here, it is
3977 ** ignored and -1 is returned. The caller will try to open a new file
3978 ** descriptor on the same path, fail, and return an error to SQLite.
3979 **
3980 ** Even if a subsequent open() call does succeed, the consequences of
3981 ** not searching for a resusable file descriptor are not dire. */
3982 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00003983 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00003984
3985 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00003986 pOpen = openList;
3987 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
3988 || pOpen->fileId.ino!=sStat.st_ino) ){
3989 pOpen = pOpen->pNext;
3990 }
3991 if( pOpen ){
dane946c392009-08-22 11:39:46 +00003992 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00003993 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00003994 pUnused = *pp;
3995 if( pUnused ){
3996 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00003997 }
3998 }
3999 unixLeaveMutex();
4000 }
dane946c392009-08-22 11:39:46 +00004001#endif /* if !OS_VXWORKS */
4002 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004003}
danielk197717b90b52008-06-06 11:11:25 +00004004
4005/*
danielk1977ad94b582007-08-20 06:44:22 +00004006** Open the file zPath.
4007**
danielk1977b4b47412007-08-17 15:53:36 +00004008** Previously, the SQLite OS layer used three functions in place of this
4009** one:
4010**
4011** sqlite3OsOpenReadWrite();
4012** sqlite3OsOpenReadOnly();
4013** sqlite3OsOpenExclusive();
4014**
4015** These calls correspond to the following combinations of flags:
4016**
4017** ReadWrite() -> (READWRITE | CREATE)
4018** ReadOnly() -> (READONLY)
4019** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4020**
4021** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4022** true, the file was configured to be automatically deleted when the
4023** file handle closed. To achieve the same effect using this new
4024** interface, add the DELETEONCLOSE flag to those specified above for
4025** OpenExclusive().
4026*/
4027static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004028 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4029 const char *zPath, /* Pathname of file to be opened */
4030 sqlite3_file *pFile, /* The file descriptor to be filled in */
4031 int flags, /* Input flags to control the opening */
4032 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004033){
dan08da86a2009-08-21 17:18:03 +00004034 unixFile *p = (unixFile *)pFile;
4035 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004036 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004037 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004038 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004039 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004040 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004041
4042 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4043 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4044 int isCreate = (flags & SQLITE_OPEN_CREATE);
4045 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4046 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004047#if SQLITE_ENABLE_LOCKING_STYLE
4048 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4049#endif
danielk1977b4b47412007-08-17 15:53:36 +00004050
danielk1977fee2d252007-08-18 10:59:19 +00004051 /* If creating a master or main-file journal, this function will open
4052 ** a file-descriptor on the directory too. The first time unixSync()
4053 ** is called the directory file descriptor will be fsync()ed and close()d.
4054 */
4055 int isOpenDirectory = (isCreate &&
4056 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4057 );
4058
danielk197717b90b52008-06-06 11:11:25 +00004059 /* If argument zPath is a NULL pointer, this function is required to open
4060 ** a temporary file. Use this buffer to store the file name in.
4061 */
4062 char zTmpname[MAX_PATHNAME+1];
4063 const char *zName = zPath;
4064
danielk1977fee2d252007-08-18 10:59:19 +00004065 /* Check the following statements are true:
4066 **
4067 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4068 ** (b) if CREATE is set, then READWRITE must also be set, and
4069 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004070 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004071 */
danielk1977b4b47412007-08-17 15:53:36 +00004072 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004073 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004074 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004075 assert(isDelete==0 || isCreate);
4076
drh33f4e022007-09-03 15:19:34 +00004077 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004078 ** deleted. Nor are they ever temporary files. */
4079 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4080 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4081 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004082
danielk1977fee2d252007-08-18 10:59:19 +00004083 /* Assert that the upper layer has set one of the "file-type" flags. */
4084 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4085 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4086 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004087 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004088 );
4089
dan08da86a2009-08-21 17:18:03 +00004090 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004091
dan08da86a2009-08-21 17:18:03 +00004092 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004093 UnixUnusedFd *pUnused;
4094 pUnused = findReusableFd(zName, flags);
4095 if( pUnused ){
4096 fd = pUnused->fd;
4097 }else{
dan6aa657f2009-08-24 18:57:58 +00004098 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004099 if( !pUnused ){
4100 return SQLITE_NOMEM;
4101 }
4102 }
4103 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004104 }else if( !zName ){
4105 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004106 assert(isDelete && !isOpenDirectory);
4107 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4108 if( rc!=SQLITE_OK ){
4109 return rc;
4110 }
4111 zName = zTmpname;
4112 }
4113
dan08da86a2009-08-21 17:18:03 +00004114 /* Determine the value of the flags parameter passed to POSIX function
4115 ** open(). These must be calculated even if open() is not called, as
4116 ** they may be stored as part of the file handle and used by the
4117 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004118 if( isReadonly ) openFlags |= O_RDONLY;
4119 if( isReadWrite ) openFlags |= O_RDWR;
4120 if( isCreate ) openFlags |= O_CREAT;
4121 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4122 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004123
danielk1977b4b47412007-08-17 15:53:36 +00004124 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004125 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4126 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004127 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
4128 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4129 /* Failed to open the file for read/write access. Try read-only. */
4130 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004131 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004132 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004133 openFlags |= O_RDONLY;
4134 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004135 }
4136 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004137 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004138 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004139 }
danielk1977b4b47412007-08-17 15:53:36 +00004140 }
dan08da86a2009-08-21 17:18:03 +00004141 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004142 if( pOutFlags ){
4143 *pOutFlags = flags;
4144 }
4145
dane946c392009-08-22 11:39:46 +00004146 if( p->pUnused ){
4147 p->pUnused->fd = fd;
4148 p->pUnused->flags = flags;
4149 }
4150
danielk1977b4b47412007-08-17 15:53:36 +00004151 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004152#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004153 zPath = zName;
4154#else
danielk197717b90b52008-06-06 11:11:25 +00004155 unlink(zName);
chw97185482008-11-17 08:05:31 +00004156#endif
danielk1977b4b47412007-08-17 15:53:36 +00004157 }
drh41022642008-11-21 00:24:42 +00004158#if SQLITE_ENABLE_LOCKING_STYLE
4159 else{
dan08da86a2009-08-21 17:18:03 +00004160 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004161 }
4162#endif
4163
danielk1977fee2d252007-08-18 10:59:19 +00004164 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004165 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004166 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004167 /* It is safe to close fd at this point, because it is guaranteed not
4168 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004169 ** it would not be safe to close as this would release any locks held
4170 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004171 assert( eType!=SQLITE_OPEN_MAIN_DB );
4172 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004173 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004174 }
4175 }
danielk1977e339d652008-06-28 11:23:00 +00004176
4177#ifdef FD_CLOEXEC
4178 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4179#endif
4180
drhda0e7682008-07-30 15:27:54 +00004181 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004182
drh7ed97b92010-01-20 13:07:21 +00004183
4184#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4185 struct statfs fsInfo;
4186 if( fstatfs(fd, &fsInfo) == -1 ){
4187 ((unixFile*)pFile)->lastErrno = errno;
4188 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4189 close(fd); /* silently leak if fail, in error */
4190 return SQLITE_IOERR_ACCESS;
4191 }
4192 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4193 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4194 }
4195#endif
4196
4197#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004198#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004199 isAutoProxy = 1;
4200#endif
4201 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004202 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4203 int useProxy = 0;
4204
dan08da86a2009-08-21 17:18:03 +00004205 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4206 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004207 if( envforce!=NULL ){
4208 useProxy = atoi(envforce)>0;
4209 }else{
4210 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004211 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004212 /* In theory, the close(fd) call is sub-optimal. If the file opened
4213 ** with fd is a database file, and there are other connections open
4214 ** on that file that are currently holding advisory locks on it,
4215 ** then the call to close() will cancel those locks. In practice,
4216 ** we're assuming that statfs() doesn't fail very often. At least
4217 ** not while other file descriptors opened by the same process on
4218 ** the same file are working. */
4219 p->lastErrno = errno;
4220 if( dirfd>=0 ){
4221 close(dirfd); /* silently leak if fail, in error */
4222 }
aswiftaebf4132008-11-21 00:10:35 +00004223 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004224 rc = SQLITE_IOERR_ACCESS;
4225 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004226 }
4227 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4228 }
4229 if( useProxy ){
4230 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4231 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004232 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004233 if( rc!=SQLITE_OK ){
4234 /* Use unixClose to clean up the resources added in fillInUnixFile
4235 ** and clear all the structure's references. Specifically,
4236 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4237 */
4238 unixClose(pFile);
4239 return rc;
4240 }
aswiftaebf4132008-11-21 00:10:35 +00004241 }
dane946c392009-08-22 11:39:46 +00004242 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004243 }
4244 }
4245#endif
4246
dane946c392009-08-22 11:39:46 +00004247 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4248open_finished:
4249 if( rc!=SQLITE_OK ){
4250 sqlite3_free(p->pUnused);
4251 }
4252 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004253}
4254
dane946c392009-08-22 11:39:46 +00004255
danielk1977b4b47412007-08-17 15:53:36 +00004256/*
danielk1977fee2d252007-08-18 10:59:19 +00004257** Delete the file at zPath. If the dirSync argument is true, fsync()
4258** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004259*/
drh6b9d6dd2008-12-03 19:34:47 +00004260static int unixDelete(
4261 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4262 const char *zPath, /* Name of file to be deleted */
4263 int dirSync /* If true, fsync() directory after deleting file */
4264){
danielk1977fee2d252007-08-18 10:59:19 +00004265 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004266 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004267 SimulateIOError(return SQLITE_IOERR_DELETE);
4268 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004269#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004270 if( dirSync ){
4271 int fd;
4272 rc = openDirectory(zPath, &fd);
4273 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004274#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004275 if( fsync(fd)==-1 )
4276#else
4277 if( fsync(fd) )
4278#endif
4279 {
danielk1977fee2d252007-08-18 10:59:19 +00004280 rc = SQLITE_IOERR_DIR_FSYNC;
4281 }
aswiftaebf4132008-11-21 00:10:35 +00004282 if( close(fd)&&!rc ){
4283 rc = SQLITE_IOERR_DIR_CLOSE;
4284 }
danielk1977fee2d252007-08-18 10:59:19 +00004285 }
4286 }
danielk1977d138dd82008-10-15 16:02:48 +00004287#endif
danielk1977fee2d252007-08-18 10:59:19 +00004288 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004289}
4290
danielk197790949c22007-08-17 16:50:38 +00004291/*
4292** Test the existance of or access permissions of file zPath. The
4293** test performed depends on the value of flags:
4294**
4295** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4296** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4297** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4298**
4299** Otherwise return 0.
4300*/
danielk1977861f7452008-06-05 11:39:11 +00004301static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004302 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4303 const char *zPath, /* Path of the file to examine */
4304 int flags, /* What do we want to learn about the zPath file? */
4305 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004306){
rse25c0d1a2007-09-20 08:38:14 +00004307 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004308 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004309 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004310 switch( flags ){
4311 case SQLITE_ACCESS_EXISTS:
4312 amode = F_OK;
4313 break;
4314 case SQLITE_ACCESS_READWRITE:
4315 amode = W_OK|R_OK;
4316 break;
drh50d3f902007-08-27 21:10:36 +00004317 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004318 amode = R_OK;
4319 break;
4320
4321 default:
4322 assert(!"Invalid flags argument");
4323 }
danielk1977861f7452008-06-05 11:39:11 +00004324 *pResOut = (access(zPath, amode)==0);
4325 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004326}
4327
danielk1977b4b47412007-08-17 15:53:36 +00004328
4329/*
4330** Turn a relative pathname into a full pathname. The relative path
4331** is stored as a nul-terminated string in the buffer pointed to by
4332** zPath.
4333**
4334** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4335** (in this case, MAX_PATHNAME bytes). The full-path is written to
4336** this buffer before returning.
4337*/
danielk1977adfb9b02007-09-17 07:02:56 +00004338static int unixFullPathname(
4339 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4340 const char *zPath, /* Possibly relative input path */
4341 int nOut, /* Size of output buffer in bytes */
4342 char *zOut /* Output buffer */
4343){
danielk1977843e65f2007-09-01 16:16:15 +00004344
4345 /* It's odd to simulate an io-error here, but really this is just
4346 ** using the io-error infrastructure to test that SQLite handles this
4347 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004348 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004349 */
4350 SimulateIOError( return SQLITE_ERROR );
4351
drh153c62c2007-08-24 03:51:33 +00004352 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004353 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004354
drh3c7f2dc2007-12-06 13:26:20 +00004355 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004356 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004357 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004358 }else{
4359 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004360 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004361 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004362 }
drhea678832008-12-10 19:26:22 +00004363 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004364 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004365 }
4366 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004367}
4368
drh0ccebe72005-06-07 22:22:50 +00004369
drh761df872006-12-21 01:29:22 +00004370#ifndef SQLITE_OMIT_LOAD_EXTENSION
4371/*
4372** Interfaces for opening a shared library, finding entry points
4373** within the shared library, and closing the shared library.
4374*/
4375#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004376static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4377 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004378 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4379}
danielk197795c8a542007-09-01 06:51:27 +00004380
4381/*
4382** SQLite calls this function immediately after a call to unixDlSym() or
4383** unixDlOpen() fails (returns a null pointer). If a more detailed error
4384** message is available, it is written to zBufOut. If no error message
4385** is available, zBufOut is left unmodified and SQLite uses a default
4386** error message.
4387*/
danielk1977397d65f2008-11-19 11:35:39 +00004388static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004389 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004390 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004391 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004392 zErr = dlerror();
4393 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004394 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004395 }
drh6c7d5c52008-11-21 20:32:33 +00004396 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004397}
drh1875f7a2008-12-08 18:19:17 +00004398static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4399 /*
4400 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4401 ** cast into a pointer to a function. And yet the library dlsym() routine
4402 ** returns a void* which is really a pointer to a function. So how do we
4403 ** use dlsym() with -pedantic-errors?
4404 **
4405 ** Variable x below is defined to be a pointer to a function taking
4406 ** parameters void* and const char* and returning a pointer to a function.
4407 ** We initialize x by assigning it a pointer to the dlsym() function.
4408 ** (That assignment requires a cast.) Then we call the function that
4409 ** x points to.
4410 **
4411 ** This work-around is unlikely to work correctly on any system where
4412 ** you really cannot cast a function pointer into void*. But then, on the
4413 ** other hand, dlsym() will not work on such a system either, so we have
4414 ** not really lost anything.
4415 */
4416 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004417 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004418 x = (void(*(*)(void*,const char*))(void))dlsym;
4419 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004420}
danielk1977397d65f2008-11-19 11:35:39 +00004421static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4422 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004423 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004424}
danielk1977b4b47412007-08-17 15:53:36 +00004425#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4426 #define unixDlOpen 0
4427 #define unixDlError 0
4428 #define unixDlSym 0
4429 #define unixDlClose 0
4430#endif
4431
4432/*
danielk197790949c22007-08-17 16:50:38 +00004433** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004434*/
danielk1977397d65f2008-11-19 11:35:39 +00004435static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4436 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004437 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004438
drhbbd42a62004-05-22 17:41:58 +00004439 /* We have to initialize zBuf to prevent valgrind from reporting
4440 ** errors. The reports issued by valgrind are incorrect - we would
4441 ** prefer that the randomness be increased by making use of the
4442 ** uninitialized space in zBuf - but valgrind errors tend to worry
4443 ** some users. Rather than argue, it seems easier just to initialize
4444 ** the whole array and silence valgrind, even if that means less randomness
4445 ** in the random seed.
4446 **
4447 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004448 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004449 ** tests repeatable.
4450 */
danielk1977b4b47412007-08-17 15:53:36 +00004451 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004452#if !defined(SQLITE_TEST)
4453 {
drh842b8642005-01-21 17:53:17 +00004454 int pid, fd;
4455 fd = open("/dev/urandom", O_RDONLY);
4456 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004457 time_t t;
4458 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004459 memcpy(zBuf, &t, sizeof(t));
4460 pid = getpid();
4461 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004462 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004463 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004464 }else{
drh72cbd072008-10-14 17:58:38 +00004465 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004466 close(fd);
4467 }
drhbbd42a62004-05-22 17:41:58 +00004468 }
4469#endif
drh72cbd072008-10-14 17:58:38 +00004470 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004471}
4472
danielk1977b4b47412007-08-17 15:53:36 +00004473
drhbbd42a62004-05-22 17:41:58 +00004474/*
4475** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004476** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004477** The return value is the number of microseconds of sleep actually
4478** requested from the underlying operating system, a number which
4479** might be greater than or equal to the argument, but not less
4480** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004481*/
danielk1977397d65f2008-11-19 11:35:39 +00004482static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004483#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004484 struct timespec sp;
4485
4486 sp.tv_sec = microseconds / 1000000;
4487 sp.tv_nsec = (microseconds % 1000000) * 1000;
4488 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004489 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004490 return microseconds;
4491#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004492 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004493 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004494 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004495#else
danielk1977b4b47412007-08-17 15:53:36 +00004496 int seconds = (microseconds+999999)/1000000;
4497 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004498 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004499 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004500#endif
drh88f474a2006-01-02 20:00:12 +00004501}
4502
4503/*
drh6b9d6dd2008-12-03 19:34:47 +00004504** The following variable, if set to a non-zero value, is interpreted as
4505** the number of seconds since 1970 and is used to set the result of
4506** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004507*/
4508#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004509int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004510#endif
4511
4512/*
4513** Find the current time (in Universal Coordinated Time). Write the
4514** current time and date as a Julian Day number into *prNow and
4515** return 0. Return 1 if the time and date cannot be found.
4516*/
danielk1977397d65f2008-11-19 11:35:39 +00004517static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004518#if defined(SQLITE_OMIT_FLOATING_POINT)
4519 time_t t;
4520 time(&t);
4521 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4522#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004523 time_t t;
4524 time(&t);
4525 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004526#elif OS_VXWORKS
4527 struct timespec sNow;
4528 clock_gettime(CLOCK_REALTIME, &sNow);
4529 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004530#else
4531 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004532 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004533 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4534#endif
danielk1977397d65f2008-11-19 11:35:39 +00004535
drhbbd42a62004-05-22 17:41:58 +00004536#ifdef SQLITE_TEST
4537 if( sqlite3_current_time ){
4538 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4539 }
4540#endif
danielk1977397d65f2008-11-19 11:35:39 +00004541 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004542 return 0;
4543}
danielk1977b4b47412007-08-17 15:53:36 +00004544
drh6b9d6dd2008-12-03 19:34:47 +00004545/*
4546** We added the xGetLastError() method with the intention of providing
4547** better low-level error messages when operating-system problems come up
4548** during SQLite operation. But so far, none of that has been implemented
4549** in the core. So this routine is never called. For now, it is merely
4550** a place-holder.
4551*/
danielk1977397d65f2008-11-19 11:35:39 +00004552static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4553 UNUSED_PARAMETER(NotUsed);
4554 UNUSED_PARAMETER(NotUsed2);
4555 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004556 return 0;
4557}
4558
drh153c62c2007-08-24 03:51:33 +00004559/*
drh734c9862008-11-28 15:37:20 +00004560************************ End of sqlite3_vfs methods ***************************
4561******************************************************************************/
4562
drh715ff302008-12-03 22:32:44 +00004563/******************************************************************************
4564************************** Begin Proxy Locking ********************************
4565**
4566** Proxy locking is a "uber-locking-method" in this sense: It uses the
4567** other locking methods on secondary lock files. Proxy locking is a
4568** meta-layer over top of the primitive locking implemented above. For
4569** this reason, the division that implements of proxy locking is deferred
4570** until late in the file (here) after all of the other I/O methods have
4571** been defined - so that the primitive locking methods are available
4572** as services to help with the implementation of proxy locking.
4573**
4574****
4575**
4576** The default locking schemes in SQLite use byte-range locks on the
4577** database file to coordinate safe, concurrent access by multiple readers
4578** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4579** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4580** as POSIX read & write locks over fixed set of locations (via fsctl),
4581** on AFP and SMB only exclusive byte-range locks are available via fsctl
4582** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4583** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4584** address in the shared range is taken for a SHARED lock, the entire
4585** shared range is taken for an EXCLUSIVE lock):
4586**
4587** PENDING_BYTE 0x40000000
4588** RESERVED_BYTE 0x40000001
4589** SHARED_RANGE 0x40000002 -> 0x40000200
4590**
4591** This works well on the local file system, but shows a nearly 100x
4592** slowdown in read performance on AFP because the AFP client disables
4593** the read cache when byte-range locks are present. Enabling the read
4594** cache exposes a cache coherency problem that is present on all OS X
4595** supported network file systems. NFS and AFP both observe the
4596** close-to-open semantics for ensuring cache coherency
4597** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4598** address the requirements for concurrent database access by multiple
4599** readers and writers
4600** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4601**
4602** To address the performance and cache coherency issues, proxy file locking
4603** changes the way database access is controlled by limiting access to a
4604** single host at a time and moving file locks off of the database file
4605** and onto a proxy file on the local file system.
4606**
4607**
4608** Using proxy locks
4609** -----------------
4610**
4611** C APIs
4612**
4613** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4614** <proxy_path> | ":auto:");
4615** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4616**
4617**
4618** SQL pragmas
4619**
4620** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4621** PRAGMA [database.]lock_proxy_file
4622**
4623** Specifying ":auto:" means that if there is a conch file with a matching
4624** host ID in it, the proxy path in the conch file will be used, otherwise
4625** a proxy path based on the user's temp dir
4626** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4627** actual proxy file name is generated from the name and path of the
4628** database file. For example:
4629**
4630** For database path "/Users/me/foo.db"
4631** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4632**
4633** Once a lock proxy is configured for a database connection, it can not
4634** be removed, however it may be switched to a different proxy path via
4635** the above APIs (assuming the conch file is not being held by another
4636** connection or process).
4637**
4638**
4639** How proxy locking works
4640** -----------------------
4641**
4642** Proxy file locking relies primarily on two new supporting files:
4643**
4644** * conch file to limit access to the database file to a single host
4645** at a time
4646**
4647** * proxy file to act as a proxy for the advisory locks normally
4648** taken on the database
4649**
4650** The conch file - to use a proxy file, sqlite must first "hold the conch"
4651** by taking an sqlite-style shared lock on the conch file, reading the
4652** contents and comparing the host's unique host ID (see below) and lock
4653** proxy path against the values stored in the conch. The conch file is
4654** stored in the same directory as the database file and the file name
4655** is patterned after the database file name as ".<databasename>-conch".
4656** If the conch file does not exist, or it's contents do not match the
4657** host ID and/or proxy path, then the lock is escalated to an exclusive
4658** lock and the conch file contents is updated with the host ID and proxy
4659** path and the lock is downgraded to a shared lock again. If the conch
4660** is held by another process (with a shared lock), the exclusive lock
4661** will fail and SQLITE_BUSY is returned.
4662**
4663** The proxy file - a single-byte file used for all advisory file locks
4664** normally taken on the database file. This allows for safe sharing
4665** of the database file for multiple readers and writers on the same
4666** host (the conch ensures that they all use the same local lock file).
4667**
drh715ff302008-12-03 22:32:44 +00004668** Requesting the lock proxy does not immediately take the conch, it is
4669** only taken when the first request to lock database file is made.
4670** This matches the semantics of the traditional locking behavior, where
4671** opening a connection to a database file does not take a lock on it.
4672** The shared lock and an open file descriptor are maintained until
4673** the connection to the database is closed.
4674**
4675** The proxy file and the lock file are never deleted so they only need
4676** to be created the first time they are used.
4677**
4678** Configuration options
4679** ---------------------
4680**
4681** SQLITE_PREFER_PROXY_LOCKING
4682**
4683** Database files accessed on non-local file systems are
4684** automatically configured for proxy locking, lock files are
4685** named automatically using the same logic as
4686** PRAGMA lock_proxy_file=":auto:"
4687**
4688** SQLITE_PROXY_DEBUG
4689**
4690** Enables the logging of error messages during host id file
4691** retrieval and creation
4692**
drh715ff302008-12-03 22:32:44 +00004693** LOCKPROXYDIR
4694**
4695** Overrides the default directory used for lock proxy files that
4696** are named automatically via the ":auto:" setting
4697**
4698** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4699**
4700** Permissions to use when creating a directory for storing the
4701** lock proxy files, only used when LOCKPROXYDIR is not set.
4702**
4703**
4704** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4705** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4706** force proxy locking to be used for every database file opened, and 0
4707** will force automatic proxy locking to be disabled for all database
4708** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4709** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4710*/
4711
4712/*
4713** Proxy locking is only available on MacOSX
4714*/
drhd2cb50b2009-01-09 21:41:17 +00004715#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004716
drh715ff302008-12-03 22:32:44 +00004717/*
4718** The proxyLockingContext has the path and file structures for the remote
4719** and local proxy files in it
4720*/
4721typedef struct proxyLockingContext proxyLockingContext;
4722struct proxyLockingContext {
4723 unixFile *conchFile; /* Open conch file */
4724 char *conchFilePath; /* Name of the conch file */
4725 unixFile *lockProxy; /* Open proxy lock file */
4726 char *lockProxyPath; /* Name of the proxy lock file */
4727 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00004728 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00004729 void *oldLockingContext; /* Original lockingcontext to restore on close */
4730 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4731};
4732
drh7ed97b92010-01-20 13:07:21 +00004733/*
4734** The proxy lock file path for the database at dbPath is written into lPath,
4735** which must point to valid, writable memory large enough for a maxLen length
4736** file path.
drh715ff302008-12-03 22:32:44 +00004737*/
drh715ff302008-12-03 22:32:44 +00004738static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4739 int len;
4740 int dbLen;
4741 int i;
4742
4743#ifdef LOCKPROXYDIR
4744 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4745#else
4746# ifdef _CS_DARWIN_USER_TEMP_DIR
4747 {
drh7ed97b92010-01-20 13:07:21 +00004748 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
4749 OSTRACE4("GETLOCKPATH failed %s errno=%d pid=%d\n",
4750 lPath, errno, getpid());
4751 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00004752 }
drh7ed97b92010-01-20 13:07:21 +00004753 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00004754 }
4755# else
4756 len = strlcpy(lPath, "/tmp/", maxLen);
4757# endif
4758#endif
4759
4760 if( lPath[len-1]!='/' ){
4761 len = strlcat(lPath, "/", maxLen);
4762 }
4763
4764 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004765 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004766 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4767 char c = dbPath[i];
4768 lPath[i+len] = (c=='/')?'_':c;
4769 }
4770 lPath[i+len]='\0';
4771 strlcat(lPath, ":auto:", maxLen);
drh7ed97b92010-01-20 13:07:21 +00004772 OSTRACE3("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid());
drh715ff302008-12-03 22:32:44 +00004773 return SQLITE_OK;
4774}
4775
drh7ed97b92010-01-20 13:07:21 +00004776/*
4777 ** Creates the lock file and any missing directories in lockPath
4778 */
4779static int proxyCreateLockPath(const char *lockPath){
4780 int i, len;
4781 char buf[MAXPATHLEN];
4782 int start = 0;
4783
4784 assert(lockPath!=NULL);
4785 /* try to create all the intermediate directories */
4786 len = (int)strlen(lockPath);
4787 buf[0] = lockPath[0];
4788 for( i=1; i<len; i++ ){
4789 if( lockPath[i] == '/' && (i - start > 0) ){
4790 /* only mkdir if leaf dir != "." or "/" or ".." */
4791 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
4792 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
4793 buf[i]='\0';
4794 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4795 int err=errno;
4796 if( err!=EEXIST ) {
4797 OSTRACE5("CREATELOCKPATH FAILED creating %s, "
4798 "'%s' proxy lock path=%s pid=%d\n",
4799 buf, strerror(err), lockPath, getpid());
4800 return err;
4801 }
4802 }
4803 }
4804 start=i+1;
4805 }
4806 buf[i] = lockPath[i];
4807 }
4808 OSTRACE3("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid());
4809 return 0;
4810}
4811
drh715ff302008-12-03 22:32:44 +00004812/*
4813** Create a new VFS file descriptor (stored in memory obtained from
4814** sqlite3_malloc) and open the file named "path" in the file descriptor.
4815**
4816** The caller is responsible not only for closing the file descriptor
4817** but also for freeing the memory associated with the file descriptor.
4818*/
drh7ed97b92010-01-20 13:07:21 +00004819static int proxyCreateUnixFile(
4820 const char *path, /* path for the new unixFile */
4821 unixFile **ppFile, /* unixFile created and returned by ref */
4822 int islockfile /* if non zero missing dirs will be created */
4823) {
4824 int fd = -1;
4825 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00004826 unixFile *pNew;
4827 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00004828 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00004829 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00004830 int terrno = 0;
4831 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00004832
drh7ed97b92010-01-20 13:07:21 +00004833 /* 1. first try to open/create the file
4834 ** 2. if that fails, and this is a lock file (not-conch), try creating
4835 ** the parent directories and then try again.
4836 ** 3. if that fails, try to open the file read-only
4837 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
4838 */
4839 pUnused = findReusableFd(path, openFlags);
4840 if( pUnused ){
4841 fd = pUnused->fd;
4842 }else{
4843 pUnused = sqlite3_malloc(sizeof(*pUnused));
4844 if( !pUnused ){
4845 return SQLITE_NOMEM;
4846 }
4847 }
4848 if( fd<0 ){
4849 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4850 terrno = errno;
4851 if( fd<0 && errno==ENOENT && islockfile ){
4852 if( proxyCreateLockPath(path) == SQLITE_OK ){
4853 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4854 }
4855 }
4856 }
4857 if( fd<0 ){
4858 openFlags = O_RDONLY;
4859 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4860 terrno = errno;
4861 }
4862 if( fd<0 ){
4863 if( islockfile ){
4864 return SQLITE_BUSY;
4865 }
4866 switch (terrno) {
4867 case EACCES:
4868 return SQLITE_PERM;
4869 case EIO:
4870 return SQLITE_IOERR_LOCK; /* even though it is the conch */
4871 default:
drh9978c972010-02-23 17:36:32 +00004872 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00004873 }
4874 }
4875
4876 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
4877 if( pNew==NULL ){
4878 rc = SQLITE_NOMEM;
4879 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00004880 }
4881 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00004882 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00004883 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00004884 pUnused->fd = fd;
4885 pUnused->flags = openFlags;
4886 pNew->pUnused = pUnused;
4887
4888 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4889 if( rc==SQLITE_OK ){
4890 *ppFile = pNew;
4891 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00004892 }
drh7ed97b92010-01-20 13:07:21 +00004893end_create_proxy:
4894 close(fd); /* silently leak fd if error, we're already in error */
4895 sqlite3_free(pNew);
4896 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00004897 return rc;
4898}
4899
drh7ed97b92010-01-20 13:07:21 +00004900#ifdef SQLITE_TEST
4901/* simulate multiple hosts by creating unique hostid file paths */
4902int sqlite3_hostid_num = 0;
4903#endif
4904
4905#define PROXY_HOSTIDLEN 16 /* conch file host id length */
4906
4907/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
4908** bytes of writable memory.
4909*/
4910static int proxyGetHostID(unsigned char *pHostID, int *pError){
4911 struct timespec timeout = {1, 0}; /* 1 sec timeout */
4912
4913 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
4914 memset(pHostID, 0, PROXY_HOSTIDLEN);
4915 if( gethostuuid(pHostID, &timeout) ){
4916 int err = errno;
4917 if( pError ){
4918 *pError = err;
4919 }
4920 return SQLITE_IOERR;
4921 }
4922#ifdef SQLITE_TEST
4923 /* simulate multiple hosts by creating unique hostid file paths */
4924 if( sqlite3_hostid_num != 0){
4925 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
4926 }
4927#endif
4928
4929 return SQLITE_OK;
4930}
4931
4932/* The conch file contains the header, host id and lock file path
4933 */
4934#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
4935#define PROXY_HEADERLEN 1 /* conch file header length */
4936#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
4937#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
4938
4939/*
4940** Takes an open conch file, copies the contents to a new path and then moves
4941** it back. The newly created file's file descriptor is assigned to the
4942** conch file structure and finally the original conch file descriptor is
4943** closed. Returns zero if successful.
4944*/
4945static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
4946 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4947 unixFile *conchFile = pCtx->conchFile;
4948 char tPath[MAXPATHLEN];
4949 char buf[PROXY_MAXCONCHLEN];
4950 char *cPath = pCtx->conchFilePath;
4951 size_t readLen = 0;
4952 size_t pathLen = 0;
4953 char errmsg[64] = "";
4954 int fd = -1;
4955 int rc = -1;
4956
4957 /* create a new path by replace the trailing '-conch' with '-break' */
4958 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
4959 if( pathLen>MAXPATHLEN || pathLen<6 ||
4960 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
4961 sprintf(errmsg, "path error (len %d)", (int)pathLen);
4962 goto end_breaklock;
4963 }
4964 /* read the conch content */
4965 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
4966 if( readLen<PROXY_PATHINDEX ){
4967 sprintf(errmsg, "read error (len %d)", (int)readLen);
4968 goto end_breaklock;
4969 }
4970 /* write it out to the temporary break file */
4971 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
4972 if( fd<0 ){
4973 sprintf(errmsg, "create failed (%d)", errno);
4974 goto end_breaklock;
4975 }
4976 if( pwrite(fd, buf, readLen, 0) != readLen ){
4977 sprintf(errmsg, "write failed (%d)", errno);
4978 goto end_breaklock;
4979 }
4980 if( rename(tPath, cPath) ){
4981 sprintf(errmsg, "rename failed (%d)", errno);
4982 goto end_breaklock;
4983 }
4984 rc = 0;
4985 fprintf(stderr, "broke stale lock on %s\n", cPath);
4986 close(conchFile->h);
4987 conchFile->h = fd;
4988 conchFile->openFlags = O_RDWR | O_CREAT;
4989
4990end_breaklock:
4991 if( rc ){
4992 if( fd>=0 ){
4993 unlink(tPath);
4994 close(fd);
4995 }
4996 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
4997 }
4998 return rc;
4999}
5000
5001/* Take the requested lock on the conch file and break a stale lock if the
5002** host id matches.
5003*/
5004static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5005 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5006 unixFile *conchFile = pCtx->conchFile;
5007 int rc = SQLITE_OK;
5008 int nTries = 0;
5009 struct timespec conchModTime;
5010
5011 do {
5012 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5013 nTries ++;
5014 if( rc==SQLITE_BUSY ){
5015 /* If the lock failed (busy):
5016 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5017 * 2nd try: fail if the mod time changed or host id is different, wait
5018 * 10 sec and try again
5019 * 3rd try: break the lock unless the mod time has changed.
5020 */
5021 struct stat buf;
5022 if( fstat(conchFile->h, &buf) ){
5023 pFile->lastErrno = errno;
5024 return SQLITE_IOERR_LOCK;
5025 }
5026
5027 if( nTries==1 ){
5028 conchModTime = buf.st_mtimespec;
5029 usleep(500000); /* wait 0.5 sec and try the lock again*/
5030 continue;
5031 }
5032
5033 assert( nTries>1 );
5034 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5035 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5036 return SQLITE_BUSY;
5037 }
5038
5039 if( nTries==2 ){
5040 char tBuf[PROXY_MAXCONCHLEN];
5041 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5042 if( len<0 ){
5043 pFile->lastErrno = errno;
5044 return SQLITE_IOERR_LOCK;
5045 }
5046 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5047 /* don't break the lock if the host id doesn't match */
5048 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5049 return SQLITE_BUSY;
5050 }
5051 }else{
5052 /* don't break the lock on short read or a version mismatch */
5053 return SQLITE_BUSY;
5054 }
5055 usleep(10000000); /* wait 10 sec and try the lock again */
5056 continue;
5057 }
5058
5059 assert( nTries==3 );
5060 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5061 rc = SQLITE_OK;
5062 if( lockType==EXCLUSIVE_LOCK ){
5063 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5064 }
5065 if( !rc ){
5066 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5067 }
5068 }
5069 }
5070 } while( rc==SQLITE_BUSY && nTries<3 );
5071
5072 return rc;
5073}
5074
5075/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005076** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5077** lockPath means that the lockPath in the conch file will be used if the
5078** host IDs match, or a new lock path will be generated automatically
5079** and written to the conch file.
5080*/
5081static int proxyTakeConch(unixFile *pFile){
5082 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5083
drh7ed97b92010-01-20 13:07:21 +00005084 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005085 return SQLITE_OK;
5086 }else{
5087 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005088 uuid_t myHostID;
5089 int pError = 0;
5090 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005091 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005092 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005093 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005094 int createConch = 0;
5095 int hostIdMatch = 0;
5096 int readLen = 0;
5097 int tryOldLockPath = 0;
5098 int forceNewLockPath = 0;
5099
drh715ff302008-12-03 22:32:44 +00005100 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5101 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
5102
drh7ed97b92010-01-20 13:07:21 +00005103 rc = proxyGetHostID(myHostID, &pError);
5104 if( (rc&0xff)==SQLITE_IOERR ){
5105 pFile->lastErrno = pError;
5106 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005107 }
drh7ed97b92010-01-20 13:07:21 +00005108 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005109 if( rc!=SQLITE_OK ){
5110 goto end_takeconch;
5111 }
drh7ed97b92010-01-20 13:07:21 +00005112 /* read the existing conch file */
5113 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5114 if( readLen<0 ){
5115 /* I/O error: lastErrno set by seekAndRead */
5116 pFile->lastErrno = conchFile->lastErrno;
5117 rc = SQLITE_IOERR_READ;
5118 goto end_takeconch;
5119 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5120 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5121 /* a short read or version format mismatch means we need to create a new
5122 ** conch file.
5123 */
5124 createConch = 1;
5125 }
5126 /* if the host id matches and the lock path already exists in the conch
5127 ** we'll try to use the path there, if we can't open that path, we'll
5128 ** retry with a new auto-generated path
5129 */
5130 do { /* in case we need to try again for an :auto: named lock file */
5131
5132 if( !createConch && !forceNewLockPath ){
5133 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5134 PROXY_HOSTIDLEN);
5135 /* if the conch has data compare the contents */
5136 if( !pCtx->lockProxyPath ){
5137 /* for auto-named local lock file, just check the host ID and we'll
5138 ** use the local lock file path that's already in there
5139 */
5140 if( hostIdMatch ){
5141 size_t pathLen = (readLen - PROXY_PATHINDEX);
5142
5143 if( pathLen>=MAXPATHLEN ){
5144 pathLen=MAXPATHLEN-1;
5145 }
5146 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5147 lockPath[pathLen] = 0;
5148 tempLockPath = lockPath;
5149 tryOldLockPath = 1;
5150 /* create a copy of the lock path if the conch is taken */
5151 goto end_takeconch;
5152 }
5153 }else if( hostIdMatch
5154 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5155 readLen-PROXY_PATHINDEX)
5156 ){
5157 /* conch host and lock path match */
5158 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005159 }
drh7ed97b92010-01-20 13:07:21 +00005160 }
5161
5162 /* if the conch isn't writable and doesn't match, we can't take it */
5163 if( (conchFile->openFlags&O_RDWR) == 0 ){
5164 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005165 goto end_takeconch;
5166 }
drh7ed97b92010-01-20 13:07:21 +00005167
5168 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005169 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005170 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5171 tempLockPath = lockPath;
5172 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005173 }
drh7ed97b92010-01-20 13:07:21 +00005174
5175 /* update conch with host and path (this will fail if other process
5176 ** has a shared lock already), if the host id matches, use the big
5177 ** stick.
drh715ff302008-12-03 22:32:44 +00005178 */
drh7ed97b92010-01-20 13:07:21 +00005179 futimes(conchFile->h, NULL);
5180 if( hostIdMatch && !createConch ){
5181 if( conchFile->pLock && conchFile->pLock->cnt>1 ){
5182 /* We are trying for an exclusive lock but another thread in this
5183 ** same process is still holding a shared lock. */
5184 rc = SQLITE_BUSY;
5185 } else {
5186 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005187 }
drh715ff302008-12-03 22:32:44 +00005188 }else{
drh7ed97b92010-01-20 13:07:21 +00005189 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005190 }
drh7ed97b92010-01-20 13:07:21 +00005191 if( rc==SQLITE_OK ){
5192 char writeBuffer[PROXY_MAXCONCHLEN];
5193 int writeSize = 0;
5194
5195 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5196 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5197 if( pCtx->lockProxyPath!=NULL ){
5198 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5199 }else{
5200 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5201 }
5202 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5203 ftruncate(conchFile->h, writeSize);
5204 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5205 fsync(conchFile->h);
5206 /* If we created a new conch file (not just updated the contents of a
5207 ** valid conch file), try to match the permissions of the database
5208 */
5209 if( rc==SQLITE_OK && createConch ){
5210 struct stat buf;
5211 int err = fstat(pFile->h, &buf);
5212 if( err==0 ){
5213 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5214 S_IROTH|S_IWOTH);
5215 /* try to match the database file R/W permissions, ignore failure */
5216#ifndef SQLITE_PROXY_DEBUG
5217 fchmod(conchFile->h, cmode);
5218#else
5219 if( fchmod(conchFile->h, cmode)!=0 ){
5220 int code = errno;
5221 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5222 cmode, code, strerror(code));
5223 } else {
5224 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5225 }
5226 }else{
5227 int code = errno;
5228 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5229 err, code, strerror(code));
5230#endif
5231 }
drh715ff302008-12-03 22:32:44 +00005232 }
5233 }
drh7ed97b92010-01-20 13:07:21 +00005234 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5235
5236 end_takeconch:
5237 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
5238 if( rc==SQLITE_OK && pFile->openFlags ){
5239 if( pFile->h>=0 ){
5240#ifdef STRICT_CLOSE_ERROR
5241 if( close(pFile->h) ){
5242 pFile->lastErrno = errno;
5243 return SQLITE_IOERR_CLOSE;
5244 }
5245#else
5246 close(pFile->h); /* silently leak fd if fail */
5247#endif
5248 }
5249 pFile->h = -1;
5250 int fd = open(pCtx->dbPath, pFile->openFlags,
5251 SQLITE_DEFAULT_FILE_PERMISSIONS);
5252 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
5253 if( fd>=0 ){
5254 pFile->h = fd;
5255 }else{
drh9978c972010-02-23 17:36:32 +00005256 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005257 during locking */
5258 }
5259 }
5260 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5261 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5262 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5263 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5264 /* we couldn't create the proxy lock file with the old lock file path
5265 ** so try again via auto-naming
5266 */
5267 forceNewLockPath = 1;
5268 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005269 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005270 }
5271 }
5272 if( rc==SQLITE_OK ){
5273 /* Need to make a copy of path if we extracted the value
5274 ** from the conch file or the path was allocated on the stack
5275 */
5276 if( tempLockPath ){
5277 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5278 if( !pCtx->lockProxyPath ){
5279 rc = SQLITE_NOMEM;
5280 }
5281 }
5282 }
5283 if( rc==SQLITE_OK ){
5284 pCtx->conchHeld = 1;
5285
5286 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5287 afpLockingContext *afpCtx;
5288 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5289 afpCtx->dbPath = pCtx->lockProxyPath;
5290 }
5291 } else {
5292 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5293 }
5294 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
5295 return rc;
5296 } 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 +00005297 }
5298}
5299
5300/*
5301** If pFile holds a lock on a conch file, then release that lock.
5302*/
5303static int proxyReleaseConch(unixFile *pFile){
5304 int rc; /* Subroutine return code */
5305 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5306 unixFile *conchFile; /* Name of the conch file */
5307
5308 pCtx = (proxyLockingContext *)pFile->lockingContext;
5309 conchFile = pCtx->conchFile;
5310 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
5311 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
5312 getpid());
drh7ed97b92010-01-20 13:07:21 +00005313 if( pCtx->conchHeld>0 ){
5314 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5315 }
drh715ff302008-12-03 22:32:44 +00005316 pCtx->conchHeld = 0;
drh715ff302008-12-03 22:32:44 +00005317 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
5318 (rc==SQLITE_OK ? "ok" : "failed"));
5319 return rc;
5320}
5321
5322/*
5323** Given the name of a database file, compute the name of its conch file.
5324** Store the conch filename in memory obtained from sqlite3_malloc().
5325** Make *pConchPath point to the new name. Return SQLITE_OK on success
5326** or SQLITE_NOMEM if unable to obtain memory.
5327**
5328** The caller is responsible for ensuring that the allocated memory
5329** space is eventually freed.
5330**
5331** *pConchPath is set to NULL if a memory allocation error occurs.
5332*/
5333static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5334 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005335 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005336 char *conchPath; /* buffer in which to construct conch name */
5337
5338 /* Allocate space for the conch filename and initialize the name to
5339 ** the name of the original database file. */
5340 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5341 if( conchPath==0 ){
5342 return SQLITE_NOMEM;
5343 }
5344 memcpy(conchPath, dbPath, len+1);
5345
5346 /* now insert a "." before the last / character */
5347 for( i=(len-1); i>=0; i-- ){
5348 if( conchPath[i]=='/' ){
5349 i++;
5350 break;
5351 }
5352 }
5353 conchPath[i]='.';
5354 while ( i<len ){
5355 conchPath[i+1]=dbPath[i];
5356 i++;
5357 }
5358
5359 /* append the "-conch" suffix to the file */
5360 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005361 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005362
5363 return SQLITE_OK;
5364}
5365
5366
5367/* Takes a fully configured proxy locking-style unix file and switches
5368** the local lock file path
5369*/
5370static int switchLockProxyPath(unixFile *pFile, const char *path) {
5371 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5372 char *oldPath = pCtx->lockProxyPath;
5373 int rc = SQLITE_OK;
5374
5375 if( pFile->locktype!=NO_LOCK ){
5376 return SQLITE_BUSY;
5377 }
5378
5379 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5380 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5381 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5382 return SQLITE_OK;
5383 }else{
5384 unixFile *lockProxy = pCtx->lockProxy;
5385 pCtx->lockProxy=NULL;
5386 pCtx->conchHeld = 0;
5387 if( lockProxy!=NULL ){
5388 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5389 if( rc ) return rc;
5390 sqlite3_free(lockProxy);
5391 }
5392 sqlite3_free(oldPath);
5393 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5394 }
5395
5396 return rc;
5397}
5398
5399/*
5400** pFile is a file that has been opened by a prior xOpen call. dbPath
5401** is a string buffer at least MAXPATHLEN+1 characters in size.
5402**
5403** This routine find the filename associated with pFile and writes it
5404** int dbPath.
5405*/
5406static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005407#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005408 if( pFile->pMethod == &afpIoMethods ){
5409 /* afp style keeps a reference to the db path in the filePath field
5410 ** of the struct */
drhea678832008-12-10 19:26:22 +00005411 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005412 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5413 } else
drh715ff302008-12-03 22:32:44 +00005414#endif
5415 if( pFile->pMethod == &dotlockIoMethods ){
5416 /* dot lock style uses the locking context to store the dot lock
5417 ** file path */
5418 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5419 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5420 }else{
5421 /* all other styles use the locking context to store the db file path */
5422 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005423 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005424 }
5425 return SQLITE_OK;
5426}
5427
5428/*
5429** Takes an already filled in unix file and alters it so all file locking
5430** will be performed on the local proxy lock file. The following fields
5431** are preserved in the locking context so that they can be restored and
5432** the unix structure properly cleaned up at close time:
5433** ->lockingContext
5434** ->pMethod
5435*/
5436static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5437 proxyLockingContext *pCtx;
5438 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5439 char *lockPath=NULL;
5440 int rc = SQLITE_OK;
5441
5442 if( pFile->locktype!=NO_LOCK ){
5443 return SQLITE_BUSY;
5444 }
5445 proxyGetDbPathForUnixFile(pFile, dbPath);
5446 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5447 lockPath=NULL;
5448 }else{
5449 lockPath=(char *)path;
5450 }
5451
5452 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5453 (lockPath ? lockPath : ":auto:"), getpid());
5454
5455 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5456 if( pCtx==0 ){
5457 return SQLITE_NOMEM;
5458 }
5459 memset(pCtx, 0, sizeof(*pCtx));
5460
5461 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5462 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005463 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5464 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5465 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5466 ** (c) the file system is read-only, then enable no-locking access.
5467 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5468 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5469 */
5470 struct statfs fsInfo;
5471 struct stat conchInfo;
5472 int goLockless = 0;
5473
5474 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5475 int err = errno;
5476 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5477 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5478 }
5479 }
5480 if( goLockless ){
5481 pCtx->conchHeld = -1; /* read only FS/ lockless */
5482 rc = SQLITE_OK;
5483 }
5484 }
drh715ff302008-12-03 22:32:44 +00005485 }
5486 if( rc==SQLITE_OK && lockPath ){
5487 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5488 }
5489
5490 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005491 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5492 if( pCtx->dbPath==NULL ){
5493 rc = SQLITE_NOMEM;
5494 }
5495 }
5496 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005497 /* all memory is allocated, proxys are created and assigned,
5498 ** switch the locking context and pMethod then return.
5499 */
drh715ff302008-12-03 22:32:44 +00005500 pCtx->oldLockingContext = pFile->lockingContext;
5501 pFile->lockingContext = pCtx;
5502 pCtx->pOldMethod = pFile->pMethod;
5503 pFile->pMethod = &proxyIoMethods;
5504 }else{
5505 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00005506 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00005507 sqlite3_free(pCtx->conchFile);
5508 }
drh7ed97b92010-01-20 13:07:21 +00005509 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00005510 sqlite3_free(pCtx->conchFilePath);
5511 sqlite3_free(pCtx);
5512 }
5513 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
5514 (rc==SQLITE_OK ? "ok" : "failed"));
5515 return rc;
5516}
5517
5518
5519/*
5520** This routine handles sqlite3_file_control() calls that are specific
5521** to proxy locking.
5522*/
5523static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5524 switch( op ){
5525 case SQLITE_GET_LOCKPROXYFILE: {
5526 unixFile *pFile = (unixFile*)id;
5527 if( pFile->pMethod == &proxyIoMethods ){
5528 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5529 proxyTakeConch(pFile);
5530 if( pCtx->lockProxyPath ){
5531 *(const char **)pArg = pCtx->lockProxyPath;
5532 }else{
5533 *(const char **)pArg = ":auto: (not held)";
5534 }
5535 } else {
5536 *(const char **)pArg = NULL;
5537 }
5538 return SQLITE_OK;
5539 }
5540 case SQLITE_SET_LOCKPROXYFILE: {
5541 unixFile *pFile = (unixFile*)id;
5542 int rc = SQLITE_OK;
5543 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5544 if( pArg==NULL || (const char *)pArg==0 ){
5545 if( isProxyStyle ){
5546 /* turn off proxy locking - not supported */
5547 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5548 }else{
5549 /* turn off proxy locking - already off - NOOP */
5550 rc = SQLITE_OK;
5551 }
5552 }else{
5553 const char *proxyPath = (const char *)pArg;
5554 if( isProxyStyle ){
5555 proxyLockingContext *pCtx =
5556 (proxyLockingContext*)pFile->lockingContext;
5557 if( !strcmp(pArg, ":auto:")
5558 || (pCtx->lockProxyPath &&
5559 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5560 ){
5561 rc = SQLITE_OK;
5562 }else{
5563 rc = switchLockProxyPath(pFile, proxyPath);
5564 }
5565 }else{
5566 /* turn on proxy file locking */
5567 rc = proxyTransformUnixFile(pFile, proxyPath);
5568 }
5569 }
5570 return rc;
5571 }
5572 default: {
5573 assert( 0 ); /* The call assures that only valid opcodes are sent */
5574 }
5575 }
5576 /*NOTREACHED*/
5577 return SQLITE_ERROR;
5578}
5579
5580/*
5581** Within this division (the proxying locking implementation) the procedures
5582** above this point are all utilities. The lock-related methods of the
5583** proxy-locking sqlite3_io_method object follow.
5584*/
5585
5586
5587/*
5588** This routine checks if there is a RESERVED lock held on the specified
5589** file by this or any other process. If such a lock is held, set *pResOut
5590** to a non-zero value otherwise *pResOut is set to zero. The return value
5591** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5592*/
5593static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5594 unixFile *pFile = (unixFile*)id;
5595 int rc = proxyTakeConch(pFile);
5596 if( rc==SQLITE_OK ){
5597 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005598 if( pCtx->conchHeld>0 ){
5599 unixFile *proxy = pCtx->lockProxy;
5600 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5601 }else{ /* conchHeld < 0 is lockless */
5602 pResOut=0;
5603 }
drh715ff302008-12-03 22:32:44 +00005604 }
5605 return rc;
5606}
5607
5608/*
5609** Lock the file with the lock specified by parameter locktype - one
5610** of the following:
5611**
5612** (1) SHARED_LOCK
5613** (2) RESERVED_LOCK
5614** (3) PENDING_LOCK
5615** (4) EXCLUSIVE_LOCK
5616**
5617** Sometimes when requesting one lock state, additional lock states
5618** are inserted in between. The locking might fail on one of the later
5619** transitions leaving the lock state different from what it started but
5620** still short of its goal. The following chart shows the allowed
5621** transitions and the inserted intermediate states:
5622**
5623** UNLOCKED -> SHARED
5624** SHARED -> RESERVED
5625** SHARED -> (PENDING) -> EXCLUSIVE
5626** RESERVED -> (PENDING) -> EXCLUSIVE
5627** PENDING -> EXCLUSIVE
5628**
5629** This routine will only increase a lock. Use the sqlite3OsUnlock()
5630** routine to lower a locking level.
5631*/
5632static int proxyLock(sqlite3_file *id, int locktype) {
5633 unixFile *pFile = (unixFile*)id;
5634 int rc = proxyTakeConch(pFile);
5635 if( rc==SQLITE_OK ){
5636 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005637 if( pCtx->conchHeld>0 ){
5638 unixFile *proxy = pCtx->lockProxy;
5639 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
5640 pFile->locktype = proxy->locktype;
5641 }else{
5642 /* conchHeld < 0 is lockless */
5643 }
drh715ff302008-12-03 22:32:44 +00005644 }
5645 return rc;
5646}
5647
5648
5649/*
5650** Lower the locking level on file descriptor pFile to locktype. locktype
5651** must be either NO_LOCK or SHARED_LOCK.
5652**
5653** If the locking level of the file descriptor is already at or below
5654** the requested locking level, this routine is a no-op.
5655*/
5656static int proxyUnlock(sqlite3_file *id, int locktype) {
5657 unixFile *pFile = (unixFile*)id;
5658 int rc = proxyTakeConch(pFile);
5659 if( rc==SQLITE_OK ){
5660 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005661 if( pCtx->conchHeld>0 ){
5662 unixFile *proxy = pCtx->lockProxy;
5663 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5664 pFile->locktype = proxy->locktype;
5665 }else{
5666 /* conchHeld < 0 is lockless */
5667 }
drh715ff302008-12-03 22:32:44 +00005668 }
5669 return rc;
5670}
5671
5672/*
5673** Close a file that uses proxy locks.
5674*/
5675static int proxyClose(sqlite3_file *id) {
5676 if( id ){
5677 unixFile *pFile = (unixFile*)id;
5678 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5679 unixFile *lockProxy = pCtx->lockProxy;
5680 unixFile *conchFile = pCtx->conchFile;
5681 int rc = SQLITE_OK;
5682
5683 if( lockProxy ){
5684 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5685 if( rc ) return rc;
5686 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5687 if( rc ) return rc;
5688 sqlite3_free(lockProxy);
5689 pCtx->lockProxy = 0;
5690 }
5691 if( conchFile ){
5692 if( pCtx->conchHeld ){
5693 rc = proxyReleaseConch(pFile);
5694 if( rc ) return rc;
5695 }
5696 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5697 if( rc ) return rc;
5698 sqlite3_free(conchFile);
5699 }
5700 sqlite3_free(pCtx->lockProxyPath);
5701 sqlite3_free(pCtx->conchFilePath);
5702 sqlite3_free(pCtx->dbPath);
5703 /* restore the original locking context and pMethod then close it */
5704 pFile->lockingContext = pCtx->oldLockingContext;
5705 pFile->pMethod = pCtx->pOldMethod;
5706 sqlite3_free(pCtx);
5707 return pFile->pMethod->xClose(id);
5708 }
5709 return SQLITE_OK;
5710}
5711
5712
5713
drhd2cb50b2009-01-09 21:41:17 +00005714#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005715/*
5716** The proxy locking style is intended for use with AFP filesystems.
5717** And since AFP is only supported on MacOSX, the proxy locking is also
5718** restricted to MacOSX.
5719**
5720**
5721******************* End of the proxy lock implementation **********************
5722******************************************************************************/
5723
drh734c9862008-11-28 15:37:20 +00005724/*
danielk1977e339d652008-06-28 11:23:00 +00005725** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005726**
5727** This routine registers all VFS implementations for unix-like operating
5728** systems. This routine, and the sqlite3_os_end() routine that follows,
5729** should be the only routines in this file that are visible from other
5730** files.
drh6b9d6dd2008-12-03 19:34:47 +00005731**
5732** This routine is called once during SQLite initialization and by a
5733** single thread. The memory allocation and mutex subsystems have not
5734** necessarily been initialized when this routine is called, and so they
5735** should not be used.
drh153c62c2007-08-24 03:51:33 +00005736*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005737int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005738 /*
5739 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005740 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5741 ** to the "finder" function. (pAppData is a pointer to a pointer because
5742 ** silly C90 rules prohibit a void* from being cast to a function pointer
5743 ** and so we have to go through the intermediate pointer to avoid problems
5744 ** when compiling with -pedantic-errors on GCC.)
5745 **
5746 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005747 ** finder-function. The finder-function returns a pointer to the
5748 ** sqlite_io_methods object that implements the desired locking
5749 ** behaviors. See the division above that contains the IOMETHODS
5750 ** macro for addition information on finder-functions.
5751 **
5752 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5753 ** object. But the "autolockIoFinder" available on MacOSX does a little
5754 ** more than that; it looks at the filesystem type that hosts the
5755 ** database file and tries to choose an locking method appropriate for
5756 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005757 */
drh7708e972008-11-29 00:56:52 +00005758 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005759 1, /* iVersion */ \
5760 sizeof(unixFile), /* szOsFile */ \
5761 MAX_PATHNAME, /* mxPathname */ \
5762 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005763 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005764 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005765 unixOpen, /* xOpen */ \
5766 unixDelete, /* xDelete */ \
5767 unixAccess, /* xAccess */ \
5768 unixFullPathname, /* xFullPathname */ \
5769 unixDlOpen, /* xDlOpen */ \
5770 unixDlError, /* xDlError */ \
5771 unixDlSym, /* xDlSym */ \
5772 unixDlClose, /* xDlClose */ \
5773 unixRandomness, /* xRandomness */ \
5774 unixSleep, /* xSleep */ \
5775 unixCurrentTime, /* xCurrentTime */ \
5776 unixGetLastError /* xGetLastError */ \
5777 }
5778
drh6b9d6dd2008-12-03 19:34:47 +00005779 /*
5780 ** All default VFSes for unix are contained in the following array.
5781 **
5782 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5783 ** by the SQLite core when the VFS is registered. So the following
5784 ** array cannot be const.
5785 */
danielk1977e339d652008-06-28 11:23:00 +00005786 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005787#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005788 UNIXVFS("unix", autolockIoFinder ),
5789#else
5790 UNIXVFS("unix", posixIoFinder ),
5791#endif
5792 UNIXVFS("unix-none", nolockIoFinder ),
5793 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005794#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005795 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005796#endif
5797#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005798 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005799#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005800 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005801#endif
chw78a13182009-04-07 05:35:03 +00005802#endif
drhd2cb50b2009-01-09 21:41:17 +00005803#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005804 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00005805 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00005806 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005807#endif
drh153c62c2007-08-24 03:51:33 +00005808 };
drh6b9d6dd2008-12-03 19:34:47 +00005809 unsigned int i; /* Loop counter */
5810
5811 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005812 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005813 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005814 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005815 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005816}
danielk1977e339d652008-06-28 11:23:00 +00005817
5818/*
drh6b9d6dd2008-12-03 19:34:47 +00005819** Shutdown the operating system interface.
5820**
5821** Some operating systems might need to do some cleanup in this routine,
5822** to release dynamically allocated objects. But not on unix.
5823** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005824*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005825int sqlite3_os_end(void){
5826 return SQLITE_OK;
5827}
drhdce8bdb2007-08-16 13:01:44 +00005828
danielk197729bafea2008-06-26 10:41:19 +00005829#endif /* SQLITE_OS_UNIX */