blob: 18ec658701d28e619e9b2d6f0ea53e4cf9acd619 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
209 int lastErrno; /* The unix errno from last I/O error */
210 void *lockingContext; /* Locking style specific state */
211 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
212 int fileFlags; /* Miscellanous flags */
213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drh0c2694b2009-09-03 16:23:44 +0000247** The following macros define bits in unixFile.fileFlags
248*/
249#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
250
251/*
drh198bf392006-01-06 21:52:49 +0000252** Include code that is common to all os_*.c files
253*/
254#include "os_common.h"
255
256/*
drh0ccebe72005-06-07 22:22:50 +0000257** Define various macros that are missing from some systems.
258*/
drhbbd42a62004-05-22 17:41:58 +0000259#ifndef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifdef SQLITE_DISABLE_LFS
263# undef O_LARGEFILE
264# define O_LARGEFILE 0
265#endif
266#ifndef O_NOFOLLOW
267# define O_NOFOLLOW 0
268#endif
269#ifndef O_BINARY
270# define O_BINARY 0
271#endif
272
273/*
drh2b4b5962005-06-15 17:47:55 +0000274** The threadid macro resolves to the thread-id or to 0. Used for
275** testing and debugging only.
276*/
drhd677b3d2007-08-20 22:48:41 +0000277#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000278#define threadid pthread_self()
279#else
280#define threadid 0
281#endif
282
drh99ab3b12011-03-02 15:09:07 +0000283/*
284** Many system calls are accessed through pointer-to-functions so that
285** they may be overridden at runtime to facilitate fault injection during
286** testing and sandboxing. The following array holds the names and pointers
287** to all overrideable system calls.
288*/
289static struct unix_syscall {
290 const char *zName; /* Name of the sytem call */
291 void *pCurrent; /* Current value of the system call */
292 void *pDefault; /* Default value */
293} aSyscall[] = {
294 { "open", (void*)open, 0 },
295#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
296
297 { "close", (void*)close, 0 },
298#define osClose ((int(*)(int))aSyscall[1].pCurrent)
299
300 { "access", (void*)access, 0 },
301#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
302
303 { "getcwd", (void*)getcwd, 0 },
304#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
305
306 { "stat", (void*)stat, 0 },
307#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
308
309/*
310** The DJGPP compiler environment looks mostly like Unix, but it
311** lacks the fcntl() system call. So redefine fcntl() to be something
312** that always succeeds. This means that locking does not occur under
313** DJGPP. But it is DOS - what did you expect?
314*/
315#ifdef __DJGPP__
316 { "fstat", 0, 0 },
317#define osFstat(a,b,c) 0
318#else
319 { "fstat", (void*)fstat, 0 },
320#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
321#endif
322
323 { "ftruncate", (void*)ftruncate, 0 },
324#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
325
drhe562be52011-03-02 18:01:10 +0000326 { "fcntl", (void*)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000327#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000328
329 { "read", (void*)read, 0 },
330#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
331
332#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
333 { "pread", (void*)pread, 0 },
334#else
335 { "pread", (void*)0, 0 },
336#endif
337#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
338
339#if defined(USE_PREAD64)
340 { "pread64", (void*)pread64, 0 },
341#else
342 { "pread64", (void*)0, 0 },
343#endif
344#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
345
346 { "write", (void*)write, 0 },
347#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
348
349#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
350 { "pwrite", (void*)pwrite, 0 },
351#else
352 { "pwrite", (void*)0, 0 },
353#endif
354#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
355 aSyscall[12].pCurrent)
356
357#if defined(USE_PREAD64)
358 { "pwrite64", (void*)pwrite64, 0 },
359#else
360 { "pwrite64", (void*)0, 0 },
361#endif
362#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
363 aSyscall[13].pCurrent)
364
365 { "fchmod", (void*)fchmod, 0 },
366#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
367
368#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
369 { "fallocate", (void*)posix_fallocate, 0 },
370#else
371 { "fallocate", (void*)0, 0 },
372#endif
373#define osFallocate ((int(*)(int,off_t,off_t)aSyscall[15].pCurrent)
374
375}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000376
377/*
378** This is the xSetSystemCall() method of sqlite3_vfs for all of the
379** "unix" VFSes.
380*/
381static int unixSetSystemCall(
382 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
383 const char *zName, /* Name of system call to override */
384 void *pNewFunc /* Pointer to new system call value */
385){
386 int i;
387 int rc = 0;
388 if( zName==0 ){
389 /* If no zName is given, restore all system calls to their default
390 ** settings and return NULL
391 */
392 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
393 if( aSyscall[i].pDefault ){
394 aSyscall[i].pCurrent = aSyscall[i].pDefault;
395 rc = 1;
396 }
397 }
398 }else{
399 /* If zName is specified, operate on only the one system call
400 ** specified.
401 */
402 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
403 if( strcmp(zName, aSyscall[i].zName)==0 ){
404 if( aSyscall[i].pDefault==0 ){
405 aSyscall[i].pDefault = aSyscall[i].pCurrent;
406 }
407 rc = 1;
408 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
409 aSyscall[i].pCurrent = pNewFunc;
410 break;
411 }
412 }
413 }
414 return rc;
415}
416
danielk197713adf8a2004-06-03 16:08:41 +0000417
drh107886a2008-11-21 22:21:50 +0000418/*
dan9359c7b2009-08-21 08:29:10 +0000419** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000420** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000421** vxworksFileId objects used by this file, all of which may be
422** shared by multiple threads.
423**
424** Function unixMutexHeld() is used to assert() that the global mutex
425** is held when required. This function is only used as part of assert()
426** statements. e.g.
427**
428** unixEnterMutex()
429** assert( unixMutexHeld() );
430** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000431*/
432static void unixEnterMutex(void){
433 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
434}
435static void unixLeaveMutex(void){
436 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
437}
dan9359c7b2009-08-21 08:29:10 +0000438#ifdef SQLITE_DEBUG
439static int unixMutexHeld(void) {
440 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
441}
442#endif
drh107886a2008-11-21 22:21:50 +0000443
drh734c9862008-11-28 15:37:20 +0000444
445#ifdef SQLITE_DEBUG
446/*
447** Helper function for printing out trace information from debugging
448** binaries. This returns the string represetation of the supplied
449** integer lock-type.
450*/
drh308c2a52010-05-14 11:30:18 +0000451static const char *azFileLock(int eFileLock){
452 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000453 case NO_LOCK: return "NONE";
454 case SHARED_LOCK: return "SHARED";
455 case RESERVED_LOCK: return "RESERVED";
456 case PENDING_LOCK: return "PENDING";
457 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000458 }
459 return "ERROR";
460}
461#endif
462
463#ifdef SQLITE_LOCK_TRACE
464/*
465** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000466**
drh734c9862008-11-28 15:37:20 +0000467** This routine is used for troubleshooting locks on multithreaded
468** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
469** command-line option on the compiler. This code is normally
470** turned off.
471*/
472static int lockTrace(int fd, int op, struct flock *p){
473 char *zOpName, *zType;
474 int s;
475 int savedErrno;
476 if( op==F_GETLK ){
477 zOpName = "GETLK";
478 }else if( op==F_SETLK ){
479 zOpName = "SETLK";
480 }else{
drh99ab3b12011-03-02 15:09:07 +0000481 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000482 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
483 return s;
484 }
485 if( p->l_type==F_RDLCK ){
486 zType = "RDLCK";
487 }else if( p->l_type==F_WRLCK ){
488 zType = "WRLCK";
489 }else if( p->l_type==F_UNLCK ){
490 zType = "UNLCK";
491 }else{
492 assert( 0 );
493 }
494 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000495 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000496 savedErrno = errno;
497 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
498 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
499 (int)p->l_pid, s);
500 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
501 struct flock l2;
502 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000503 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000504 if( l2.l_type==F_RDLCK ){
505 zType = "RDLCK";
506 }else if( l2.l_type==F_WRLCK ){
507 zType = "WRLCK";
508 }else if( l2.l_type==F_UNLCK ){
509 zType = "UNLCK";
510 }else{
511 assert( 0 );
512 }
513 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
514 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
515 }
516 errno = savedErrno;
517 return s;
518}
drh99ab3b12011-03-02 15:09:07 +0000519#undef osFcntl
520#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000521#endif /* SQLITE_LOCK_TRACE */
522
523
drhff812312011-02-23 13:33:46 +0000524/*
525** Retry ftruncate() calls that fail due to EINTR
526*/
527#ifdef EINTR
528static int robust_ftruncate(int h, sqlite3_int64 sz){
529 int rc;
drh99ab3b12011-03-02 15:09:07 +0000530 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000531 return rc;
532}
533#else
drh99ab3b12011-03-02 15:09:07 +0000534# define robust_ftruncate(a,b) osFtruncate(a,b)
drhff812312011-02-23 13:33:46 +0000535#endif
536
drh734c9862008-11-28 15:37:20 +0000537
538/*
539** This routine translates a standard POSIX errno code into something
540** useful to the clients of the sqlite3 functions. Specifically, it is
541** intended to translate a variety of "try again" errors into SQLITE_BUSY
542** and a variety of "please close the file descriptor NOW" errors into
543** SQLITE_IOERR
544**
545** Errors during initialization of locks, or file system support for locks,
546** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
547*/
548static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
549 switch (posixError) {
550 case 0:
551 return SQLITE_OK;
552
553 case EAGAIN:
554 case ETIMEDOUT:
555 case EBUSY:
556 case EINTR:
557 case ENOLCK:
558 /* random NFS retry error, unless during file system support
559 * introspection, in which it actually means what it says */
560 return SQLITE_BUSY;
561
562 case EACCES:
563 /* EACCES is like EAGAIN during locking operations, but not any other time*/
564 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
565 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
566 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
567 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
568 return SQLITE_BUSY;
569 }
570 /* else fall through */
571 case EPERM:
572 return SQLITE_PERM;
573
574 case EDEADLK:
575 return SQLITE_IOERR_BLOCKED;
576
577#if EOPNOTSUPP!=ENOTSUP
578 case EOPNOTSUPP:
579 /* something went terribly awry, unless during file system support
580 * introspection, in which it actually means what it says */
581#endif
582#ifdef ENOTSUP
583 case ENOTSUP:
584 /* invalid fd, unless during file system support introspection, in which
585 * it actually means what it says */
586#endif
587 case EIO:
588 case EBADF:
589 case EINVAL:
590 case ENOTCONN:
591 case ENODEV:
592 case ENXIO:
593 case ENOENT:
594 case ESTALE:
595 case ENOSYS:
596 /* these should force the client to close the file and reconnect */
597
598 default:
599 return sqliteIOErr;
600 }
601}
602
603
604
605/******************************************************************************
606****************** Begin Unique File ID Utility Used By VxWorks ***************
607**
608** On most versions of unix, we can get a unique ID for a file by concatenating
609** the device number and the inode number. But this does not work on VxWorks.
610** On VxWorks, a unique file id must be based on the canonical filename.
611**
612** A pointer to an instance of the following structure can be used as a
613** unique file ID in VxWorks. Each instance of this structure contains
614** a copy of the canonical filename. There is also a reference count.
615** The structure is reclaimed when the number of pointers to it drops to
616** zero.
617**
618** There are never very many files open at one time and lookups are not
619** a performance-critical path, so it is sufficient to put these
620** structures on a linked list.
621*/
622struct vxworksFileId {
623 struct vxworksFileId *pNext; /* Next in a list of them all */
624 int nRef; /* Number of references to this one */
625 int nName; /* Length of the zCanonicalName[] string */
626 char *zCanonicalName; /* Canonical filename */
627};
628
629#if OS_VXWORKS
630/*
drh9b35ea62008-11-29 02:20:26 +0000631** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000632** variable:
633*/
634static struct vxworksFileId *vxworksFileList = 0;
635
636/*
637** Simplify a filename into its canonical form
638** by making the following changes:
639**
640** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000641** * convert /./ into just /
642** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000643**
644** Changes are made in-place. Return the new name length.
645**
646** The original filename is in z[0..n-1]. Return the number of
647** characters in the simplified name.
648*/
649static int vxworksSimplifyName(char *z, int n){
650 int i, j;
651 while( n>1 && z[n-1]=='/' ){ n--; }
652 for(i=j=0; i<n; i++){
653 if( z[i]=='/' ){
654 if( z[i+1]=='/' ) continue;
655 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
656 i += 1;
657 continue;
658 }
659 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
660 while( j>0 && z[j-1]!='/' ){ j--; }
661 if( j>0 ){ j--; }
662 i += 2;
663 continue;
664 }
665 }
666 z[j++] = z[i];
667 }
668 z[j] = 0;
669 return j;
670}
671
672/*
673** Find a unique file ID for the given absolute pathname. Return
674** a pointer to the vxworksFileId object. This pointer is the unique
675** file ID.
676**
677** The nRef field of the vxworksFileId object is incremented before
678** the object is returned. A new vxworksFileId object is created
679** and added to the global list if necessary.
680**
681** If a memory allocation error occurs, return NULL.
682*/
683static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
684 struct vxworksFileId *pNew; /* search key and new file ID */
685 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
686 int n; /* Length of zAbsoluteName string */
687
688 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000689 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000690 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
691 if( pNew==0 ) return 0;
692 pNew->zCanonicalName = (char*)&pNew[1];
693 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
694 n = vxworksSimplifyName(pNew->zCanonicalName, n);
695
696 /* Search for an existing entry that matching the canonical name.
697 ** If found, increment the reference count and return a pointer to
698 ** the existing file ID.
699 */
700 unixEnterMutex();
701 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
702 if( pCandidate->nName==n
703 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
704 ){
705 sqlite3_free(pNew);
706 pCandidate->nRef++;
707 unixLeaveMutex();
708 return pCandidate;
709 }
710 }
711
712 /* No match was found. We will make a new file ID */
713 pNew->nRef = 1;
714 pNew->nName = n;
715 pNew->pNext = vxworksFileList;
716 vxworksFileList = pNew;
717 unixLeaveMutex();
718 return pNew;
719}
720
721/*
722** Decrement the reference count on a vxworksFileId object. Free
723** the object when the reference count reaches zero.
724*/
725static void vxworksReleaseFileId(struct vxworksFileId *pId){
726 unixEnterMutex();
727 assert( pId->nRef>0 );
728 pId->nRef--;
729 if( pId->nRef==0 ){
730 struct vxworksFileId **pp;
731 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
732 assert( *pp==pId );
733 *pp = pId->pNext;
734 sqlite3_free(pId);
735 }
736 unixLeaveMutex();
737}
738#endif /* OS_VXWORKS */
739/*************** End of Unique File ID Utility Used By VxWorks ****************
740******************************************************************************/
741
742
743/******************************************************************************
744*************************** Posix Advisory Locking ****************************
745**
drh9b35ea62008-11-29 02:20:26 +0000746** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000747** section 6.5.2.2 lines 483 through 490 specify that when a process
748** sets or clears a lock, that operation overrides any prior locks set
749** by the same process. It does not explicitly say so, but this implies
750** that it overrides locks set by the same process using a different
751** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000752**
753** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000754** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
755**
756** Suppose ./file1 and ./file2 are really the same file (because
757** one is a hard or symbolic link to the other) then if you set
758** an exclusive lock on fd1, then try to get an exclusive lock
759** on fd2, it works. I would have expected the second lock to
760** fail since there was already a lock on the file due to fd1.
761** But not so. Since both locks came from the same process, the
762** second overrides the first, even though they were on different
763** file descriptors opened on different file names.
764**
drh734c9862008-11-28 15:37:20 +0000765** This means that we cannot use POSIX locks to synchronize file access
766** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000767** to synchronize access for threads in separate processes, but not
768** threads within the same process.
769**
770** To work around the problem, SQLite has to manage file locks internally
771** on its own. Whenever a new database is opened, we have to find the
772** specific inode of the database file (the inode is determined by the
773** st_dev and st_ino fields of the stat structure that fstat() fills in)
774** and check for locks already existing on that inode. When locks are
775** created or removed, we have to look at our own internal record of the
776** locks to see if another thread has previously set a lock on that same
777** inode.
778**
drh9b35ea62008-11-29 02:20:26 +0000779** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
780** For VxWorks, we have to use the alternative unique ID system based on
781** canonical filename and implemented in the previous division.)
782**
danielk1977ad94b582007-08-20 06:44:22 +0000783** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000784** descriptor. It is now a structure that holds the integer file
785** descriptor and a pointer to a structure that describes the internal
786** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000787** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000788** point to the same locking structure. The locking structure keeps
789** a reference count (so we will know when to delete it) and a "cnt"
790** field that tells us its internal lock status. cnt==0 means the
791** file is unlocked. cnt==-1 means the file has an exclusive lock.
792** cnt>0 means there are cnt shared locks on the file.
793**
794** Any attempt to lock or unlock a file first checks the locking
795** structure. The fcntl() system call is only invoked to set a
796** POSIX lock if the internal lock structure transitions between
797** a locked and an unlocked state.
798**
drh734c9862008-11-28 15:37:20 +0000799** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000800**
801** If you close a file descriptor that points to a file that has locks,
802** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000803** released. To work around this problem, each unixInodeInfo object
804** maintains a count of the number of pending locks on tha inode.
805** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000806** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000807** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000808** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000809** be closed and that list is walked (and cleared) when the last lock
810** clears.
811**
drh9b35ea62008-11-29 02:20:26 +0000812** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000813**
drh9b35ea62008-11-29 02:20:26 +0000814** Many older versions of linux use the LinuxThreads library which is
815** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000816** A cannot be modified or overridden by a different thread B.
817** Only thread A can modify the lock. Locking behavior is correct
818** if the appliation uses the newer Native Posix Thread Library (NPTL)
819** on linux - with NPTL a lock created by thread A can override locks
820** in thread B. But there is no way to know at compile-time which
821** threading library is being used. So there is no way to know at
822** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000823** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000824** current process.
drh5fdae772004-06-29 03:29:00 +0000825**
drh8af6c222010-05-14 12:43:01 +0000826** SQLite used to support LinuxThreads. But support for LinuxThreads
827** was dropped beginning with version 3.7.0. SQLite will still work with
828** LinuxThreads provided that (1) there is no more than one connection
829** per database file in the same process and (2) database connections
830** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000831*/
832
833/*
834** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000835** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000836*/
837struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000838 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000839#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000840 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000841#else
drh107886a2008-11-21 22:21:50 +0000842 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000843#endif
844};
845
846/*
drhbbd42a62004-05-22 17:41:58 +0000847** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000848** inode. Or, on LinuxThreads, there is one of these structures for
849** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000850**
danielk1977ad94b582007-08-20 06:44:22 +0000851** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000852** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000853** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000854*/
drh8af6c222010-05-14 12:43:01 +0000855struct unixInodeInfo {
856 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000857 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000858 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000859 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000860 unixShmNode *pShmNode; /* Shared memory associated with this inode */
861 int nLock; /* Number of outstanding file locks */
862 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
863 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
864 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000865#if defined(SQLITE_ENABLE_LOCKING_STYLE)
866 unsigned long long sharedByte; /* for AFP simulated shared lock */
867#endif
drh6c7d5c52008-11-21 20:32:33 +0000868#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000869 sem_t *pSem; /* Named POSIX semaphore */
870 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000871#endif
drhbbd42a62004-05-22 17:41:58 +0000872};
873
drhda0e7682008-07-30 15:27:54 +0000874/*
drh8af6c222010-05-14 12:43:01 +0000875** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000876*/
drhd91c68f2010-05-14 14:52:25 +0000877static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000878
drh5fdae772004-06-29 03:29:00 +0000879/*
dane18d4952011-02-21 11:46:24 +0000880**
881** This function - unixLogError_x(), is only ever called via the macro
882** unixLogError().
883**
884** It is invoked after an error occurs in an OS function and errno has been
885** set. It logs a message using sqlite3_log() containing the current value of
886** errno and, if possible, the human-readable equivalent from strerror() or
887** strerror_r().
888**
889** The first argument passed to the macro should be the error code that
890** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
891** The two subsequent arguments should be the name of the OS function that
892** failed (e.g. "unlink", "open") and the the associated file-system path,
893** if any.
894*/
drh0e9365c2011-03-02 02:08:13 +0000895#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
896static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000897 int errcode, /* SQLite error code */
898 const char *zFunc, /* Name of OS function that failed */
899 const char *zPath, /* File path associated with error */
900 int iLine /* Source line number where error occurred */
901){
902 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000903 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000904
905 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
906 ** the strerror() function to obtain the human-readable error message
907 ** equivalent to errno. Otherwise, use strerror_r().
908 */
909#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
910 char aErr[80];
911 memset(aErr, 0, sizeof(aErr));
912 zErr = aErr;
913
914 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
915 ** assume that the system provides the the GNU version of strerror_r() that
916 ** returns a pointer to a buffer containing the error message. That pointer
917 ** may point to aErr[], or it may point to some static storage somewhere.
918 ** Otherwise, assume that the system provides the POSIX version of
919 ** strerror_r(), which always writes an error message into aErr[].
920 **
921 ** If the code incorrectly assumes that it is the POSIX version that is
922 ** available, the error message will often be an empty string. Not a
923 ** huge problem. Incorrectly concluding that the GNU version is available
924 ** could lead to a segfault though.
925 */
926#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
927 zErr =
928# endif
drh0e9365c2011-03-02 02:08:13 +0000929 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000930
931#elif SQLITE_THREADSAFE
932 /* This is a threadsafe build, but strerror_r() is not available. */
933 zErr = "";
934#else
935 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000936 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000937#endif
938
939 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000940 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000941 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000942 "os_unix.c:%d: (%d) %s(%s) - %s",
943 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000944 );
945
946 return errcode;
947}
948
drh0e9365c2011-03-02 02:08:13 +0000949/*
950** Close a file descriptor.
951**
952** We assume that close() almost always works, since it is only in a
953** very sick application or on a very sick platform that it might fail.
954** If it does fail, simply leak the file descriptor, but do log the
955** error.
956**
957** Note that it is not safe to retry close() after EINTR since the
958** file descriptor might have already been reused by another thread.
959** So we don't even try to recover from an EINTR. Just log the error
960** and move on.
961*/
962static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +0000963 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +0000964 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
965 pFile ? pFile->zPath : 0, lineno);
966 }
967}
dane18d4952011-02-21 11:46:24 +0000968
969/*
danb0ac3e32010-06-16 10:55:42 +0000970** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +0000971*/
drh0e9365c2011-03-02 02:08:13 +0000972static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +0000973 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +0000974 UnixUnusedFd *p;
975 UnixUnusedFd *pNext;
976 for(p=pInode->pUnused; p; p=pNext){
977 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +0000978 robust_close(pFile, p->fd, __LINE__);
979 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +0000980 }
drh0e9365c2011-03-02 02:08:13 +0000981 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +0000982}
983
984/*
drh8af6c222010-05-14 12:43:01 +0000985** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000986**
987** The mutex entered using the unixEnterMutex() function must be held
988** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000989*/
danb0ac3e32010-06-16 10:55:42 +0000990static void releaseInodeInfo(unixFile *pFile){
991 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000992 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000993 if( pInode ){
994 pInode->nRef--;
995 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000996 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000997 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000998 if( pInode->pPrev ){
999 assert( pInode->pPrev->pNext==pInode );
1000 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001001 }else{
drh8af6c222010-05-14 12:43:01 +00001002 assert( inodeList==pInode );
1003 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001004 }
drh8af6c222010-05-14 12:43:01 +00001005 if( pInode->pNext ){
1006 assert( pInode->pNext->pPrev==pInode );
1007 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001008 }
drh8af6c222010-05-14 12:43:01 +00001009 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001010 }
drhbbd42a62004-05-22 17:41:58 +00001011 }
1012}
1013
1014/*
drh8af6c222010-05-14 12:43:01 +00001015** Given a file descriptor, locate the unixInodeInfo object that
1016** describes that file descriptor. Create a new one if necessary. The
1017** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001018**
dan9359c7b2009-08-21 08:29:10 +00001019** The mutex entered using the unixEnterMutex() function must be held
1020** when this function is called.
1021**
drh6c7d5c52008-11-21 20:32:33 +00001022** Return an appropriate error code.
1023*/
drh8af6c222010-05-14 12:43:01 +00001024static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001025 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001026 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001027){
1028 int rc; /* System call return code */
1029 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001030 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1031 struct stat statbuf; /* Low-level file information */
1032 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001033
dan9359c7b2009-08-21 08:29:10 +00001034 assert( unixMutexHeld() );
1035
drh6c7d5c52008-11-21 20:32:33 +00001036 /* Get low-level information about the file that we can used to
1037 ** create a unique name for the file.
1038 */
1039 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001040 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001041 if( rc!=0 ){
1042 pFile->lastErrno = errno;
1043#ifdef EOVERFLOW
1044 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1045#endif
1046 return SQLITE_IOERR;
1047 }
1048
drheb0d74f2009-02-03 15:27:02 +00001049#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001050 /* On OS X on an msdos filesystem, the inode number is reported
1051 ** incorrectly for zero-size files. See ticket #3260. To work
1052 ** around this problem (we consider it a bug in OS X, not SQLite)
1053 ** we always increase the file size to 1 by writing a single byte
1054 ** prior to accessing the inode number. The one byte written is
1055 ** an ASCII 'S' character which also happens to be the first byte
1056 ** in the header of every SQLite database. In this way, if there
1057 ** is a race condition such that another thread has already populated
1058 ** the first page of the database, no damage is done.
1059 */
drh7ed97b92010-01-20 13:07:21 +00001060 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001061 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001062 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001063 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001064 return SQLITE_IOERR;
1065 }
drh99ab3b12011-03-02 15:09:07 +00001066 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001067 if( rc!=0 ){
1068 pFile->lastErrno = errno;
1069 return SQLITE_IOERR;
1070 }
1071 }
drheb0d74f2009-02-03 15:27:02 +00001072#endif
drh6c7d5c52008-11-21 20:32:33 +00001073
drh8af6c222010-05-14 12:43:01 +00001074 memset(&fileId, 0, sizeof(fileId));
1075 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001076#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001077 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001078#else
drh8af6c222010-05-14 12:43:01 +00001079 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001080#endif
drh8af6c222010-05-14 12:43:01 +00001081 pInode = inodeList;
1082 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1083 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001084 }
drh8af6c222010-05-14 12:43:01 +00001085 if( pInode==0 ){
1086 pInode = sqlite3_malloc( sizeof(*pInode) );
1087 if( pInode==0 ){
1088 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001089 }
drh8af6c222010-05-14 12:43:01 +00001090 memset(pInode, 0, sizeof(*pInode));
1091 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1092 pInode->nRef = 1;
1093 pInode->pNext = inodeList;
1094 pInode->pPrev = 0;
1095 if( inodeList ) inodeList->pPrev = pInode;
1096 inodeList = pInode;
1097 }else{
1098 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001099 }
drh8af6c222010-05-14 12:43:01 +00001100 *ppInode = pInode;
1101 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001102}
drh6c7d5c52008-11-21 20:32:33 +00001103
aswift5b1a2562008-08-22 00:22:35 +00001104
1105/*
danielk197713adf8a2004-06-03 16:08:41 +00001106** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001107** file by this or any other process. If such a lock is held, set *pResOut
1108** to a non-zero value otherwise *pResOut is set to zero. The return value
1109** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001110*/
danielk1977861f7452008-06-05 11:39:11 +00001111static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001112 int rc = SQLITE_OK;
1113 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001114 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001115
danielk1977861f7452008-06-05 11:39:11 +00001116 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1117
drh054889e2005-11-30 03:20:31 +00001118 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001119 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001120
1121 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001122 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001123 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001124 }
1125
drh2ac3ee92004-06-07 16:27:46 +00001126 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001127 */
danielk197709480a92009-02-09 05:32:32 +00001128#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001129 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001130 struct flock lock;
1131 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001132 lock.l_start = RESERVED_BYTE;
1133 lock.l_len = 1;
1134 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001135 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001136 int tErrno = errno;
1137 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1138 pFile->lastErrno = tErrno;
1139 } else if( lock.l_type!=F_UNLCK ){
1140 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001141 }
1142 }
danielk197709480a92009-02-09 05:32:32 +00001143#endif
danielk197713adf8a2004-06-03 16:08:41 +00001144
drh6c7d5c52008-11-21 20:32:33 +00001145 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001146 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001147
aswift5b1a2562008-08-22 00:22:35 +00001148 *pResOut = reserved;
1149 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001150}
1151
1152/*
drh308c2a52010-05-14 11:30:18 +00001153** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001154** of the following:
1155**
drh2ac3ee92004-06-07 16:27:46 +00001156** (1) SHARED_LOCK
1157** (2) RESERVED_LOCK
1158** (3) PENDING_LOCK
1159** (4) EXCLUSIVE_LOCK
1160**
drhb3e04342004-06-08 00:47:47 +00001161** Sometimes when requesting one lock state, additional lock states
1162** are inserted in between. The locking might fail on one of the later
1163** transitions leaving the lock state different from what it started but
1164** still short of its goal. The following chart shows the allowed
1165** transitions and the inserted intermediate states:
1166**
1167** UNLOCKED -> SHARED
1168** SHARED -> RESERVED
1169** SHARED -> (PENDING) -> EXCLUSIVE
1170** RESERVED -> (PENDING) -> EXCLUSIVE
1171** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001172**
drha6abd042004-06-09 17:37:22 +00001173** This routine will only increase a lock. Use the sqlite3OsUnlock()
1174** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001175*/
drh308c2a52010-05-14 11:30:18 +00001176static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001177 /* The following describes the implementation of the various locks and
1178 ** lock transitions in terms of the POSIX advisory shared and exclusive
1179 ** lock primitives (called read-locks and write-locks below, to avoid
1180 ** confusion with SQLite lock names). The algorithms are complicated
1181 ** slightly in order to be compatible with windows systems simultaneously
1182 ** accessing the same database file, in case that is ever required.
1183 **
1184 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1185 ** byte', each single bytes at well known offsets, and the 'shared byte
1186 ** range', a range of 510 bytes at a well known offset.
1187 **
1188 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1189 ** byte'. If this is successful, a random byte from the 'shared byte
1190 ** range' is read-locked and the lock on the 'pending byte' released.
1191 **
danielk197790ba3bd2004-06-25 08:32:25 +00001192 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1193 ** A RESERVED lock is implemented by grabbing a write-lock on the
1194 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001195 **
1196 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001197 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1198 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1199 ** obtained, but existing SHARED locks are allowed to persist. A process
1200 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1201 ** This property is used by the algorithm for rolling back a journal file
1202 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001203 **
danielk197790ba3bd2004-06-25 08:32:25 +00001204 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1205 ** implemented by obtaining a write-lock on the entire 'shared byte
1206 ** range'. Since all other locks require a read-lock on one of the bytes
1207 ** within this range, this ensures that no other locks are held on the
1208 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001209 **
1210 ** The reason a single byte cannot be used instead of the 'shared byte
1211 ** range' is that some versions of windows do not support read-locks. By
1212 ** locking a random byte from a range, concurrent SHARED locks may exist
1213 ** even if the locking primitive used is always a write-lock.
1214 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001215 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001216 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001217 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001218 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001219 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001220 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001221
drh054889e2005-11-30 03:20:31 +00001222 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001223 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1224 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001225 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001226
1227 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001228 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001229 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001230 */
drh308c2a52010-05-14 11:30:18 +00001231 if( pFile->eFileLock>=eFileLock ){
1232 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1233 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001234 return SQLITE_OK;
1235 }
1236
drh0c2694b2009-09-03 16:23:44 +00001237 /* Make sure the locking sequence is correct.
1238 ** (1) We never move from unlocked to anything higher than shared lock.
1239 ** (2) SQLite never explicitly requests a pendig lock.
1240 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001241 */
drh308c2a52010-05-14 11:30:18 +00001242 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1243 assert( eFileLock!=PENDING_LOCK );
1244 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001245
drh8af6c222010-05-14 12:43:01 +00001246 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001247 */
drh6c7d5c52008-11-21 20:32:33 +00001248 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001249 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001250
danielk1977ad94b582007-08-20 06:44:22 +00001251 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001252 ** handle that precludes the requested lock, return BUSY.
1253 */
drh8af6c222010-05-14 12:43:01 +00001254 if( (pFile->eFileLock!=pInode->eFileLock &&
1255 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001256 ){
1257 rc = SQLITE_BUSY;
1258 goto end_lock;
1259 }
1260
1261 /* If a SHARED lock is requested, and some thread using this PID already
1262 ** has a SHARED or RESERVED lock, then increment reference counts and
1263 ** return SQLITE_OK.
1264 */
drh308c2a52010-05-14 11:30:18 +00001265 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001266 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001267 assert( eFileLock==SHARED_LOCK );
1268 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001269 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001270 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001271 pInode->nShared++;
1272 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001273 goto end_lock;
1274 }
1275
danielk19779a1d0ab2004-06-01 14:09:28 +00001276
drh3cde3bb2004-06-12 02:17:14 +00001277 /* A PENDING lock is needed before acquiring a SHARED lock and before
1278 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1279 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001280 */
drh0c2694b2009-09-03 16:23:44 +00001281 lock.l_len = 1L;
1282 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001283 if( eFileLock==SHARED_LOCK
1284 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001285 ){
drh308c2a52010-05-14 11:30:18 +00001286 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001287 lock.l_start = PENDING_BYTE;
drh99ab3b12011-03-02 15:09:07 +00001288 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001289 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001290 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001291 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1292 if( IS_LOCK_ERROR(rc) ){
1293 pFile->lastErrno = tErrno;
1294 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 goto end_lock;
1296 }
drh3cde3bb2004-06-12 02:17:14 +00001297 }
1298
1299
1300 /* If control gets to this point, then actually go ahead and make
1301 ** operating system calls for the specified lock.
1302 */
drh308c2a52010-05-14 11:30:18 +00001303 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001304 assert( pInode->nShared==0 );
1305 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001306
drh2ac3ee92004-06-07 16:27:46 +00001307 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001308 lock.l_start = SHARED_FIRST;
1309 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001310 if( (s = osFcntl(pFile->h, F_SETLK, &lock))==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001311 tErrno = errno;
1312 }
drh2ac3ee92004-06-07 16:27:46 +00001313 /* Drop the temporary PENDING lock */
1314 lock.l_start = PENDING_BYTE;
1315 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 lock.l_type = F_UNLCK;
drh99ab3b12011-03-02 15:09:07 +00001317 if( osFcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001318 if( s != -1 ){
1319 /* This could happen with a network mount */
1320 tErrno = errno;
1321 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1322 if( IS_LOCK_ERROR(rc) ){
1323 pFile->lastErrno = tErrno;
1324 }
1325 goto end_lock;
1326 }
drh2b4b5962005-06-15 17:47:55 +00001327 }
drhe2396a12007-03-29 20:19:58 +00001328 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001329 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1330 if( IS_LOCK_ERROR(rc) ){
1331 pFile->lastErrno = tErrno;
1332 }
drhbbd42a62004-05-22 17:41:58 +00001333 }else{
drh308c2a52010-05-14 11:30:18 +00001334 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001335 pInode->nLock++;
1336 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001337 }
drh8af6c222010-05-14 12:43:01 +00001338 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001339 /* We are trying for an exclusive lock but another thread in this
1340 ** same process is still holding a shared lock. */
1341 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001342 }else{
drh3cde3bb2004-06-12 02:17:14 +00001343 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001344 ** assumed that there is a SHARED or greater lock on the file
1345 ** already.
1346 */
drh308c2a52010-05-14 11:30:18 +00001347 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001348 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001349 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001351 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001352 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001353 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001354 lock.l_start = SHARED_FIRST;
1355 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001356 break;
1357 default:
1358 assert(0);
1359 }
drh99ab3b12011-03-02 15:09:07 +00001360 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001361 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001362 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001363 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1364 if( IS_LOCK_ERROR(rc) ){
1365 pFile->lastErrno = tErrno;
1366 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001367 }
drhbbd42a62004-05-22 17:41:58 +00001368 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001369
drh8f941bc2009-01-14 23:03:40 +00001370
1371#ifndef NDEBUG
1372 /* Set up the transaction-counter change checking flags when
1373 ** transitioning from a SHARED to a RESERVED lock. The change
1374 ** from SHARED to RESERVED marks the beginning of a normal
1375 ** write operation (not a hot journal rollback).
1376 */
1377 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001378 && pFile->eFileLock<=SHARED_LOCK
1379 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001380 ){
1381 pFile->transCntrChng = 0;
1382 pFile->dbUpdate = 0;
1383 pFile->inNormalWrite = 1;
1384 }
1385#endif
1386
1387
danielk1977ecb2a962004-06-02 06:30:16 +00001388 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001389 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001390 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001391 }else if( eFileLock==EXCLUSIVE_LOCK ){
1392 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001393 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001394 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001395
1396end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001397 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001398 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1399 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001400 return rc;
1401}
1402
1403/*
dan08da86a2009-08-21 17:18:03 +00001404** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001405** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001406*/
1407static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001408 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001409 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001410 p->pNext = pInode->pUnused;
1411 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001412 pFile->h = -1;
1413 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001414}
1415
1416/*
drh308c2a52010-05-14 11:30:18 +00001417** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001418** must be either NO_LOCK or SHARED_LOCK.
1419**
1420** If the locking level of the file descriptor is already at or below
1421** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001422**
1423** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1424** the byte range is divided into 2 parts and the first part is unlocked then
1425** set to a read lock, then the other part is simply unlocked. This works
1426** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1427** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001428*/
drh308c2a52010-05-14 11:30:18 +00001429static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001430 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001431 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001432 struct flock lock;
1433 int rc = SQLITE_OK;
1434 int h;
drh0c2694b2009-09-03 16:23:44 +00001435 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001436
drh054889e2005-11-30 03:20:31 +00001437 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001438 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001439 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001440 getpid()));
drha6abd042004-06-09 17:37:22 +00001441
drh308c2a52010-05-14 11:30:18 +00001442 assert( eFileLock<=SHARED_LOCK );
1443 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001444 return SQLITE_OK;
1445 }
drh6c7d5c52008-11-21 20:32:33 +00001446 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001447 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001448 pInode = pFile->pInode;
1449 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001450 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001451 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001452 SimulateIOErrorBenign(1);
1453 SimulateIOError( h=(-1) )
1454 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001455
1456#ifndef NDEBUG
1457 /* When reducing a lock such that other processes can start
1458 ** reading the database file again, make sure that the
1459 ** transaction counter was updated if any part of the database
1460 ** file changed. If the transaction counter is not updated,
1461 ** other connections to the same file might not realize that
1462 ** the file has changed and hence might not know to flush their
1463 ** cache. The use of a stale cache can lead to database corruption.
1464 */
dan7c246102010-04-12 19:00:29 +00001465#if 0
drh8f941bc2009-01-14 23:03:40 +00001466 assert( pFile->inNormalWrite==0
1467 || pFile->dbUpdate==0
1468 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001469#endif
drh8f941bc2009-01-14 23:03:40 +00001470 pFile->inNormalWrite = 0;
1471#endif
1472
drh7ed97b92010-01-20 13:07:21 +00001473 /* downgrading to a shared lock on NFS involves clearing the write lock
1474 ** before establishing the readlock - to avoid a race condition we downgrade
1475 ** the lock in 2 blocks, so that part of the range will be covered by a
1476 ** write lock until the rest is covered by a read lock:
1477 ** 1: [WWWWW]
1478 ** 2: [....W]
1479 ** 3: [RRRRW]
1480 ** 4: [RRRR.]
1481 */
drh308c2a52010-05-14 11:30:18 +00001482 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001483
1484#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1485 assert( handleNFSUnlock==0 );
1486#endif
1487#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001488 if( handleNFSUnlock ){
1489 off_t divSize = SHARED_SIZE - 1;
1490
1491 lock.l_type = F_UNLCK;
1492 lock.l_whence = SEEK_SET;
1493 lock.l_start = SHARED_FIRST;
1494 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001495 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001496 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001497 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1498 if( IS_LOCK_ERROR(rc) ){
1499 pFile->lastErrno = tErrno;
1500 }
1501 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001502 }
drh7ed97b92010-01-20 13:07:21 +00001503 lock.l_type = F_RDLCK;
1504 lock.l_whence = SEEK_SET;
1505 lock.l_start = SHARED_FIRST;
1506 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001507 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001508 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001509 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1510 if( IS_LOCK_ERROR(rc) ){
1511 pFile->lastErrno = tErrno;
1512 }
1513 goto end_unlock;
1514 }
1515 lock.l_type = F_UNLCK;
1516 lock.l_whence = SEEK_SET;
1517 lock.l_start = SHARED_FIRST+divSize;
1518 lock.l_len = SHARED_SIZE-divSize;
drh99ab3b12011-03-02 15:09:07 +00001519 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001520 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001521 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1522 if( IS_LOCK_ERROR(rc) ){
1523 pFile->lastErrno = tErrno;
1524 }
1525 goto end_unlock;
1526 }
drh30f776f2011-02-25 03:25:07 +00001527 }else
1528#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1529 {
drh7ed97b92010-01-20 13:07:21 +00001530 lock.l_type = F_RDLCK;
1531 lock.l_whence = SEEK_SET;
1532 lock.l_start = SHARED_FIRST;
1533 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001534 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001535 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001536 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1537 if( IS_LOCK_ERROR(rc) ){
1538 pFile->lastErrno = tErrno;
1539 }
1540 goto end_unlock;
1541 }
drh9c105bb2004-10-02 20:38:28 +00001542 }
1543 }
drhbbd42a62004-05-22 17:41:58 +00001544 lock.l_type = F_UNLCK;
1545 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001546 lock.l_start = PENDING_BYTE;
1547 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh99ab3b12011-03-02 15:09:07 +00001548 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001549 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001550 }else{
drh0c2694b2009-09-03 16:23:44 +00001551 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001552 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1553 if( IS_LOCK_ERROR(rc) ){
1554 pFile->lastErrno = tErrno;
1555 }
drhcd731cf2009-03-28 23:23:02 +00001556 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001557 }
drhbbd42a62004-05-22 17:41:58 +00001558 }
drh308c2a52010-05-14 11:30:18 +00001559 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001560 /* Decrement the shared lock counter. Release the lock using an
1561 ** OS call only when all threads in this same process have released
1562 ** the lock.
1563 */
drh8af6c222010-05-14 12:43:01 +00001564 pInode->nShared--;
1565 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001566 lock.l_type = F_UNLCK;
1567 lock.l_whence = SEEK_SET;
1568 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001569 SimulateIOErrorBenign(1);
1570 SimulateIOError( h=(-1) )
1571 SimulateIOErrorBenign(0);
drh99ab3b12011-03-02 15:09:07 +00001572 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001573 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001574 }else{
drh0c2694b2009-09-03 16:23:44 +00001575 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001576 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001577 if( IS_LOCK_ERROR(rc) ){
1578 pFile->lastErrno = tErrno;
1579 }
drh8af6c222010-05-14 12:43:01 +00001580 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001581 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001582 }
drha6abd042004-06-09 17:37:22 +00001583 }
1584
drhbbd42a62004-05-22 17:41:58 +00001585 /* Decrement the count of locks against this same file. When the
1586 ** count reaches zero, close any other file descriptors whose close
1587 ** was deferred because of outstanding locks.
1588 */
drh8af6c222010-05-14 12:43:01 +00001589 pInode->nLock--;
1590 assert( pInode->nLock>=0 );
1591 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001592 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001593 }
1594 }
aswift5b1a2562008-08-22 00:22:35 +00001595
1596end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001597 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001598 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001599 return rc;
drhbbd42a62004-05-22 17:41:58 +00001600}
1601
1602/*
drh308c2a52010-05-14 11:30:18 +00001603** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001604** must be either NO_LOCK or SHARED_LOCK.
1605**
1606** If the locking level of the file descriptor is already at or below
1607** the requested locking level, this routine is a no-op.
1608*/
drh308c2a52010-05-14 11:30:18 +00001609static int unixUnlock(sqlite3_file *id, int eFileLock){
1610 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001611}
1612
1613/*
danielk1977e339d652008-06-28 11:23:00 +00001614** This function performs the parts of the "close file" operation
1615** common to all locking schemes. It closes the directory and file
1616** handles, if they are valid, and sets all fields of the unixFile
1617** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001618**
1619** It is *not* necessary to hold the mutex when this routine is called,
1620** even on VxWorks. A mutex will be acquired on VxWorks by the
1621** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001622*/
1623static int closeUnixFile(sqlite3_file *id){
1624 unixFile *pFile = (unixFile*)id;
1625 if( pFile ){
1626 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001627 robust_close(pFile, pFile->dirfd, __LINE__);
1628 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001629 }
1630 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001631 robust_close(pFile, pFile->h, __LINE__);
1632 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001633 }
drh6c7d5c52008-11-21 20:32:33 +00001634#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001635 if( pFile->pId ){
1636 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001637 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001638 }
drh107886a2008-11-21 22:21:50 +00001639 vxworksReleaseFileId(pFile->pId);
1640 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001641 }
1642#endif
drhff59a112010-05-14 20:15:51 +00001643 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001644 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001645 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001646 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001647 }
1648 return SQLITE_OK;
1649}
1650
1651/*
danielk1977e3026632004-06-22 11:29:02 +00001652** Close a file.
1653*/
danielk197762079062007-08-15 17:08:46 +00001654static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001655 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001656 if( id ){
1657 unixFile *pFile = (unixFile *)id;
1658 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001659 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001660 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001661 /* If there are outstanding locks, do not actually close the file just
1662 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001663 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001664 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001665 */
dan08da86a2009-08-21 17:18:03 +00001666 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001667 }
danb0ac3e32010-06-16 10:55:42 +00001668 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001669 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001670 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001671 }
aswiftaebf4132008-11-21 00:10:35 +00001672 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001673}
1674
drh734c9862008-11-28 15:37:20 +00001675/************** End of the posix advisory lock implementation *****************
1676******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001677
drh734c9862008-11-28 15:37:20 +00001678/******************************************************************************
1679****************************** No-op Locking **********************************
1680**
1681** Of the various locking implementations available, this is by far the
1682** simplest: locking is ignored. No attempt is made to lock the database
1683** file for reading or writing.
1684**
1685** This locking mode is appropriate for use on read-only databases
1686** (ex: databases that are burned into CD-ROM, for example.) It can
1687** also be used if the application employs some external mechanism to
1688** prevent simultaneous access of the same database by two or more
1689** database connections. But there is a serious risk of database
1690** corruption if this locking mode is used in situations where multiple
1691** database connections are accessing the same database file at the same
1692** time and one or more of those connections are writing.
1693*/
drhbfe66312006-10-03 17:40:40 +00001694
drh734c9862008-11-28 15:37:20 +00001695static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1696 UNUSED_PARAMETER(NotUsed);
1697 *pResOut = 0;
1698 return SQLITE_OK;
1699}
drh734c9862008-11-28 15:37:20 +00001700static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1701 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1702 return SQLITE_OK;
1703}
drh734c9862008-11-28 15:37:20 +00001704static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1705 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1706 return SQLITE_OK;
1707}
1708
1709/*
drh9b35ea62008-11-29 02:20:26 +00001710** Close the file.
drh734c9862008-11-28 15:37:20 +00001711*/
1712static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001713 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001714}
1715
1716/******************* End of the no-op lock implementation *********************
1717******************************************************************************/
1718
1719/******************************************************************************
1720************************* Begin dot-file Locking ******************************
1721**
drh0c2694b2009-09-03 16:23:44 +00001722** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001723** files in order to control access to the database. This works on just
1724** about every filesystem imaginable. But there are serious downsides:
1725**
1726** (1) There is zero concurrency. A single reader blocks all other
1727** connections from reading or writing the database.
1728**
1729** (2) An application crash or power loss can leave stale lock files
1730** sitting around that need to be cleared manually.
1731**
1732** Nevertheless, a dotlock is an appropriate locking mode for use if no
1733** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001734**
1735** Dotfile locking works by creating a file in the same directory as the
1736** database and with the same name but with a ".lock" extension added.
1737** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1738** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001739*/
1740
1741/*
1742** The file suffix added to the data base filename in order to create the
1743** lock file.
1744*/
1745#define DOTLOCK_SUFFIX ".lock"
1746
drh7708e972008-11-29 00:56:52 +00001747/*
1748** This routine checks if there is a RESERVED lock held on the specified
1749** file by this or any other process. If such a lock is held, set *pResOut
1750** to a non-zero value otherwise *pResOut is set to zero. The return value
1751** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1752**
1753** In dotfile locking, either a lock exists or it does not. So in this
1754** variation of CheckReservedLock(), *pResOut is set to true if any lock
1755** is held on the file and false if the file is unlocked.
1756*/
drh734c9862008-11-28 15:37:20 +00001757static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1758 int rc = SQLITE_OK;
1759 int reserved = 0;
1760 unixFile *pFile = (unixFile*)id;
1761
1762 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1763
1764 assert( pFile );
1765
1766 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001767 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001768 /* Either this connection or some other connection in the same process
1769 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001770 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001771 }else{
1772 /* The lock is held if and only if the lockfile exists */
1773 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001774 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001775 }
drh308c2a52010-05-14 11:30:18 +00001776 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001777 *pResOut = reserved;
1778 return rc;
1779}
1780
drh7708e972008-11-29 00:56:52 +00001781/*
drh308c2a52010-05-14 11:30:18 +00001782** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001783** of the following:
1784**
1785** (1) SHARED_LOCK
1786** (2) RESERVED_LOCK
1787** (3) PENDING_LOCK
1788** (4) EXCLUSIVE_LOCK
1789**
1790** Sometimes when requesting one lock state, additional lock states
1791** are inserted in between. The locking might fail on one of the later
1792** transitions leaving the lock state different from what it started but
1793** still short of its goal. The following chart shows the allowed
1794** transitions and the inserted intermediate states:
1795**
1796** UNLOCKED -> SHARED
1797** SHARED -> RESERVED
1798** SHARED -> (PENDING) -> EXCLUSIVE
1799** RESERVED -> (PENDING) -> EXCLUSIVE
1800** PENDING -> EXCLUSIVE
1801**
1802** This routine will only increase a lock. Use the sqlite3OsUnlock()
1803** routine to lower a locking level.
1804**
1805** With dotfile locking, we really only support state (4): EXCLUSIVE.
1806** But we track the other locking levels internally.
1807*/
drh308c2a52010-05-14 11:30:18 +00001808static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001809 unixFile *pFile = (unixFile*)id;
1810 int fd;
1811 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001812 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001813
drh7708e972008-11-29 00:56:52 +00001814
1815 /* If we have any lock, then the lock file already exists. All we have
1816 ** to do is adjust our internal record of the lock level.
1817 */
drh308c2a52010-05-14 11:30:18 +00001818 if( pFile->eFileLock > NO_LOCK ){
1819 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001820#if !OS_VXWORKS
1821 /* Always update the timestamp on the old file */
1822 utimes(zLockFile, NULL);
1823#endif
drh7708e972008-11-29 00:56:52 +00001824 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001825 }
1826
1827 /* grab an exclusive lock */
drh99ab3b12011-03-02 15:09:07 +00001828 fd = osOpen(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001829 if( fd<0 ){
1830 /* failed to open/create the file, someone else may have stolen the lock */
1831 int tErrno = errno;
1832 if( EEXIST == tErrno ){
1833 rc = SQLITE_BUSY;
1834 } else {
1835 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1836 if( IS_LOCK_ERROR(rc) ){
1837 pFile->lastErrno = tErrno;
1838 }
1839 }
drh7708e972008-11-29 00:56:52 +00001840 return rc;
drh734c9862008-11-28 15:37:20 +00001841 }
drh0e9365c2011-03-02 02:08:13 +00001842 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001843
1844 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001845 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001846 return rc;
1847}
1848
drh7708e972008-11-29 00:56:52 +00001849/*
drh308c2a52010-05-14 11:30:18 +00001850** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001851** must be either NO_LOCK or SHARED_LOCK.
1852**
1853** If the locking level of the file descriptor is already at or below
1854** the requested locking level, this routine is a no-op.
1855**
1856** When the locking level reaches NO_LOCK, delete the lock file.
1857*/
drh308c2a52010-05-14 11:30:18 +00001858static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001859 unixFile *pFile = (unixFile*)id;
1860 char *zLockFile = (char *)pFile->lockingContext;
1861
1862 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001863 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1864 pFile->eFileLock, getpid()));
1865 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001866
1867 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001868 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001869 return SQLITE_OK;
1870 }
drh7708e972008-11-29 00:56:52 +00001871
1872 /* To downgrade to shared, simply update our internal notion of the
1873 ** lock state. No need to mess with the file on disk.
1874 */
drh308c2a52010-05-14 11:30:18 +00001875 if( eFileLock==SHARED_LOCK ){
1876 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001877 return SQLITE_OK;
1878 }
1879
drh7708e972008-11-29 00:56:52 +00001880 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001881 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001882 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001883 int rc = 0;
1884 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001885 if( ENOENT != tErrno ){
1886 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1887 }
1888 if( IS_LOCK_ERROR(rc) ){
1889 pFile->lastErrno = tErrno;
1890 }
1891 return rc;
1892 }
drh308c2a52010-05-14 11:30:18 +00001893 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001894 return SQLITE_OK;
1895}
1896
1897/*
drh9b35ea62008-11-29 02:20:26 +00001898** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001899*/
1900static int dotlockClose(sqlite3_file *id) {
1901 int rc;
1902 if( id ){
1903 unixFile *pFile = (unixFile*)id;
1904 dotlockUnlock(id, NO_LOCK);
1905 sqlite3_free(pFile->lockingContext);
1906 }
drh734c9862008-11-28 15:37:20 +00001907 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001908 return rc;
1909}
1910/****************** End of the dot-file lock implementation *******************
1911******************************************************************************/
1912
1913/******************************************************************************
1914************************** Begin flock Locking ********************************
1915**
1916** Use the flock() system call to do file locking.
1917**
drh6b9d6dd2008-12-03 19:34:47 +00001918** flock() locking is like dot-file locking in that the various
1919** fine-grain locking levels supported by SQLite are collapsed into
1920** a single exclusive lock. In other words, SHARED, RESERVED, and
1921** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1922** still works when you do this, but concurrency is reduced since
1923** only a single process can be reading the database at a time.
1924**
drh734c9862008-11-28 15:37:20 +00001925** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1926** compiling for VXWORKS.
1927*/
1928#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001929
drh6b9d6dd2008-12-03 19:34:47 +00001930/*
drhff812312011-02-23 13:33:46 +00001931** Retry flock() calls that fail with EINTR
1932*/
1933#ifdef EINTR
1934static int robust_flock(int fd, int op){
1935 int rc;
1936 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
1937 return rc;
1938}
1939#else
drh5c819272011-02-23 14:00:12 +00001940# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00001941#endif
1942
1943
1944/*
drh6b9d6dd2008-12-03 19:34:47 +00001945** This routine checks if there is a RESERVED lock held on the specified
1946** file by this or any other process. If such a lock is held, set *pResOut
1947** to a non-zero value otherwise *pResOut is set to zero. The return value
1948** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1949*/
drh734c9862008-11-28 15:37:20 +00001950static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1951 int rc = SQLITE_OK;
1952 int reserved = 0;
1953 unixFile *pFile = (unixFile*)id;
1954
1955 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1956
1957 assert( pFile );
1958
1959 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001960 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001961 reserved = 1;
1962 }
1963
1964 /* Otherwise see if some other process holds it. */
1965 if( !reserved ){
1966 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00001967 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00001968 if( !lrc ){
1969 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00001970 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00001971 if ( lrc ) {
1972 int tErrno = errno;
1973 /* unlock failed with an error */
1974 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1975 if( IS_LOCK_ERROR(lrc) ){
1976 pFile->lastErrno = tErrno;
1977 rc = lrc;
1978 }
1979 }
1980 } else {
1981 int tErrno = errno;
1982 reserved = 1;
1983 /* someone else might have it reserved */
1984 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1985 if( IS_LOCK_ERROR(lrc) ){
1986 pFile->lastErrno = tErrno;
1987 rc = lrc;
1988 }
1989 }
1990 }
drh308c2a52010-05-14 11:30:18 +00001991 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001992
1993#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1994 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1995 rc = SQLITE_OK;
1996 reserved=1;
1997 }
1998#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1999 *pResOut = reserved;
2000 return rc;
2001}
2002
drh6b9d6dd2008-12-03 19:34:47 +00002003/*
drh308c2a52010-05-14 11:30:18 +00002004** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002005** of the following:
2006**
2007** (1) SHARED_LOCK
2008** (2) RESERVED_LOCK
2009** (3) PENDING_LOCK
2010** (4) EXCLUSIVE_LOCK
2011**
2012** Sometimes when requesting one lock state, additional lock states
2013** are inserted in between. The locking might fail on one of the later
2014** transitions leaving the lock state different from what it started but
2015** still short of its goal. The following chart shows the allowed
2016** transitions and the inserted intermediate states:
2017**
2018** UNLOCKED -> SHARED
2019** SHARED -> RESERVED
2020** SHARED -> (PENDING) -> EXCLUSIVE
2021** RESERVED -> (PENDING) -> EXCLUSIVE
2022** PENDING -> EXCLUSIVE
2023**
2024** flock() only really support EXCLUSIVE locks. We track intermediate
2025** lock states in the sqlite3_file structure, but all locks SHARED or
2026** above are really EXCLUSIVE locks and exclude all other processes from
2027** access the file.
2028**
2029** This routine will only increase a lock. Use the sqlite3OsUnlock()
2030** routine to lower a locking level.
2031*/
drh308c2a52010-05-14 11:30:18 +00002032static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002033 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002034 unixFile *pFile = (unixFile*)id;
2035
2036 assert( pFile );
2037
2038 /* if we already have a lock, it is exclusive.
2039 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002040 if (pFile->eFileLock > NO_LOCK) {
2041 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002042 return SQLITE_OK;
2043 }
2044
2045 /* grab an exclusive lock */
2046
drhff812312011-02-23 13:33:46 +00002047 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002048 int tErrno = errno;
2049 /* didn't get, must be busy */
2050 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2051 if( IS_LOCK_ERROR(rc) ){
2052 pFile->lastErrno = tErrno;
2053 }
2054 } else {
2055 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002056 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002057 }
drh308c2a52010-05-14 11:30:18 +00002058 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2059 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002060#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2061 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2062 rc = SQLITE_BUSY;
2063 }
2064#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2065 return rc;
2066}
2067
drh6b9d6dd2008-12-03 19:34:47 +00002068
2069/*
drh308c2a52010-05-14 11:30:18 +00002070** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002071** must be either NO_LOCK or SHARED_LOCK.
2072**
2073** If the locking level of the file descriptor is already at or below
2074** the requested locking level, this routine is a no-op.
2075*/
drh308c2a52010-05-14 11:30:18 +00002076static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002077 unixFile *pFile = (unixFile*)id;
2078
2079 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002080 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2081 pFile->eFileLock, getpid()));
2082 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002083
2084 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002085 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002086 return SQLITE_OK;
2087 }
2088
2089 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002090 if (eFileLock==SHARED_LOCK) {
2091 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002092 return SQLITE_OK;
2093 }
2094
2095 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002096 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002097 if (rc) {
2098 int r, tErrno = errno;
2099 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2100 if( IS_LOCK_ERROR(r) ){
2101 pFile->lastErrno = tErrno;
2102 }
2103#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2104 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2105 r = SQLITE_BUSY;
2106 }
2107#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2108
2109 return r;
2110 } else {
drh308c2a52010-05-14 11:30:18 +00002111 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002112 return SQLITE_OK;
2113 }
2114}
2115
2116/*
2117** Close a file.
2118*/
2119static int flockClose(sqlite3_file *id) {
2120 if( id ){
2121 flockUnlock(id, NO_LOCK);
2122 }
2123 return closeUnixFile(id);
2124}
2125
2126#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2127
2128/******************* End of the flock lock implementation *********************
2129******************************************************************************/
2130
2131/******************************************************************************
2132************************ Begin Named Semaphore Locking ************************
2133**
2134** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002135**
2136** Semaphore locking is like dot-lock and flock in that it really only
2137** supports EXCLUSIVE locking. Only a single process can read or write
2138** the database file at a time. This reduces potential concurrency, but
2139** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002140*/
2141#if OS_VXWORKS
2142
drh6b9d6dd2008-12-03 19:34:47 +00002143/*
2144** This routine checks if there is a RESERVED lock held on the specified
2145** file by this or any other process. If such a lock is held, set *pResOut
2146** to a non-zero value otherwise *pResOut is set to zero. The return value
2147** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2148*/
drh734c9862008-11-28 15:37:20 +00002149static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2150 int rc = SQLITE_OK;
2151 int reserved = 0;
2152 unixFile *pFile = (unixFile*)id;
2153
2154 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2155
2156 assert( pFile );
2157
2158 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002159 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002160 reserved = 1;
2161 }
2162
2163 /* Otherwise see if some other process holds it. */
2164 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002165 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002166 struct stat statBuf;
2167
2168 if( sem_trywait(pSem)==-1 ){
2169 int tErrno = errno;
2170 if( EAGAIN != tErrno ){
2171 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2172 pFile->lastErrno = tErrno;
2173 } else {
2174 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002175 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002176 }
2177 }else{
2178 /* we could have it if we want it */
2179 sem_post(pSem);
2180 }
2181 }
drh308c2a52010-05-14 11:30:18 +00002182 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002183
2184 *pResOut = reserved;
2185 return rc;
2186}
2187
drh6b9d6dd2008-12-03 19:34:47 +00002188/*
drh308c2a52010-05-14 11:30:18 +00002189** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002190** of the following:
2191**
2192** (1) SHARED_LOCK
2193** (2) RESERVED_LOCK
2194** (3) PENDING_LOCK
2195** (4) EXCLUSIVE_LOCK
2196**
2197** Sometimes when requesting one lock state, additional lock states
2198** are inserted in between. The locking might fail on one of the later
2199** transitions leaving the lock state different from what it started but
2200** still short of its goal. The following chart shows the allowed
2201** transitions and the inserted intermediate states:
2202**
2203** UNLOCKED -> SHARED
2204** SHARED -> RESERVED
2205** SHARED -> (PENDING) -> EXCLUSIVE
2206** RESERVED -> (PENDING) -> EXCLUSIVE
2207** PENDING -> EXCLUSIVE
2208**
2209** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2210** lock states in the sqlite3_file structure, but all locks SHARED or
2211** above are really EXCLUSIVE locks and exclude all other processes from
2212** access the file.
2213**
2214** This routine will only increase a lock. Use the sqlite3OsUnlock()
2215** routine to lower a locking level.
2216*/
drh308c2a52010-05-14 11:30:18 +00002217static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002218 unixFile *pFile = (unixFile*)id;
2219 int fd;
drh8af6c222010-05-14 12:43:01 +00002220 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002221 int rc = SQLITE_OK;
2222
2223 /* if we already have a lock, it is exclusive.
2224 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002225 if (pFile->eFileLock > NO_LOCK) {
2226 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002227 rc = SQLITE_OK;
2228 goto sem_end_lock;
2229 }
2230
2231 /* lock semaphore now but bail out when already locked. */
2232 if( sem_trywait(pSem)==-1 ){
2233 rc = SQLITE_BUSY;
2234 goto sem_end_lock;
2235 }
2236
2237 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002238 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002239
2240 sem_end_lock:
2241 return rc;
2242}
2243
drh6b9d6dd2008-12-03 19:34:47 +00002244/*
drh308c2a52010-05-14 11:30:18 +00002245** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002246** must be either NO_LOCK or SHARED_LOCK.
2247**
2248** If the locking level of the file descriptor is already at or below
2249** the requested locking level, this routine is a no-op.
2250*/
drh308c2a52010-05-14 11:30:18 +00002251static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002252 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002253 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002254
2255 assert( pFile );
2256 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002257 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2258 pFile->eFileLock, getpid()));
2259 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002260
2261 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002262 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002263 return SQLITE_OK;
2264 }
2265
2266 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002267 if (eFileLock==SHARED_LOCK) {
2268 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002269 return SQLITE_OK;
2270 }
2271
2272 /* no, really unlock. */
2273 if ( sem_post(pSem)==-1 ) {
2274 int rc, tErrno = errno;
2275 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2276 if( IS_LOCK_ERROR(rc) ){
2277 pFile->lastErrno = tErrno;
2278 }
2279 return rc;
2280 }
drh308c2a52010-05-14 11:30:18 +00002281 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002282 return SQLITE_OK;
2283}
2284
2285/*
2286 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002287 */
drh734c9862008-11-28 15:37:20 +00002288static int semClose(sqlite3_file *id) {
2289 if( id ){
2290 unixFile *pFile = (unixFile*)id;
2291 semUnlock(id, NO_LOCK);
2292 assert( pFile );
2293 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002294 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002295 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002296 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002297 }
2298 return SQLITE_OK;
2299}
2300
2301#endif /* OS_VXWORKS */
2302/*
2303** Named semaphore locking is only available on VxWorks.
2304**
2305*************** End of the named semaphore lock implementation ****************
2306******************************************************************************/
2307
2308
2309/******************************************************************************
2310*************************** Begin AFP Locking *********************************
2311**
2312** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2313** on Apple Macintosh computers - both OS9 and OSX.
2314**
2315** Third-party implementations of AFP are available. But this code here
2316** only works on OSX.
2317*/
2318
drhd2cb50b2009-01-09 21:41:17 +00002319#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002320/*
2321** The afpLockingContext structure contains all afp lock specific state
2322*/
drhbfe66312006-10-03 17:40:40 +00002323typedef struct afpLockingContext afpLockingContext;
2324struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002325 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002326 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002327};
2328
2329struct ByteRangeLockPB2
2330{
2331 unsigned long long offset; /* offset to first byte to lock */
2332 unsigned long long length; /* nbr of bytes to lock */
2333 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2334 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2335 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2336 int fd; /* file desc to assoc this lock with */
2337};
2338
drhfd131da2007-08-07 17:13:03 +00002339#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002340
drh6b9d6dd2008-12-03 19:34:47 +00002341/*
2342** This is a utility for setting or clearing a bit-range lock on an
2343** AFP filesystem.
2344**
2345** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2346*/
2347static int afpSetLock(
2348 const char *path, /* Name of the file to be locked or unlocked */
2349 unixFile *pFile, /* Open file descriptor on path */
2350 unsigned long long offset, /* First byte to be locked */
2351 unsigned long long length, /* Number of bytes to lock */
2352 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002353){
drh6b9d6dd2008-12-03 19:34:47 +00002354 struct ByteRangeLockPB2 pb;
2355 int err;
drhbfe66312006-10-03 17:40:40 +00002356
2357 pb.unLockFlag = setLockFlag ? 0 : 1;
2358 pb.startEndFlag = 0;
2359 pb.offset = offset;
2360 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002361 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002362
drh308c2a52010-05-14 11:30:18 +00002363 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002364 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002365 offset, length));
drhbfe66312006-10-03 17:40:40 +00002366 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2367 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002368 int rc;
2369 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002370 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2371 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002372#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2373 rc = SQLITE_BUSY;
2374#else
drh734c9862008-11-28 15:37:20 +00002375 rc = sqliteErrorFromPosixError(tErrno,
2376 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002377#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002378 if( IS_LOCK_ERROR(rc) ){
2379 pFile->lastErrno = tErrno;
2380 }
2381 return rc;
drhbfe66312006-10-03 17:40:40 +00002382 } else {
aswift5b1a2562008-08-22 00:22:35 +00002383 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002384 }
2385}
2386
drh6b9d6dd2008-12-03 19:34:47 +00002387/*
2388** This routine checks if there is a RESERVED lock held on the specified
2389** file by this or any other process. If such a lock is held, set *pResOut
2390** to a non-zero value otherwise *pResOut is set to zero. The return value
2391** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2392*/
danielk1977e339d652008-06-28 11:23:00 +00002393static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002394 int rc = SQLITE_OK;
2395 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002396 unixFile *pFile = (unixFile*)id;
2397
aswift5b1a2562008-08-22 00:22:35 +00002398 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2399
2400 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002401 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002402 if( context->reserved ){
2403 *pResOut = 1;
2404 return SQLITE_OK;
2405 }
drh8af6c222010-05-14 12:43:01 +00002406 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002407
2408 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002409 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002410 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002411 }
2412
2413 /* Otherwise see if some other process holds it.
2414 */
aswift5b1a2562008-08-22 00:22:35 +00002415 if( !reserved ){
2416 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002417 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002418 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002419 /* if we succeeded in taking the reserved lock, unlock it to restore
2420 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002421 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002422 } else {
2423 /* if we failed to get the lock then someone else must have it */
2424 reserved = 1;
2425 }
2426 if( IS_LOCK_ERROR(lrc) ){
2427 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002428 }
2429 }
drhbfe66312006-10-03 17:40:40 +00002430
drh7ed97b92010-01-20 13:07:21 +00002431 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002432 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002433
2434 *pResOut = reserved;
2435 return rc;
drhbfe66312006-10-03 17:40:40 +00002436}
2437
drh6b9d6dd2008-12-03 19:34:47 +00002438/*
drh308c2a52010-05-14 11:30:18 +00002439** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002440** of the following:
2441**
2442** (1) SHARED_LOCK
2443** (2) RESERVED_LOCK
2444** (3) PENDING_LOCK
2445** (4) EXCLUSIVE_LOCK
2446**
2447** Sometimes when requesting one lock state, additional lock states
2448** are inserted in between. The locking might fail on one of the later
2449** transitions leaving the lock state different from what it started but
2450** still short of its goal. The following chart shows the allowed
2451** transitions and the inserted intermediate states:
2452**
2453** UNLOCKED -> SHARED
2454** SHARED -> RESERVED
2455** SHARED -> (PENDING) -> EXCLUSIVE
2456** RESERVED -> (PENDING) -> EXCLUSIVE
2457** PENDING -> EXCLUSIVE
2458**
2459** This routine will only increase a lock. Use the sqlite3OsUnlock()
2460** routine to lower a locking level.
2461*/
drh308c2a52010-05-14 11:30:18 +00002462static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002463 int rc = SQLITE_OK;
2464 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002465 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002466 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002467
2468 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002469 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2470 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002471 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002472
drhbfe66312006-10-03 17:40:40 +00002473 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002474 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002475 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002476 */
drh308c2a52010-05-14 11:30:18 +00002477 if( pFile->eFileLock>=eFileLock ){
2478 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2479 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002480 return SQLITE_OK;
2481 }
2482
2483 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002484 ** (1) We never move from unlocked to anything higher than shared lock.
2485 ** (2) SQLite never explicitly requests a pendig lock.
2486 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002487 */
drh308c2a52010-05-14 11:30:18 +00002488 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2489 assert( eFileLock!=PENDING_LOCK );
2490 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002491
drh8af6c222010-05-14 12:43:01 +00002492 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002493 */
drh6c7d5c52008-11-21 20:32:33 +00002494 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002495 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002496
2497 /* If some thread using this PID has a lock via a different unixFile*
2498 ** handle that precludes the requested lock, return BUSY.
2499 */
drh8af6c222010-05-14 12:43:01 +00002500 if( (pFile->eFileLock!=pInode->eFileLock &&
2501 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002502 ){
2503 rc = SQLITE_BUSY;
2504 goto afp_end_lock;
2505 }
2506
2507 /* If a SHARED lock is requested, and some thread using this PID already
2508 ** has a SHARED or RESERVED lock, then increment reference counts and
2509 ** return SQLITE_OK.
2510 */
drh308c2a52010-05-14 11:30:18 +00002511 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002512 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002513 assert( eFileLock==SHARED_LOCK );
2514 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002515 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002516 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002517 pInode->nShared++;
2518 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002519 goto afp_end_lock;
2520 }
drhbfe66312006-10-03 17:40:40 +00002521
2522 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002523 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2524 ** be released.
2525 */
drh308c2a52010-05-14 11:30:18 +00002526 if( eFileLock==SHARED_LOCK
2527 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002528 ){
2529 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002530 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002531 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002532 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002533 goto afp_end_lock;
2534 }
2535 }
2536
2537 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002538 ** operating system calls for the specified lock.
2539 */
drh308c2a52010-05-14 11:30:18 +00002540 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002541 int lrc1, lrc2, lrc1Errno;
2542 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002543
drh8af6c222010-05-14 12:43:01 +00002544 assert( pInode->nShared==0 );
2545 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002546
2547 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002548 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002549 /* note that the quality of the randomness doesn't matter that much */
2550 lk = random();
drh8af6c222010-05-14 12:43:01 +00002551 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002552 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002553 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002554 if( IS_LOCK_ERROR(lrc1) ){
2555 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002556 }
aswift5b1a2562008-08-22 00:22:35 +00002557 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002558 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002559
aswift5b1a2562008-08-22 00:22:35 +00002560 if( IS_LOCK_ERROR(lrc1) ) {
2561 pFile->lastErrno = lrc1Errno;
2562 rc = lrc1;
2563 goto afp_end_lock;
2564 } else if( IS_LOCK_ERROR(lrc2) ){
2565 rc = lrc2;
2566 goto afp_end_lock;
2567 } else if( lrc1 != SQLITE_OK ) {
2568 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002569 } else {
drh308c2a52010-05-14 11:30:18 +00002570 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002571 pInode->nLock++;
2572 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002573 }
drh8af6c222010-05-14 12:43:01 +00002574 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002575 /* We are trying for an exclusive lock but another thread in this
2576 ** same process is still holding a shared lock. */
2577 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002578 }else{
2579 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2580 ** assumed that there is a SHARED or greater lock on the file
2581 ** already.
2582 */
2583 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002584 assert( 0!=pFile->eFileLock );
2585 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002586 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002587 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002588 if( !failed ){
2589 context->reserved = 1;
2590 }
drhbfe66312006-10-03 17:40:40 +00002591 }
drh308c2a52010-05-14 11:30:18 +00002592 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002593 /* Acquire an EXCLUSIVE lock */
2594
2595 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002596 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002597 */
drh6b9d6dd2008-12-03 19:34:47 +00002598 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002599 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002600 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002601 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002602 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002603 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002604 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002605 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002606 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2607 ** a critical I/O error
2608 */
2609 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2610 SQLITE_IOERR_LOCK;
2611 goto afp_end_lock;
2612 }
2613 }else{
aswift5b1a2562008-08-22 00:22:35 +00002614 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002615 }
2616 }
aswift5b1a2562008-08-22 00:22:35 +00002617 if( failed ){
2618 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002619 }
2620 }
2621
2622 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002623 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002624 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002625 }else if( eFileLock==EXCLUSIVE_LOCK ){
2626 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002627 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002628 }
2629
2630afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002631 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002632 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2633 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002634 return rc;
2635}
2636
2637/*
drh308c2a52010-05-14 11:30:18 +00002638** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002639** must be either NO_LOCK or SHARED_LOCK.
2640**
2641** If the locking level of the file descriptor is already at or below
2642** the requested locking level, this routine is a no-op.
2643*/
drh308c2a52010-05-14 11:30:18 +00002644static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002645 int rc = SQLITE_OK;
2646 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002647 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002648 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2649 int skipShared = 0;
2650#ifdef SQLITE_TEST
2651 int h = pFile->h;
2652#endif
drhbfe66312006-10-03 17:40:40 +00002653
2654 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002655 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002656 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002657 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002658
drh308c2a52010-05-14 11:30:18 +00002659 assert( eFileLock<=SHARED_LOCK );
2660 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002661 return SQLITE_OK;
2662 }
drh6c7d5c52008-11-21 20:32:33 +00002663 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002664 pInode = pFile->pInode;
2665 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002666 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002667 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002668 SimulateIOErrorBenign(1);
2669 SimulateIOError( h=(-1) )
2670 SimulateIOErrorBenign(0);
2671
2672#ifndef NDEBUG
2673 /* When reducing a lock such that other processes can start
2674 ** reading the database file again, make sure that the
2675 ** transaction counter was updated if any part of the database
2676 ** file changed. If the transaction counter is not updated,
2677 ** other connections to the same file might not realize that
2678 ** the file has changed and hence might not know to flush their
2679 ** cache. The use of a stale cache can lead to database corruption.
2680 */
2681 assert( pFile->inNormalWrite==0
2682 || pFile->dbUpdate==0
2683 || pFile->transCntrChng==1 );
2684 pFile->inNormalWrite = 0;
2685#endif
aswiftaebf4132008-11-21 00:10:35 +00002686
drh308c2a52010-05-14 11:30:18 +00002687 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002688 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002689 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002690 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002691 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002692 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2693 } else {
2694 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002695 }
2696 }
drh308c2a52010-05-14 11:30:18 +00002697 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002698 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002699 }
drh308c2a52010-05-14 11:30:18 +00002700 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002701 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2702 if( !rc ){
2703 context->reserved = 0;
2704 }
aswiftaebf4132008-11-21 00:10:35 +00002705 }
drh8af6c222010-05-14 12:43:01 +00002706 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2707 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002708 }
aswiftaebf4132008-11-21 00:10:35 +00002709 }
drh308c2a52010-05-14 11:30:18 +00002710 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002711
drh7ed97b92010-01-20 13:07:21 +00002712 /* Decrement the shared lock counter. Release the lock using an
2713 ** OS call only when all threads in this same process have released
2714 ** the lock.
2715 */
drh8af6c222010-05-14 12:43:01 +00002716 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2717 pInode->nShared--;
2718 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002719 SimulateIOErrorBenign(1);
2720 SimulateIOError( h=(-1) )
2721 SimulateIOErrorBenign(0);
2722 if( !skipShared ){
2723 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2724 }
2725 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002726 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002727 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002728 }
2729 }
2730 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002731 pInode->nLock--;
2732 assert( pInode->nLock>=0 );
2733 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002734 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002735 }
2736 }
drhbfe66312006-10-03 17:40:40 +00002737 }
drh7ed97b92010-01-20 13:07:21 +00002738
drh6c7d5c52008-11-21 20:32:33 +00002739 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002740 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002741 return rc;
2742}
2743
2744/*
drh339eb0b2008-03-07 15:34:11 +00002745** Close a file & cleanup AFP specific locking context
2746*/
danielk1977e339d652008-06-28 11:23:00 +00002747static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002748 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002749 if( id ){
2750 unixFile *pFile = (unixFile*)id;
2751 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002752 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002753 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002754 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002755 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002756 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002757 ** the last lock is cleared.
2758 */
dan08da86a2009-08-21 17:18:03 +00002759 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002760 }
danb0ac3e32010-06-16 10:55:42 +00002761 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002762 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002763 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002764 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002765 }
drh7ed97b92010-01-20 13:07:21 +00002766 return rc;
drhbfe66312006-10-03 17:40:40 +00002767}
2768
drhd2cb50b2009-01-09 21:41:17 +00002769#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002770/*
2771** The code above is the AFP lock implementation. The code is specific
2772** to MacOSX and does not work on other unix platforms. No alternative
2773** is available. If you don't compile for a mac, then the "unix-afp"
2774** VFS is not available.
2775**
2776********************* End of the AFP lock implementation **********************
2777******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002778
drh7ed97b92010-01-20 13:07:21 +00002779/******************************************************************************
2780*************************** Begin NFS Locking ********************************/
2781
2782#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2783/*
drh308c2a52010-05-14 11:30:18 +00002784 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002785 ** must be either NO_LOCK or SHARED_LOCK.
2786 **
2787 ** If the locking level of the file descriptor is already at or below
2788 ** the requested locking level, this routine is a no-op.
2789 */
drh308c2a52010-05-14 11:30:18 +00002790static int nfsUnlock(sqlite3_file *id, int eFileLock){
2791 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002792}
2793
2794#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2795/*
2796** The code above is the NFS lock implementation. The code is specific
2797** to MacOSX and does not work on other unix platforms. No alternative
2798** is available.
2799**
2800********************* End of the NFS lock implementation **********************
2801******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002802
2803/******************************************************************************
2804**************** Non-locking sqlite3_file methods *****************************
2805**
2806** The next division contains implementations for all methods of the
2807** sqlite3_file object other than the locking methods. The locking
2808** methods were defined in divisions above (one locking method per
2809** division). Those methods that are common to all locking modes
2810** are gather together into this division.
2811*/
drhbfe66312006-10-03 17:40:40 +00002812
2813/*
drh734c9862008-11-28 15:37:20 +00002814** Seek to the offset passed as the second argument, then read cnt
2815** bytes into pBuf. Return the number of bytes actually read.
2816**
2817** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2818** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2819** one system to another. Since SQLite does not define USE_PREAD
2820** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2821** See tickets #2741 and #2681.
2822**
2823** To avoid stomping the errno value on a failed read the lastErrno value
2824** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002825*/
drh734c9862008-11-28 15:37:20 +00002826static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2827 int got;
drh7ed97b92010-01-20 13:07:21 +00002828#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002829 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002830#endif
drh734c9862008-11-28 15:37:20 +00002831 TIMER_START;
2832#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002833 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002834 SimulateIOError( got = -1 );
2835#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002836 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002837 SimulateIOError( got = -1 );
2838#else
2839 newOffset = lseek(id->h, offset, SEEK_SET);
2840 SimulateIOError( newOffset-- );
2841 if( newOffset!=offset ){
2842 if( newOffset == -1 ){
2843 ((unixFile*)id)->lastErrno = errno;
2844 }else{
2845 ((unixFile*)id)->lastErrno = 0;
2846 }
2847 return -1;
2848 }
drhe562be52011-03-02 18:01:10 +00002849 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002850#endif
2851 TIMER_END;
2852 if( got<0 ){
2853 ((unixFile*)id)->lastErrno = errno;
2854 }
drh308c2a52010-05-14 11:30:18 +00002855 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002856 return got;
drhbfe66312006-10-03 17:40:40 +00002857}
2858
2859/*
drh734c9862008-11-28 15:37:20 +00002860** Read data from a file into a buffer. Return SQLITE_OK if all
2861** bytes were read successfully and SQLITE_IOERR if anything goes
2862** wrong.
drh339eb0b2008-03-07 15:34:11 +00002863*/
drh734c9862008-11-28 15:37:20 +00002864static int unixRead(
2865 sqlite3_file *id,
2866 void *pBuf,
2867 int amt,
2868 sqlite3_int64 offset
2869){
dan08da86a2009-08-21 17:18:03 +00002870 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002871 int got;
2872 assert( id );
drh08c6d442009-02-09 17:34:07 +00002873
dan08da86a2009-08-21 17:18:03 +00002874 /* If this is a database file (not a journal, master-journal or temp
2875 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002876#if 0
dane946c392009-08-22 11:39:46 +00002877 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002878 || offset>=PENDING_BYTE+512
2879 || offset+amt<=PENDING_BYTE
2880 );
dan7c246102010-04-12 19:00:29 +00002881#endif
drh08c6d442009-02-09 17:34:07 +00002882
dan08da86a2009-08-21 17:18:03 +00002883 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002884 if( got==amt ){
2885 return SQLITE_OK;
2886 }else if( got<0 ){
2887 /* lastErrno set by seekAndRead */
2888 return SQLITE_IOERR_READ;
2889 }else{
dan08da86a2009-08-21 17:18:03 +00002890 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002891 /* Unread parts of the buffer must be zero-filled */
2892 memset(&((char*)pBuf)[got], 0, amt-got);
2893 return SQLITE_IOERR_SHORT_READ;
2894 }
2895}
2896
2897/*
2898** Seek to the offset in id->offset then read cnt bytes into pBuf.
2899** Return the number of bytes actually read. Update the offset.
2900**
2901** To avoid stomping the errno value on a failed write the lastErrno value
2902** is set before returning.
2903*/
2904static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2905 int got;
drh7ed97b92010-01-20 13:07:21 +00002906#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002907 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002908#endif
drh734c9862008-11-28 15:37:20 +00002909 TIMER_START;
2910#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002911 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002912#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002913 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002914#else
2915 newOffset = lseek(id->h, offset, SEEK_SET);
2916 if( newOffset!=offset ){
2917 if( newOffset == -1 ){
2918 ((unixFile*)id)->lastErrno = errno;
2919 }else{
2920 ((unixFile*)id)->lastErrno = 0;
2921 }
2922 return -1;
2923 }
drhe562be52011-03-02 18:01:10 +00002924 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002925#endif
2926 TIMER_END;
2927 if( got<0 ){
2928 ((unixFile*)id)->lastErrno = errno;
2929 }
2930
drh308c2a52010-05-14 11:30:18 +00002931 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002932 return got;
2933}
2934
2935
2936/*
2937** Write data from a buffer into a file. Return SQLITE_OK on success
2938** or some other error code on failure.
2939*/
2940static int unixWrite(
2941 sqlite3_file *id,
2942 const void *pBuf,
2943 int amt,
2944 sqlite3_int64 offset
2945){
dan08da86a2009-08-21 17:18:03 +00002946 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002947 int wrote = 0;
2948 assert( id );
2949 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002950
dan08da86a2009-08-21 17:18:03 +00002951 /* If this is a database file (not a journal, master-journal or temp
2952 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002953#if 0
dane946c392009-08-22 11:39:46 +00002954 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002955 || offset>=PENDING_BYTE+512
2956 || offset+amt<=PENDING_BYTE
2957 );
dan7c246102010-04-12 19:00:29 +00002958#endif
drh08c6d442009-02-09 17:34:07 +00002959
drh8f941bc2009-01-14 23:03:40 +00002960#ifndef NDEBUG
2961 /* If we are doing a normal write to a database file (as opposed to
2962 ** doing a hot-journal rollback or a write to some file other than a
2963 ** normal database file) then record the fact that the database
2964 ** has changed. If the transaction counter is modified, record that
2965 ** fact too.
2966 */
dan08da86a2009-08-21 17:18:03 +00002967 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002968 pFile->dbUpdate = 1; /* The database has been modified */
2969 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002970 int rc;
drh8f941bc2009-01-14 23:03:40 +00002971 char oldCntr[4];
2972 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002973 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002974 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002975 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002976 pFile->transCntrChng = 1; /* The transaction counter has changed */
2977 }
2978 }
2979 }
2980#endif
2981
dan08da86a2009-08-21 17:18:03 +00002982 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002983 amt -= wrote;
2984 offset += wrote;
2985 pBuf = &((char*)pBuf)[wrote];
2986 }
2987 SimulateIOError(( wrote=(-1), amt=1 ));
2988 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002989
drh734c9862008-11-28 15:37:20 +00002990 if( amt>0 ){
2991 if( wrote<0 ){
2992 /* lastErrno set by seekAndWrite */
2993 return SQLITE_IOERR_WRITE;
2994 }else{
dan08da86a2009-08-21 17:18:03 +00002995 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002996 return SQLITE_FULL;
2997 }
2998 }
dan6e09d692010-07-27 18:34:15 +00002999
drh734c9862008-11-28 15:37:20 +00003000 return SQLITE_OK;
3001}
3002
3003#ifdef SQLITE_TEST
3004/*
3005** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003006** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003007*/
3008int sqlite3_sync_count = 0;
3009int sqlite3_fullsync_count = 0;
3010#endif
3011
3012/*
drh89240432009-03-25 01:06:01 +00003013** We do not trust systems to provide a working fdatasync(). Some do.
3014** Others do no. To be safe, we will stick with the (slower) fsync().
3015** If you know that your system does support fdatasync() correctly,
3016** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003017*/
drh89240432009-03-25 01:06:01 +00003018#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003019# define fdatasync fsync
3020#endif
3021
3022/*
3023** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3024** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3025** only available on Mac OS X. But that could change.
3026*/
3027#ifdef F_FULLFSYNC
3028# define HAVE_FULLFSYNC 1
3029#else
3030# define HAVE_FULLFSYNC 0
3031#endif
3032
3033
3034/*
3035** The fsync() system call does not work as advertised on many
3036** unix systems. The following procedure is an attempt to make
3037** it work better.
3038**
3039** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3040** for testing when we want to run through the test suite quickly.
3041** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3042** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3043** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003044**
3045** SQLite sets the dataOnly flag if the size of the file is unchanged.
3046** The idea behind dataOnly is that it should only write the file content
3047** to disk, not the inode. We only set dataOnly if the file size is
3048** unchanged since the file size is part of the inode. However,
3049** Ted Ts'o tells us that fdatasync() will also write the inode if the
3050** file size has changed. The only real difference between fdatasync()
3051** and fsync(), Ted tells us, is that fdatasync() will not flush the
3052** inode if the mtime or owner or other inode attributes have changed.
3053** We only care about the file size, not the other file attributes, so
3054** as far as SQLite is concerned, an fdatasync() is always adequate.
3055** So, we always use fdatasync() if it is available, regardless of
3056** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003057*/
3058static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003059 int rc;
drh734c9862008-11-28 15:37:20 +00003060
3061 /* The following "ifdef/elif/else/" block has the same structure as
3062 ** the one below. It is replicated here solely to avoid cluttering
3063 ** up the real code with the UNUSED_PARAMETER() macros.
3064 */
3065#ifdef SQLITE_NO_SYNC
3066 UNUSED_PARAMETER(fd);
3067 UNUSED_PARAMETER(fullSync);
3068 UNUSED_PARAMETER(dataOnly);
3069#elif HAVE_FULLFSYNC
3070 UNUSED_PARAMETER(dataOnly);
3071#else
3072 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003073 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003074#endif
3075
3076 /* Record the number of times that we do a normal fsync() and
3077 ** FULLSYNC. This is used during testing to verify that this procedure
3078 ** gets called with the correct arguments.
3079 */
3080#ifdef SQLITE_TEST
3081 if( fullSync ) sqlite3_fullsync_count++;
3082 sqlite3_sync_count++;
3083#endif
3084
3085 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3086 ** no-op
3087 */
3088#ifdef SQLITE_NO_SYNC
3089 rc = SQLITE_OK;
3090#elif HAVE_FULLFSYNC
3091 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003092 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003093 }else{
3094 rc = 1;
3095 }
3096 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003097 ** It shouldn't be possible for fullfsync to fail on the local
3098 ** file system (on OSX), so failure indicates that FULLFSYNC
3099 ** isn't supported for this file system. So, attempt an fsync
3100 ** and (for now) ignore the overhead of a superfluous fcntl call.
3101 ** It'd be better to detect fullfsync support once and avoid
3102 ** the fcntl call every time sync is called.
3103 */
drh734c9862008-11-28 15:37:20 +00003104 if( rc ) rc = fsync(fd);
3105
drh7ed97b92010-01-20 13:07:21 +00003106#elif defined(__APPLE__)
3107 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3108 ** so currently we default to the macro that redefines fdatasync to fsync
3109 */
3110 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003111#else
drh0b647ff2009-03-21 14:41:04 +00003112 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003113#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003114 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003115 rc = fsync(fd);
3116 }
drh0b647ff2009-03-21 14:41:04 +00003117#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003118#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3119
3120 if( OS_VXWORKS && rc!= -1 ){
3121 rc = 0;
3122 }
chw97185482008-11-17 08:05:31 +00003123 return rc;
drhbfe66312006-10-03 17:40:40 +00003124}
3125
drh734c9862008-11-28 15:37:20 +00003126/*
3127** Make sure all writes to a particular file are committed to disk.
3128**
3129** If dataOnly==0 then both the file itself and its metadata (file
3130** size, access time, etc) are synced. If dataOnly!=0 then only the
3131** file data is synced.
3132**
3133** Under Unix, also make sure that the directory entry for the file
3134** has been created by fsync-ing the directory that contains the file.
3135** If we do not do this and we encounter a power failure, the directory
3136** entry for the journal might not exist after we reboot. The next
3137** SQLite to access the file will not know that the journal exists (because
3138** the directory entry for the journal was never created) and the transaction
3139** will not roll back - possibly leading to database corruption.
3140*/
3141static int unixSync(sqlite3_file *id, int flags){
3142 int rc;
3143 unixFile *pFile = (unixFile*)id;
3144
3145 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3146 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3147
3148 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3149 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3150 || (flags&0x0F)==SQLITE_SYNC_FULL
3151 );
3152
3153 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3154 ** line is to test that doing so does not cause any problems.
3155 */
3156 SimulateDiskfullError( return SQLITE_FULL );
3157
3158 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003159 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003160 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3161 SimulateIOError( rc=1 );
3162 if( rc ){
3163 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003164 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003165 }
3166 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003167 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3168 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003169#ifndef SQLITE_DISABLE_DIRSYNC
3170 /* The directory sync is only attempted if full_fsync is
3171 ** turned off or unavailable. If a full_fsync occurred above,
3172 ** then the directory sync is superfluous.
3173 */
3174 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3175 /*
3176 ** We have received multiple reports of fsync() returning
3177 ** errors when applied to directories on certain file systems.
3178 ** A failed directory sync is not a big deal. So it seems
3179 ** better to ignore the error. Ticket #1657
3180 */
3181 /* pFile->lastErrno = errno; */
3182 /* return SQLITE_IOERR; */
3183 }
3184#endif
drh0e9365c2011-03-02 02:08:13 +00003185 /* Only need to sync once, so close the directory when we are done */
3186 robust_close(pFile, pFile->dirfd, __LINE__);
3187 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003188 }
3189 return rc;
3190}
3191
3192/*
3193** Truncate an open file to a specified size
3194*/
3195static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003196 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003197 int rc;
dan6e09d692010-07-27 18:34:15 +00003198 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003199 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003200
3201 /* If the user has configured a chunk-size for this file, truncate the
3202 ** file so that it consists of an integer number of chunks (i.e. the
3203 ** actual file size after the operation may be larger than the requested
3204 ** size).
3205 */
3206 if( pFile->szChunk ){
3207 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3208 }
3209
drhff812312011-02-23 13:33:46 +00003210 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003211 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003212 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003213 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003214 }else{
drh3313b142009-11-06 04:13:18 +00003215#ifndef NDEBUG
3216 /* If we are doing a normal write to a database file (as opposed to
3217 ** doing a hot-journal rollback or a write to some file other than a
3218 ** normal database file) and we truncate the file to zero length,
3219 ** that effectively updates the change counter. This might happen
3220 ** when restoring a database using the backup API from a zero-length
3221 ** source.
3222 */
dan6e09d692010-07-27 18:34:15 +00003223 if( pFile->inNormalWrite && nByte==0 ){
3224 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003225 }
3226#endif
3227
drh734c9862008-11-28 15:37:20 +00003228 return SQLITE_OK;
3229 }
3230}
3231
3232/*
3233** Determine the current size of a file in bytes
3234*/
3235static int unixFileSize(sqlite3_file *id, i64 *pSize){
3236 int rc;
3237 struct stat buf;
3238 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003239 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003240 SimulateIOError( rc=1 );
3241 if( rc!=0 ){
3242 ((unixFile*)id)->lastErrno = errno;
3243 return SQLITE_IOERR_FSTAT;
3244 }
3245 *pSize = buf.st_size;
3246
drh8af6c222010-05-14 12:43:01 +00003247 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003248 ** writes a single byte into that file in order to work around a bug
3249 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3250 ** layers, we need to report this file size as zero even though it is
3251 ** really 1. Ticket #3260.
3252 */
3253 if( *pSize==1 ) *pSize = 0;
3254
3255
3256 return SQLITE_OK;
3257}
3258
drhd2cb50b2009-01-09 21:41:17 +00003259#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003260/*
3261** Handler for proxy-locking file-control verbs. Defined below in the
3262** proxying locking division.
3263*/
3264static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003265#endif
drh715ff302008-12-03 22:32:44 +00003266
dan502019c2010-07-28 14:26:17 +00003267/*
3268** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3269** file-control operation.
3270**
3271** If the user has configured a chunk-size for this file, it could be
3272** that the file needs to be extended at this point. Otherwise, the
3273** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3274*/
3275static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3276 if( pFile->szChunk ){
3277 i64 nSize; /* Required file size */
3278 struct stat buf; /* Used to hold return values of fstat() */
3279
drh99ab3b12011-03-02 15:09:07 +00003280 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003281
3282 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3283 if( nSize>(i64)buf.st_size ){
3284#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003285 int rc;
3286 do{
drhe562be52011-03-02 18:01:10 +00003287 rc = osFallocate(pFile->.h, buf.st_size, nSize-buf.st_size;
drhff812312011-02-23 13:33:46 +00003288 }while( rc<0 && errno=EINTR );
3289 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003290#else
3291 /* If the OS does not have posix_fallocate(), fake it. First use
3292 ** ftruncate() to set the file size, then write a single byte to
3293 ** the last byte in each block within the extended region. This
3294 ** is the same technique used by glibc to implement posix_fallocate()
3295 ** on systems that do not have a real fallocate() system call.
3296 */
3297 int nBlk = buf.st_blksize; /* File-system block size */
3298 i64 iWrite; /* Next offset to write to */
3299 int nWrite; /* Return value from seekAndWrite() */
3300
drhff812312011-02-23 13:33:46 +00003301 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003302 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003303 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003304 }
3305 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3306 do {
3307 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3308 iWrite += nBlk;
3309 } while( nWrite==1 && iWrite<nSize );
3310 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3311#endif
3312 }
3313 }
3314
3315 return SQLITE_OK;
3316}
danielk1977ad94b582007-08-20 06:44:22 +00003317
danielk1977e3026632004-06-22 11:29:02 +00003318/*
drh9e33c2c2007-08-31 18:34:59 +00003319** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003320*/
drhcc6bb3e2007-08-31 16:11:35 +00003321static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003322 switch( op ){
3323 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003324 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003325 return SQLITE_OK;
3326 }
drh7708e972008-11-29 00:56:52 +00003327 case SQLITE_LAST_ERRNO: {
3328 *(int*)pArg = ((unixFile*)id)->lastErrno;
3329 return SQLITE_OK;
3330 }
dan6e09d692010-07-27 18:34:15 +00003331 case SQLITE_FCNTL_CHUNK_SIZE: {
3332 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003333 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003334 }
drh9ff27ec2010-05-19 19:26:05 +00003335 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003336 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003337 }
drh8f941bc2009-01-14 23:03:40 +00003338#ifndef NDEBUG
3339 /* The pager calls this method to signal that it has done
3340 ** a rollback and that the database is therefore unchanged and
3341 ** it hence it is OK for the transaction change counter to be
3342 ** unchanged.
3343 */
3344 case SQLITE_FCNTL_DB_UNCHANGED: {
3345 ((unixFile*)id)->dbUpdate = 0;
3346 return SQLITE_OK;
3347 }
3348#endif
drhd2cb50b2009-01-09 21:41:17 +00003349#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003350 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003351 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003352 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003353 }
drhd2cb50b2009-01-09 21:41:17 +00003354#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003355 case SQLITE_FCNTL_SYNC_OMITTED: {
3356 return SQLITE_OK; /* A no-op */
3357 }
drh9e33c2c2007-08-31 18:34:59 +00003358 }
drh0b52b7d2011-01-26 19:46:22 +00003359 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003360}
3361
3362/*
danielk1977a3d4c882007-03-23 10:08:38 +00003363** Return the sector size in bytes of the underlying block device for
3364** the specified file. This is almost always 512 bytes, but may be
3365** larger for some devices.
3366**
3367** SQLite code assumes this function cannot fail. It also assumes that
3368** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003369** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003370** same for both.
3371*/
danielk1977397d65f2008-11-19 11:35:39 +00003372static int unixSectorSize(sqlite3_file *NotUsed){
3373 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003374 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003375}
3376
danielk197790949c22007-08-17 16:50:38 +00003377/*
danielk1977397d65f2008-11-19 11:35:39 +00003378** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003379*/
danielk1977397d65f2008-11-19 11:35:39 +00003380static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3381 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003382 return 0;
3383}
3384
drhd9e5c4f2010-05-12 18:01:39 +00003385#ifndef SQLITE_OMIT_WAL
3386
3387
3388/*
drhd91c68f2010-05-14 14:52:25 +00003389** Object used to represent an shared memory buffer.
3390**
3391** When multiple threads all reference the same wal-index, each thread
3392** has its own unixShm object, but they all point to a single instance
3393** of this unixShmNode object. In other words, each wal-index is opened
3394** only once per process.
3395**
3396** Each unixShmNode object is connected to a single unixInodeInfo object.
3397** We could coalesce this object into unixInodeInfo, but that would mean
3398** every open file that does not use shared memory (in other words, most
3399** open files) would have to carry around this extra information. So
3400** the unixInodeInfo object contains a pointer to this unixShmNode object
3401** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003402**
3403** unixMutexHeld() must be true when creating or destroying
3404** this object or while reading or writing the following fields:
3405**
3406** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003407**
3408** The following fields are read-only after the object is created:
3409**
3410** fid
3411** zFilename
3412**
drhd91c68f2010-05-14 14:52:25 +00003413** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003414** unixMutexHeld() is true when reading or writing any other field
3415** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003416*/
drhd91c68f2010-05-14 14:52:25 +00003417struct unixShmNode {
3418 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003419 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003420 char *zFilename; /* Name of the mmapped file */
3421 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003422 int szRegion; /* Size of shared-memory regions */
3423 int nRegion; /* Size of array apRegion */
3424 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003425 int nRef; /* Number of unixShm objects pointing to this */
3426 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003427#ifdef SQLITE_DEBUG
3428 u8 exclMask; /* Mask of exclusive locks held */
3429 u8 sharedMask; /* Mask of shared locks held */
3430 u8 nextShmId; /* Next available unixShm.id value */
3431#endif
3432};
3433
3434/*
drhd9e5c4f2010-05-12 18:01:39 +00003435** Structure used internally by this VFS to record the state of an
3436** open shared memory connection.
3437**
drhd91c68f2010-05-14 14:52:25 +00003438** The following fields are initialized when this object is created and
3439** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003440**
drhd91c68f2010-05-14 14:52:25 +00003441** unixShm.pFile
3442** unixShm.id
3443**
3444** All other fields are read/write. The unixShm.pFile->mutex must be held
3445** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003446*/
3447struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003448 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3449 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003450 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003451 u16 sharedMask; /* Mask of shared locks held */
3452 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003453#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003454 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003455#endif
3456};
3457
3458/*
drhd9e5c4f2010-05-12 18:01:39 +00003459** Constants used for locking
3460*/
drhbd9676c2010-06-23 17:58:38 +00003461#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003462#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003463
drhd9e5c4f2010-05-12 18:01:39 +00003464/*
drh73b64e42010-05-30 19:55:15 +00003465** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003466**
3467** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3468** otherwise.
3469*/
3470static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003471 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3472 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003473 int ofst, /* First byte of the locking range */
3474 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003475){
3476 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003477 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003478
drhd91c68f2010-05-14 14:52:25 +00003479 /* Access to the unixShmNode object is serialized by the caller */
3480 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003481
drh73b64e42010-05-30 19:55:15 +00003482 /* Shared locks never span more than one byte */
3483 assert( n==1 || lockType!=F_RDLCK );
3484
3485 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003486 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003487
drhd9e5c4f2010-05-12 18:01:39 +00003488 /* Initialize the locking parameters */
3489 memset(&f, 0, sizeof(f));
3490 f.l_type = lockType;
3491 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003492 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003493 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003494
drh99ab3b12011-03-02 15:09:07 +00003495 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003496 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3497
3498 /* Update the global lock state and do debug tracing */
3499#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003500 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003501 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003502 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003503 if( rc==SQLITE_OK ){
3504 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003505 OSTRACE(("unlock %d ok", ofst));
3506 pShmNode->exclMask &= ~mask;
3507 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003508 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003509 OSTRACE(("read-lock %d ok", ofst));
3510 pShmNode->exclMask &= ~mask;
3511 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003512 }else{
3513 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003514 OSTRACE(("write-lock %d ok", ofst));
3515 pShmNode->exclMask |= mask;
3516 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003517 }
3518 }else{
3519 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003520 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003521 }else if( lockType==F_RDLCK ){
3522 OSTRACE(("read-lock failed"));
3523 }else{
3524 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003525 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003526 }
3527 }
drh20e1f082010-05-31 16:10:12 +00003528 OSTRACE((" - afterwards %03x,%03x\n",
3529 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003530 }
drhd9e5c4f2010-05-12 18:01:39 +00003531#endif
3532
3533 return rc;
3534}
3535
drhd9e5c4f2010-05-12 18:01:39 +00003536
3537/*
drhd91c68f2010-05-14 14:52:25 +00003538** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003539**
3540** This is not a VFS shared-memory method; it is a utility function called
3541** by VFS shared-memory methods.
3542*/
drhd91c68f2010-05-14 14:52:25 +00003543static void unixShmPurge(unixFile *pFd){
3544 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003545 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003546 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003547 int i;
drhd91c68f2010-05-14 14:52:25 +00003548 assert( p->pInode==pFd->pInode );
3549 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003550 for(i=0; i<p->nRegion; i++){
3551 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003552 }
dan18801912010-06-14 14:07:50 +00003553 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003554 if( p->h>=0 ){
3555 robust_close(pFd, p->h, __LINE__);
3556 p->h = -1;
3557 }
drhd91c68f2010-05-14 14:52:25 +00003558 p->pInode->pShmNode = 0;
3559 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003560 }
3561}
3562
3563/*
danda9fe0c2010-07-13 18:44:03 +00003564** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003565** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003566**
drh7234c6d2010-06-19 15:10:09 +00003567** The file used to implement shared-memory is in the same directory
3568** as the open database file and has the same name as the open database
3569** file with the "-shm" suffix added. For example, if the database file
3570** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003571** for shared memory will be called "/home/user1/config.db-shm".
3572**
3573** Another approach to is to use files in /dev/shm or /dev/tmp or an
3574** some other tmpfs mount. But if a file in a different directory
3575** from the database file is used, then differing access permissions
3576** or a chroot() might cause two different processes on the same
3577** database to end up using different files for shared memory -
3578** meaning that their memory would not really be shared - resulting
3579** in database corruption. Nevertheless, this tmpfs file usage
3580** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3581** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3582** option results in an incompatible build of SQLite; builds of SQLite
3583** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3584** same database file at the same time, database corruption will likely
3585** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3586** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003587**
3588** When opening a new shared-memory file, if no other instances of that
3589** file are currently open, in this process or in other processes, then
3590** the file must be truncated to zero length or have its header cleared.
3591*/
danda9fe0c2010-07-13 18:44:03 +00003592static int unixOpenSharedMemory(unixFile *pDbFd){
3593 struct unixShm *p = 0; /* The connection to be opened */
3594 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3595 int rc; /* Result code */
3596 unixInodeInfo *pInode; /* The inode of fd */
3597 char *zShmFilename; /* Name of the file used for SHM */
3598 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003599
danda9fe0c2010-07-13 18:44:03 +00003600 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003601 p = sqlite3_malloc( sizeof(*p) );
3602 if( p==0 ) return SQLITE_NOMEM;
3603 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003604 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003605
danda9fe0c2010-07-13 18:44:03 +00003606 /* Check to see if a unixShmNode object already exists. Reuse an existing
3607 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003608 */
3609 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003610 pInode = pDbFd->pInode;
3611 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003612 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003613 struct stat sStat; /* fstat() info for database file */
3614
3615 /* Call fstat() to figure out the permissions on the database file. If
3616 ** a new *-shm file is created, an attempt will be made to create it
3617 ** with the same permissions. The actual permissions the file is created
3618 ** with are subject to the current umask setting.
3619 */
drh99ab3b12011-03-02 15:09:07 +00003620 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00003621 rc = SQLITE_IOERR_FSTAT;
3622 goto shm_open_err;
3623 }
3624
drha4ced192010-07-15 18:32:40 +00003625#ifdef SQLITE_SHM_DIRECTORY
3626 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3627#else
drh7234c6d2010-06-19 15:10:09 +00003628 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003629#endif
drh7234c6d2010-06-19 15:10:09 +00003630 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003631 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003632 rc = SQLITE_NOMEM;
3633 goto shm_open_err;
3634 }
drhd91c68f2010-05-14 14:52:25 +00003635 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003636 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003637#ifdef SQLITE_SHM_DIRECTORY
3638 sqlite3_snprintf(nShmFilename, zShmFilename,
3639 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3640 (u32)sStat.st_ino, (u32)sStat.st_dev);
3641#else
drh7234c6d2010-06-19 15:10:09 +00003642 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003643#endif
drhd91c68f2010-05-14 14:52:25 +00003644 pShmNode->h = -1;
3645 pDbFd->pInode->pShmNode = pShmNode;
3646 pShmNode->pInode = pDbFd->pInode;
3647 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3648 if( pShmNode->mutex==0 ){
3649 rc = SQLITE_NOMEM;
3650 goto shm_open_err;
3651 }
drhd9e5c4f2010-05-12 18:01:39 +00003652
drh99ab3b12011-03-02 15:09:07 +00003653 pShmNode->h = osOpen(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003654 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003655 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003656 goto shm_open_err;
3657 }
3658
drhd9e5c4f2010-05-12 18:01:39 +00003659 /* Check to see if another process is holding the dead-man switch.
3660 ** If not, truncate the file to zero length.
3661 */
drhd91c68f2010-05-14 14:52:25 +00003662 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003663 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhff812312011-02-23 13:33:46 +00003664 if( robust_ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003665 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003666 }
3667 }
3668 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003669 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003670 }
3671 if( rc ) goto shm_open_err;
3672 }
3673
drhd91c68f2010-05-14 14:52:25 +00003674 /* Make the new connection a child of the unixShmNode */
3675 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003676#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003677 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003678#endif
drhd91c68f2010-05-14 14:52:25 +00003679 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003680 pDbFd->pShm = p;
3681 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003682
3683 /* The reference count on pShmNode has already been incremented under
3684 ** the cover of the unixEnterMutex() mutex and the pointer from the
3685 ** new (struct unixShm) object to the pShmNode has been set. All that is
3686 ** left to do is to link the new object into the linked list starting
3687 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3688 ** mutex.
3689 */
3690 sqlite3_mutex_enter(pShmNode->mutex);
3691 p->pNext = pShmNode->pFirst;
3692 pShmNode->pFirst = p;
3693 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003694 return SQLITE_OK;
3695
3696 /* Jump here on any error */
3697shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003698 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003699 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003700 unixLeaveMutex();
3701 return rc;
3702}
3703
3704/*
danda9fe0c2010-07-13 18:44:03 +00003705** This function is called to obtain a pointer to region iRegion of the
3706** shared-memory associated with the database file fd. Shared-memory regions
3707** are numbered starting from zero. Each shared-memory region is szRegion
3708** bytes in size.
3709**
3710** If an error occurs, an error code is returned and *pp is set to NULL.
3711**
3712** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3713** region has not been allocated (by any client, including one running in a
3714** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3715** bExtend is non-zero and the requested shared-memory region has not yet
3716** been allocated, it is allocated by this function.
3717**
3718** If the shared-memory region has already been allocated or is allocated by
3719** this call as described above, then it is mapped into this processes
3720** address space (if it is not already), *pp is set to point to the mapped
3721** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003722*/
danda9fe0c2010-07-13 18:44:03 +00003723static int unixShmMap(
3724 sqlite3_file *fd, /* Handle open on database file */
3725 int iRegion, /* Region to retrieve */
3726 int szRegion, /* Size of regions */
3727 int bExtend, /* True to extend file if necessary */
3728 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003729){
danda9fe0c2010-07-13 18:44:03 +00003730 unixFile *pDbFd = (unixFile*)fd;
3731 unixShm *p;
3732 unixShmNode *pShmNode;
3733 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003734
danda9fe0c2010-07-13 18:44:03 +00003735 /* If the shared-memory file has not yet been opened, open it now. */
3736 if( pDbFd->pShm==0 ){
3737 rc = unixOpenSharedMemory(pDbFd);
3738 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003739 }
drhd9e5c4f2010-05-12 18:01:39 +00003740
danda9fe0c2010-07-13 18:44:03 +00003741 p = pDbFd->pShm;
3742 pShmNode = p->pShmNode;
3743 sqlite3_mutex_enter(pShmNode->mutex);
3744 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3745
3746 if( pShmNode->nRegion<=iRegion ){
3747 char **apNew; /* New apRegion[] array */
3748 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3749 struct stat sStat; /* Used by fstat() */
3750
3751 pShmNode->szRegion = szRegion;
3752
3753 /* The requested region is not mapped into this processes address space.
3754 ** Check to see if it has been allocated (i.e. if the wal-index file is
3755 ** large enough to contain the requested region).
3756 */
drh99ab3b12011-03-02 15:09:07 +00003757 if( osFstat(pShmNode->h, &sStat) ){
danda9fe0c2010-07-13 18:44:03 +00003758 rc = SQLITE_IOERR_SHMSIZE;
3759 goto shmpage_out;
3760 }
3761
3762 if( sStat.st_size<nByte ){
3763 /* The requested memory region does not exist. If bExtend is set to
3764 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3765 **
3766 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3767 ** the requested memory region.
3768 */
3769 if( !bExtend ) goto shmpage_out;
drhff812312011-02-23 13:33:46 +00003770 if( robust_ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003771 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003772 goto shmpage_out;
3773 }
3774 }
3775
3776 /* Map the requested memory region into this processes address space. */
3777 apNew = (char **)sqlite3_realloc(
3778 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3779 );
3780 if( !apNew ){
3781 rc = SQLITE_IOERR_NOMEM;
3782 goto shmpage_out;
3783 }
3784 pShmNode->apRegion = apNew;
3785 while(pShmNode->nRegion<=iRegion){
3786 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003787 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003788 );
3789 if( pMem==MAP_FAILED ){
3790 rc = SQLITE_IOERR;
3791 goto shmpage_out;
3792 }
3793 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3794 pShmNode->nRegion++;
3795 }
3796 }
3797
3798shmpage_out:
3799 if( pShmNode->nRegion>iRegion ){
3800 *pp = pShmNode->apRegion[iRegion];
3801 }else{
3802 *pp = 0;
3803 }
3804 sqlite3_mutex_leave(pShmNode->mutex);
3805 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003806}
3807
3808/*
drhd9e5c4f2010-05-12 18:01:39 +00003809** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003810**
3811** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3812** different here than in posix. In xShmLock(), one can go from unlocked
3813** to shared and back or from unlocked to exclusive and back. But one may
3814** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003815*/
3816static int unixShmLock(
3817 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003818 int ofst, /* First lock to acquire or release */
3819 int n, /* Number of locks to acquire or release */
3820 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003821){
drh73b64e42010-05-30 19:55:15 +00003822 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3823 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3824 unixShm *pX; /* For looping over all siblings */
3825 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3826 int rc = SQLITE_OK; /* Result code */
3827 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003828
drhd91c68f2010-05-14 14:52:25 +00003829 assert( pShmNode==pDbFd->pInode->pShmNode );
3830 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003831 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003832 assert( n>=1 );
3833 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3834 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3835 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3836 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3837 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003838
drhc99597c2010-05-31 01:41:15 +00003839 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003840 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003841 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003842 if( flags & SQLITE_SHM_UNLOCK ){
3843 u16 allMask = 0; /* Mask of locks held by siblings */
3844
3845 /* See if any siblings hold this same lock */
3846 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3847 if( pX==p ) continue;
3848 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3849 allMask |= pX->sharedMask;
3850 }
3851
3852 /* Unlock the system-level locks */
3853 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003854 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003855 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003856 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003857 }
drh73b64e42010-05-30 19:55:15 +00003858
3859 /* Undo the local locks */
3860 if( rc==SQLITE_OK ){
3861 p->exclMask &= ~mask;
3862 p->sharedMask &= ~mask;
3863 }
3864 }else if( flags & SQLITE_SHM_SHARED ){
3865 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3866
3867 /* Find out which shared locks are already held by sibling connections.
3868 ** If any sibling already holds an exclusive lock, go ahead and return
3869 ** SQLITE_BUSY.
3870 */
3871 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003872 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003873 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003874 break;
3875 }
3876 allShared |= pX->sharedMask;
3877 }
3878
3879 /* Get shared locks at the system level, if necessary */
3880 if( rc==SQLITE_OK ){
3881 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003882 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003883 }else{
drh73b64e42010-05-30 19:55:15 +00003884 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003885 }
drhd9e5c4f2010-05-12 18:01:39 +00003886 }
drh73b64e42010-05-30 19:55:15 +00003887
3888 /* Get the local shared locks */
3889 if( rc==SQLITE_OK ){
3890 p->sharedMask |= mask;
3891 }
3892 }else{
3893 /* Make sure no sibling connections hold locks that will block this
3894 ** lock. If any do, return SQLITE_BUSY right away.
3895 */
3896 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003897 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3898 rc = SQLITE_BUSY;
3899 break;
3900 }
3901 }
3902
3903 /* Get the exclusive locks at the system level. Then if successful
3904 ** also mark the local connection as being locked.
3905 */
3906 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003907 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003908 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003909 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003910 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003911 }
drhd9e5c4f2010-05-12 18:01:39 +00003912 }
3913 }
drhd91c68f2010-05-14 14:52:25 +00003914 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003915 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3916 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003917 return rc;
3918}
3919
drh286a2882010-05-20 23:51:06 +00003920/*
3921** Implement a memory barrier or memory fence on shared memory.
3922**
3923** All loads and stores begun before the barrier must complete before
3924** any load or store begun after the barrier.
3925*/
3926static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003927 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003928){
drhff828942010-06-26 21:34:06 +00003929 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003930 unixEnterMutex();
3931 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003932}
3933
dan18801912010-06-14 14:07:50 +00003934/*
danda9fe0c2010-07-13 18:44:03 +00003935** Close a connection to shared-memory. Delete the underlying
3936** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003937**
3938** If there is no shared memory associated with the connection then this
3939** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003940*/
danda9fe0c2010-07-13 18:44:03 +00003941static int unixShmUnmap(
3942 sqlite3_file *fd, /* The underlying database file */
3943 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003944){
danda9fe0c2010-07-13 18:44:03 +00003945 unixShm *p; /* The connection to be closed */
3946 unixShmNode *pShmNode; /* The underlying shared-memory file */
3947 unixShm **pp; /* For looping over sibling connections */
3948 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003949
danda9fe0c2010-07-13 18:44:03 +00003950 pDbFd = (unixFile*)fd;
3951 p = pDbFd->pShm;
3952 if( p==0 ) return SQLITE_OK;
3953 pShmNode = p->pShmNode;
3954
3955 assert( pShmNode==pDbFd->pInode->pShmNode );
3956 assert( pShmNode->pInode==pDbFd->pInode );
3957
3958 /* Remove connection p from the set of connections associated
3959 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003960 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003961 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3962 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003963
danda9fe0c2010-07-13 18:44:03 +00003964 /* Free the connection p */
3965 sqlite3_free(p);
3966 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003967 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003968
3969 /* If pShmNode->nRef has reached 0, then close the underlying
3970 ** shared-memory file, too */
3971 unixEnterMutex();
3972 assert( pShmNode->nRef>0 );
3973 pShmNode->nRef--;
3974 if( pShmNode->nRef==0 ){
3975 if( deleteFlag ) unlink(pShmNode->zFilename);
3976 unixShmPurge(pDbFd);
3977 }
3978 unixLeaveMutex();
3979
3980 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003981}
drh286a2882010-05-20 23:51:06 +00003982
danda9fe0c2010-07-13 18:44:03 +00003983
drhd9e5c4f2010-05-12 18:01:39 +00003984#else
drh6b017cc2010-06-14 18:01:46 +00003985# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003986# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003987# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003988# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003989#endif /* #ifndef SQLITE_OMIT_WAL */
3990
drh734c9862008-11-28 15:37:20 +00003991/*
3992** Here ends the implementation of all sqlite3_file methods.
3993**
3994********************** End sqlite3_file Methods *******************************
3995******************************************************************************/
3996
3997/*
drh6b9d6dd2008-12-03 19:34:47 +00003998** This division contains definitions of sqlite3_io_methods objects that
3999** implement various file locking strategies. It also contains definitions
4000** of "finder" functions. A finder-function is used to locate the appropriate
4001** sqlite3_io_methods object for a particular database file. The pAppData
4002** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4003** the correct finder-function for that VFS.
4004**
4005** Most finder functions return a pointer to a fixed sqlite3_io_methods
4006** object. The only interesting finder-function is autolockIoFinder, which
4007** looks at the filesystem type and tries to guess the best locking
4008** strategy from that.
4009**
drh1875f7a2008-12-08 18:19:17 +00004010** For finder-funtion F, two objects are created:
4011**
4012** (1) The real finder-function named "FImpt()".
4013**
dane946c392009-08-22 11:39:46 +00004014** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004015**
4016**
4017** A pointer to the F pointer is used as the pAppData value for VFS
4018** objects. We have to do this instead of letting pAppData point
4019** directly at the finder-function since C90 rules prevent a void*
4020** from be cast into a function pointer.
4021**
drh6b9d6dd2008-12-03 19:34:47 +00004022**
drh7708e972008-11-29 00:56:52 +00004023** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004024**
drh7708e972008-11-29 00:56:52 +00004025** * A constant sqlite3_io_methods object call METHOD that has locking
4026** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4027**
4028** * An I/O method finder function called FINDER that returns a pointer
4029** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004030*/
drhd9e5c4f2010-05-12 18:01:39 +00004031#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004032static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004033 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004034 CLOSE, /* xClose */ \
4035 unixRead, /* xRead */ \
4036 unixWrite, /* xWrite */ \
4037 unixTruncate, /* xTruncate */ \
4038 unixSync, /* xSync */ \
4039 unixFileSize, /* xFileSize */ \
4040 LOCK, /* xLock */ \
4041 UNLOCK, /* xUnlock */ \
4042 CKLOCK, /* xCheckReservedLock */ \
4043 unixFileControl, /* xFileControl */ \
4044 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004045 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004046 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004047 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004048 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004049 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004050}; \
drh0c2694b2009-09-03 16:23:44 +00004051static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4052 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004053 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004054} \
drh0c2694b2009-09-03 16:23:44 +00004055static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004056 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004057
4058/*
4059** Here are all of the sqlite3_io_methods objects for each of the
4060** locking strategies. Functions that return pointers to these methods
4061** are also created.
4062*/
4063IOMETHODS(
4064 posixIoFinder, /* Finder function name */
4065 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004066 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004067 unixClose, /* xClose method */
4068 unixLock, /* xLock method */
4069 unixUnlock, /* xUnlock method */
4070 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004071)
drh7708e972008-11-29 00:56:52 +00004072IOMETHODS(
4073 nolockIoFinder, /* Finder function name */
4074 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004075 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004076 nolockClose, /* xClose method */
4077 nolockLock, /* xLock method */
4078 nolockUnlock, /* xUnlock method */
4079 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004080)
drh7708e972008-11-29 00:56:52 +00004081IOMETHODS(
4082 dotlockIoFinder, /* Finder function name */
4083 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004084 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004085 dotlockClose, /* xClose method */
4086 dotlockLock, /* xLock method */
4087 dotlockUnlock, /* xUnlock method */
4088 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004089)
drh7708e972008-11-29 00:56:52 +00004090
chw78a13182009-04-07 05:35:03 +00004091#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004092IOMETHODS(
4093 flockIoFinder, /* Finder function name */
4094 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004095 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004096 flockClose, /* xClose method */
4097 flockLock, /* xLock method */
4098 flockUnlock, /* xUnlock method */
4099 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004100)
drh7708e972008-11-29 00:56:52 +00004101#endif
4102
drh6c7d5c52008-11-21 20:32:33 +00004103#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004104IOMETHODS(
4105 semIoFinder, /* Finder function name */
4106 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004107 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004108 semClose, /* xClose method */
4109 semLock, /* xLock method */
4110 semUnlock, /* xUnlock method */
4111 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004112)
aswiftaebf4132008-11-21 00:10:35 +00004113#endif
drh7708e972008-11-29 00:56:52 +00004114
drhd2cb50b2009-01-09 21:41:17 +00004115#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004116IOMETHODS(
4117 afpIoFinder, /* Finder function name */
4118 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004119 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004120 afpClose, /* xClose method */
4121 afpLock, /* xLock method */
4122 afpUnlock, /* xUnlock method */
4123 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004124)
drh715ff302008-12-03 22:32:44 +00004125#endif
4126
4127/*
4128** The proxy locking method is a "super-method" in the sense that it
4129** opens secondary file descriptors for the conch and lock files and
4130** it uses proxy, dot-file, AFP, and flock() locking methods on those
4131** secondary files. For this reason, the division that implements
4132** proxy locking is located much further down in the file. But we need
4133** to go ahead and define the sqlite3_io_methods and finder function
4134** for proxy locking here. So we forward declare the I/O methods.
4135*/
drhd2cb50b2009-01-09 21:41:17 +00004136#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004137static int proxyClose(sqlite3_file*);
4138static int proxyLock(sqlite3_file*, int);
4139static int proxyUnlock(sqlite3_file*, int);
4140static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004141IOMETHODS(
4142 proxyIoFinder, /* Finder function name */
4143 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004144 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004145 proxyClose, /* xClose method */
4146 proxyLock, /* xLock method */
4147 proxyUnlock, /* xUnlock method */
4148 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004149)
aswiftaebf4132008-11-21 00:10:35 +00004150#endif
drh7708e972008-11-29 00:56:52 +00004151
drh7ed97b92010-01-20 13:07:21 +00004152/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4153#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4154IOMETHODS(
4155 nfsIoFinder, /* Finder function name */
4156 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004157 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004158 unixClose, /* xClose method */
4159 unixLock, /* xLock method */
4160 nfsUnlock, /* xUnlock method */
4161 unixCheckReservedLock /* xCheckReservedLock method */
4162)
4163#endif
drh7708e972008-11-29 00:56:52 +00004164
drhd2cb50b2009-01-09 21:41:17 +00004165#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004166/*
drh6b9d6dd2008-12-03 19:34:47 +00004167** This "finder" function attempts to determine the best locking strategy
4168** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004169** object that implements that strategy.
4170**
4171** This is for MacOSX only.
4172*/
drh1875f7a2008-12-08 18:19:17 +00004173static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004174 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004175 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004176){
4177 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004178 const char *zFilesystem; /* Filesystem type name */
4179 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004180 } aMap[] = {
4181 { "hfs", &posixIoMethods },
4182 { "ufs", &posixIoMethods },
4183 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004184 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004185 { "webdav", &nolockIoMethods },
4186 { 0, 0 }
4187 };
4188 int i;
4189 struct statfs fsInfo;
4190 struct flock lockInfo;
4191
4192 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004193 /* If filePath==NULL that means we are dealing with a transient file
4194 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004195 return &nolockIoMethods;
4196 }
4197 if( statfs(filePath, &fsInfo) != -1 ){
4198 if( fsInfo.f_flags & MNT_RDONLY ){
4199 return &nolockIoMethods;
4200 }
4201 for(i=0; aMap[i].zFilesystem; i++){
4202 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4203 return aMap[i].pMethods;
4204 }
4205 }
4206 }
4207
4208 /* Default case. Handles, amongst others, "nfs".
4209 ** Test byte-range lock using fcntl(). If the call succeeds,
4210 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004211 */
drh7708e972008-11-29 00:56:52 +00004212 lockInfo.l_len = 1;
4213 lockInfo.l_start = 0;
4214 lockInfo.l_whence = SEEK_SET;
4215 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004216 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004217 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4218 return &nfsIoMethods;
4219 } else {
4220 return &posixIoMethods;
4221 }
drh7708e972008-11-29 00:56:52 +00004222 }else{
4223 return &dotlockIoMethods;
4224 }
4225}
drh0c2694b2009-09-03 16:23:44 +00004226static const sqlite3_io_methods
4227 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004228
drhd2cb50b2009-01-09 21:41:17 +00004229#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004230
chw78a13182009-04-07 05:35:03 +00004231#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4232/*
4233** This "finder" function attempts to determine the best locking strategy
4234** for the database file "filePath". It then returns the sqlite3_io_methods
4235** object that implements that strategy.
4236**
4237** This is for VXWorks only.
4238*/
4239static const sqlite3_io_methods *autolockIoFinderImpl(
4240 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004241 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004242){
4243 struct flock lockInfo;
4244
4245 if( !filePath ){
4246 /* If filePath==NULL that means we are dealing with a transient file
4247 ** that does not need to be locked. */
4248 return &nolockIoMethods;
4249 }
4250
4251 /* Test if fcntl() is supported and use POSIX style locks.
4252 ** Otherwise fall back to the named semaphore method.
4253 */
4254 lockInfo.l_len = 1;
4255 lockInfo.l_start = 0;
4256 lockInfo.l_whence = SEEK_SET;
4257 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004258 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004259 return &posixIoMethods;
4260 }else{
4261 return &semIoMethods;
4262 }
4263}
drh0c2694b2009-09-03 16:23:44 +00004264static const sqlite3_io_methods
4265 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004266
4267#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4268
drh7708e972008-11-29 00:56:52 +00004269/*
4270** An abstract type for a pointer to a IO method finder function:
4271*/
drh0c2694b2009-09-03 16:23:44 +00004272typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004273
aswiftaebf4132008-11-21 00:10:35 +00004274
drh734c9862008-11-28 15:37:20 +00004275/****************************************************************************
4276**************************** sqlite3_vfs methods ****************************
4277**
4278** This division contains the implementation of methods on the
4279** sqlite3_vfs object.
4280*/
4281
danielk1977a3d4c882007-03-23 10:08:38 +00004282/*
danielk1977e339d652008-06-28 11:23:00 +00004283** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004284*/
4285static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004286 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004287 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004288 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004289 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004290 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004291 int noLock, /* Omit locking if true */
4292 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004293){
drh7708e972008-11-29 00:56:52 +00004294 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004295 unixFile *pNew = (unixFile *)pId;
4296 int rc = SQLITE_OK;
4297
drh8af6c222010-05-14 12:43:01 +00004298 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004299
dane946c392009-08-22 11:39:46 +00004300 /* Parameter isDelete is only used on vxworks. Express this explicitly
4301 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004302 */
drh7708e972008-11-29 00:56:52 +00004303 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004304
dan00157392010-10-05 11:33:15 +00004305 /* Usually the path zFilename should not be a relative pathname. The
4306 ** exception is when opening the proxy "conch" file in builds that
4307 ** include the special Apple locking styles.
4308 */
dan00157392010-10-05 11:33:15 +00004309#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004310 assert( zFilename==0 || zFilename[0]=='/'
4311 || pVfs->pAppData==(void*)&autolockIoFinder );
4312#else
4313 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004314#endif
dan00157392010-10-05 11:33:15 +00004315
drh308c2a52010-05-14 11:30:18 +00004316 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004317 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004318 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004319 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004320 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004321
drh6c7d5c52008-11-21 20:32:33 +00004322#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004323 pNew->pId = vxworksFindFileId(zFilename);
4324 if( pNew->pId==0 ){
4325 noLock = 1;
4326 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004327 }
4328#endif
4329
drhda0e7682008-07-30 15:27:54 +00004330 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004331 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004332 }else{
drh0c2694b2009-09-03 16:23:44 +00004333 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004334#if SQLITE_ENABLE_LOCKING_STYLE
4335 /* Cache zFilename in the locking context (AFP and dotlock override) for
4336 ** proxyLock activation is possible (remote proxy is based on db name)
4337 ** zFilename remains valid until file is closed, to support */
4338 pNew->lockingContext = (void*)zFilename;
4339#endif
drhda0e7682008-07-30 15:27:54 +00004340 }
danielk1977e339d652008-06-28 11:23:00 +00004341
drh7ed97b92010-01-20 13:07:21 +00004342 if( pLockingStyle == &posixIoMethods
4343#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4344 || pLockingStyle == &nfsIoMethods
4345#endif
4346 ){
drh7708e972008-11-29 00:56:52 +00004347 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004348 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004349 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004350 /* If an error occured in findInodeInfo(), close the file descriptor
4351 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004352 ** in two scenarios:
4353 **
4354 ** (a) A call to fstat() failed.
4355 ** (b) A malloc failed.
4356 **
4357 ** Scenario (b) may only occur if the process is holding no other
4358 ** file descriptors open on the same file. If there were other file
4359 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004360 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004361 ** handle h - as it is guaranteed that no posix locks will be released
4362 ** by doing so.
4363 **
4364 ** If scenario (a) caused the error then things are not so safe. The
4365 ** implicit assumption here is that if fstat() fails, things are in
4366 ** such bad shape that dropping a lock or two doesn't matter much.
4367 */
drh0e9365c2011-03-02 02:08:13 +00004368 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004369 h = -1;
4370 }
drh7708e972008-11-29 00:56:52 +00004371 unixLeaveMutex();
4372 }
danielk1977e339d652008-06-28 11:23:00 +00004373
drhd2cb50b2009-01-09 21:41:17 +00004374#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004375 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004376 /* AFP locking uses the file path so it needs to be included in
4377 ** the afpLockingContext.
4378 */
4379 afpLockingContext *pCtx;
4380 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4381 if( pCtx==0 ){
4382 rc = SQLITE_NOMEM;
4383 }else{
4384 /* NB: zFilename exists and remains valid until the file is closed
4385 ** according to requirement F11141. So we do not need to make a
4386 ** copy of the filename. */
4387 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004388 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004389 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004390 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004391 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004392 if( rc!=SQLITE_OK ){
4393 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004394 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004395 h = -1;
4396 }
drh7708e972008-11-29 00:56:52 +00004397 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004398 }
drh7708e972008-11-29 00:56:52 +00004399 }
4400#endif
danielk1977e339d652008-06-28 11:23:00 +00004401
drh7708e972008-11-29 00:56:52 +00004402 else if( pLockingStyle == &dotlockIoMethods ){
4403 /* Dotfile locking uses the file path so it needs to be included in
4404 ** the dotlockLockingContext
4405 */
4406 char *zLockFile;
4407 int nFilename;
drhea678832008-12-10 19:26:22 +00004408 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004409 zLockFile = (char *)sqlite3_malloc(nFilename);
4410 if( zLockFile==0 ){
4411 rc = SQLITE_NOMEM;
4412 }else{
4413 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004414 }
drh7708e972008-11-29 00:56:52 +00004415 pNew->lockingContext = zLockFile;
4416 }
danielk1977e339d652008-06-28 11:23:00 +00004417
drh6c7d5c52008-11-21 20:32:33 +00004418#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004419 else if( pLockingStyle == &semIoMethods ){
4420 /* Named semaphore locking uses the file path so it needs to be
4421 ** included in the semLockingContext
4422 */
4423 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004424 rc = findInodeInfo(pNew, &pNew->pInode);
4425 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4426 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004427 int n;
drh2238dcc2009-08-27 17:56:20 +00004428 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004429 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004430 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004431 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004432 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4433 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004434 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004435 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004436 }
chw97185482008-11-17 08:05:31 +00004437 }
drh7708e972008-11-29 00:56:52 +00004438 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004439 }
drh7708e972008-11-29 00:56:52 +00004440#endif
aswift5b1a2562008-08-22 00:22:35 +00004441
4442 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004443#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004444 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004445 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004446 h = -1;
chw97185482008-11-17 08:05:31 +00004447 unlink(zFilename);
4448 isDelete = 0;
4449 }
4450 pNew->isDelete = isDelete;
4451#endif
danielk1977e339d652008-06-28 11:23:00 +00004452 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004453 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4454 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004455 }else{
drh7708e972008-11-29 00:56:52 +00004456 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004457 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004458 }
danielk1977e339d652008-06-28 11:23:00 +00004459 return rc;
drh054889e2005-11-30 03:20:31 +00004460}
drh9c06c952005-11-26 00:25:00 +00004461
danielk1977ad94b582007-08-20 06:44:22 +00004462/*
4463** Open a file descriptor to the directory containing file zFilename.
4464** If successful, *pFd is set to the opened file descriptor and
4465** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4466** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4467** value.
4468**
4469** If SQLITE_OK is returned, the caller is responsible for closing
4470** the file descriptor *pFd using close().
4471*/
danielk1977fee2d252007-08-18 10:59:19 +00004472static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004473 int ii;
drh777b17a2007-09-20 10:02:54 +00004474 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004475 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004476
drh153c62c2007-08-24 03:51:33 +00004477 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004478 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004479 if( ii>0 ){
4480 zDirname[ii] = '\0';
drh99ab3b12011-03-02 15:09:07 +00004481 fd = osOpen(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004482 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004483#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004484 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004485#endif
drh308c2a52010-05-14 11:30:18 +00004486 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004487 }
4488 }
danielk1977fee2d252007-08-18 10:59:19 +00004489 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004490 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004491}
4492
danielk1977b4b47412007-08-17 15:53:36 +00004493/*
drh8b3cf822010-06-01 21:02:51 +00004494** Return the name of a directory in which to put temporary files.
4495** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004496*/
drh7234c6d2010-06-19 15:10:09 +00004497static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004498 static const char *azDirs[] = {
4499 0,
aswiftaebf4132008-11-21 00:10:35 +00004500 0,
danielk197717b90b52008-06-06 11:11:25 +00004501 "/var/tmp",
4502 "/usr/tmp",
4503 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004504 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004505 };
drh8b3cf822010-06-01 21:02:51 +00004506 unsigned int i;
4507 struct stat buf;
4508 const char *zDir = 0;
4509
4510 azDirs[0] = sqlite3_temp_directory;
4511 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004512 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004513 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004514 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004515 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004516 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004517 break;
4518 }
4519 return zDir;
4520}
4521
4522/*
4523** Create a temporary file name in zBuf. zBuf must be allocated
4524** by the calling process and must be big enough to hold at least
4525** pVfs->mxPathname bytes.
4526*/
4527static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004528 static const unsigned char zChars[] =
4529 "abcdefghijklmnopqrstuvwxyz"
4530 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4531 "0123456789";
drh41022642008-11-21 00:24:42 +00004532 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004533 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004534
4535 /* It's odd to simulate an io-error here, but really this is just
4536 ** using the io-error infrastructure to test that SQLite handles this
4537 ** function failing.
4538 */
4539 SimulateIOError( return SQLITE_IOERR );
4540
drh7234c6d2010-06-19 15:10:09 +00004541 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004542 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004543
4544 /* Check that the output buffer is large enough for the temporary file
4545 ** name. If it is not, return SQLITE_ERROR.
4546 */
danielk197700e13612008-11-17 19:18:54 +00004547 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004548 return SQLITE_ERROR;
4549 }
4550
4551 do{
4552 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004553 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004554 sqlite3_randomness(15, &zBuf[j]);
4555 for(i=0; i<15; i++, j++){
4556 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4557 }
4558 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004559 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004560 return SQLITE_OK;
4561}
4562
drhd2cb50b2009-01-09 21:41:17 +00004563#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004564/*
4565** Routine to transform a unixFile into a proxy-locking unixFile.
4566** Implementation in the proxy-lock division, but used by unixOpen()
4567** if SQLITE_PREFER_PROXY_LOCKING is defined.
4568*/
4569static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004570#endif
drhc66d5b62008-12-03 22:48:32 +00004571
dan08da86a2009-08-21 17:18:03 +00004572/*
4573** Search for an unused file descriptor that was opened on the database
4574** file (not a journal or master-journal file) identified by pathname
4575** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4576** argument to this function.
4577**
4578** Such a file descriptor may exist if a database connection was closed
4579** but the associated file descriptor could not be closed because some
4580** other file descriptor open on the same file is holding a file-lock.
4581** Refer to comments in the unixClose() function and the lengthy comment
4582** describing "Posix Advisory Locking" at the start of this file for
4583** further details. Also, ticket #4018.
4584**
4585** If a suitable file descriptor is found, then it is returned. If no
4586** such file descriptor is located, -1 is returned.
4587*/
dane946c392009-08-22 11:39:46 +00004588static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4589 UnixUnusedFd *pUnused = 0;
4590
4591 /* Do not search for an unused file descriptor on vxworks. Not because
4592 ** vxworks would not benefit from the change (it might, we're not sure),
4593 ** but because no way to test it is currently available. It is better
4594 ** not to risk breaking vxworks support for the sake of such an obscure
4595 ** feature. */
4596#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004597 struct stat sStat; /* Results of stat() call */
4598
4599 /* A stat() call may fail for various reasons. If this happens, it is
4600 ** almost certain that an open() call on the same path will also fail.
4601 ** For this reason, if an error occurs in the stat() call here, it is
4602 ** ignored and -1 is returned. The caller will try to open a new file
4603 ** descriptor on the same path, fail, and return an error to SQLite.
4604 **
4605 ** Even if a subsequent open() call does succeed, the consequences of
4606 ** not searching for a resusable file descriptor are not dire. */
4607 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004608 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004609
4610 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004611 pInode = inodeList;
4612 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4613 || pInode->fileId.ino!=sStat.st_ino) ){
4614 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004615 }
drh8af6c222010-05-14 12:43:01 +00004616 if( pInode ){
dane946c392009-08-22 11:39:46 +00004617 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004618 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004619 pUnused = *pp;
4620 if( pUnused ){
4621 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004622 }
4623 }
4624 unixLeaveMutex();
4625 }
dane946c392009-08-22 11:39:46 +00004626#endif /* if !OS_VXWORKS */
4627 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004628}
danielk197717b90b52008-06-06 11:11:25 +00004629
4630/*
danddb0ac42010-07-14 14:48:58 +00004631** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004632** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004633** and a value suitable for passing as the third argument to open(2) is
4634** written to *pMode. If an IO error occurs, an SQLite error code is
4635** returned and the value of *pMode is not modified.
4636**
4637** If the file being opened is a temporary file, it is always created with
4638** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004639** is a database or master journal file, it is created with the permissions
4640** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004641**
drh8ab58662010-07-15 18:38:39 +00004642** Finally, if the file being opened is a WAL or regular journal file, then
4643** this function queries the file-system for the permissions on the
4644** corresponding database file and sets *pMode to this value. Whenever
4645** possible, WAL and journal files are created using the same permissions
4646** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004647*/
4648static int findCreateFileMode(
4649 const char *zPath, /* Path of file (possibly) being created */
4650 int flags, /* Flags passed as 4th argument to xOpen() */
4651 mode_t *pMode /* OUT: Permissions to open file with */
4652){
4653 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004654 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004655 char zDb[MAX_PATHNAME+1]; /* Database file path */
4656 int nDb; /* Number of valid bytes in zDb */
4657 struct stat sStat; /* Output of stat() on database file */
4658
dana0c989d2010-11-05 18:07:37 +00004659 /* zPath is a path to a WAL or journal file. The following block derives
4660 ** the path to the associated database file from zPath. This block handles
4661 ** the following naming conventions:
4662 **
4663 ** "<path to db>-journal"
4664 ** "<path to db>-wal"
4665 ** "<path to db>-journal-NNNN"
4666 ** "<path to db>-wal-NNNN"
4667 **
4668 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4669 ** used by the test_multiplex.c module.
4670 */
4671 nDb = sqlite3Strlen30(zPath) - 1;
4672 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4673 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004674 memcpy(zDb, zPath, nDb);
4675 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004676
danddb0ac42010-07-14 14:48:58 +00004677 if( 0==stat(zDb, &sStat) ){
4678 *pMode = sStat.st_mode & 0777;
4679 }else{
4680 rc = SQLITE_IOERR_FSTAT;
4681 }
4682 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4683 *pMode = 0600;
4684 }else{
4685 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4686 }
4687 return rc;
4688}
4689
4690/*
danielk1977ad94b582007-08-20 06:44:22 +00004691** Open the file zPath.
4692**
danielk1977b4b47412007-08-17 15:53:36 +00004693** Previously, the SQLite OS layer used three functions in place of this
4694** one:
4695**
4696** sqlite3OsOpenReadWrite();
4697** sqlite3OsOpenReadOnly();
4698** sqlite3OsOpenExclusive();
4699**
4700** These calls correspond to the following combinations of flags:
4701**
4702** ReadWrite() -> (READWRITE | CREATE)
4703** ReadOnly() -> (READONLY)
4704** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4705**
4706** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4707** true, the file was configured to be automatically deleted when the
4708** file handle closed. To achieve the same effect using this new
4709** interface, add the DELETEONCLOSE flag to those specified above for
4710** OpenExclusive().
4711*/
4712static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004713 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4714 const char *zPath, /* Pathname of file to be opened */
4715 sqlite3_file *pFile, /* The file descriptor to be filled in */
4716 int flags, /* Input flags to control the opening */
4717 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004718){
dan08da86a2009-08-21 17:18:03 +00004719 unixFile *p = (unixFile *)pFile;
4720 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004721 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004722 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004723 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004724 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004725 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004726
4727 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4728 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4729 int isCreate = (flags & SQLITE_OPEN_CREATE);
4730 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4731 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004732#if SQLITE_ENABLE_LOCKING_STYLE
4733 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4734#endif
danielk1977b4b47412007-08-17 15:53:36 +00004735
danielk1977fee2d252007-08-18 10:59:19 +00004736 /* If creating a master or main-file journal, this function will open
4737 ** a file-descriptor on the directory too. The first time unixSync()
4738 ** is called the directory file descriptor will be fsync()ed and close()d.
4739 */
danddb0ac42010-07-14 14:48:58 +00004740 int isOpenDirectory = (isCreate && (
4741 eType==SQLITE_OPEN_MASTER_JOURNAL
4742 || eType==SQLITE_OPEN_MAIN_JOURNAL
4743 || eType==SQLITE_OPEN_WAL
4744 ));
danielk1977fee2d252007-08-18 10:59:19 +00004745
danielk197717b90b52008-06-06 11:11:25 +00004746 /* If argument zPath is a NULL pointer, this function is required to open
4747 ** a temporary file. Use this buffer to store the file name in.
4748 */
4749 char zTmpname[MAX_PATHNAME+1];
4750 const char *zName = zPath;
4751
danielk1977fee2d252007-08-18 10:59:19 +00004752 /* Check the following statements are true:
4753 **
4754 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4755 ** (b) if CREATE is set, then READWRITE must also be set, and
4756 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004757 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004758 */
danielk1977b4b47412007-08-17 15:53:36 +00004759 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004760 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004761 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004762 assert(isDelete==0 || isCreate);
4763
danddb0ac42010-07-14 14:48:58 +00004764 /* The main DB, main journal, WAL file and master journal are never
4765 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004766 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4767 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4768 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004769 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004770
danielk1977fee2d252007-08-18 10:59:19 +00004771 /* Assert that the upper layer has set one of the "file-type" flags. */
4772 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4773 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4774 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004775 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004776 );
4777
dan08da86a2009-08-21 17:18:03 +00004778 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004779
dan08da86a2009-08-21 17:18:03 +00004780 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004781 UnixUnusedFd *pUnused;
4782 pUnused = findReusableFd(zName, flags);
4783 if( pUnused ){
4784 fd = pUnused->fd;
4785 }else{
dan6aa657f2009-08-24 18:57:58 +00004786 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004787 if( !pUnused ){
4788 return SQLITE_NOMEM;
4789 }
4790 }
4791 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004792 }else if( !zName ){
4793 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004794 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004795 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004796 if( rc!=SQLITE_OK ){
4797 return rc;
4798 }
4799 zName = zTmpname;
4800 }
4801
dan08da86a2009-08-21 17:18:03 +00004802 /* Determine the value of the flags parameter passed to POSIX function
4803 ** open(). These must be calculated even if open() is not called, as
4804 ** they may be stored as part of the file handle and used by the
4805 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004806 if( isReadonly ) openFlags |= O_RDONLY;
4807 if( isReadWrite ) openFlags |= O_RDWR;
4808 if( isCreate ) openFlags |= O_CREAT;
4809 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4810 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004811
danielk1977b4b47412007-08-17 15:53:36 +00004812 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004813 mode_t openMode; /* Permissions to create file with */
4814 rc = findCreateFileMode(zName, flags, &openMode);
4815 if( rc!=SQLITE_OK ){
4816 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004817 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004818 return rc;
4819 }
drh99ab3b12011-03-02 15:09:07 +00004820 fd = osOpen(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004821 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004822 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4823 /* Failed to open the file for read/write access. Try read-only. */
4824 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004825 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004826 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004827 openFlags |= O_RDONLY;
drh99ab3b12011-03-02 15:09:07 +00004828 fd = osOpen(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004829 }
4830 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004831 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004832 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004833 }
danielk1977b4b47412007-08-17 15:53:36 +00004834 }
dan08da86a2009-08-21 17:18:03 +00004835 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004836 if( pOutFlags ){
4837 *pOutFlags = flags;
4838 }
4839
dane946c392009-08-22 11:39:46 +00004840 if( p->pUnused ){
4841 p->pUnused->fd = fd;
4842 p->pUnused->flags = flags;
4843 }
4844
danielk1977b4b47412007-08-17 15:53:36 +00004845 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004846#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004847 zPath = zName;
4848#else
danielk197717b90b52008-06-06 11:11:25 +00004849 unlink(zName);
chw97185482008-11-17 08:05:31 +00004850#endif
danielk1977b4b47412007-08-17 15:53:36 +00004851 }
drh41022642008-11-21 00:24:42 +00004852#if SQLITE_ENABLE_LOCKING_STYLE
4853 else{
dan08da86a2009-08-21 17:18:03 +00004854 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004855 }
4856#endif
4857
danielk1977fee2d252007-08-18 10:59:19 +00004858 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004859 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004860 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004861 /* It is safe to close fd at this point, because it is guaranteed not
4862 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004863 ** it would not be safe to close as this would release any locks held
4864 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004865 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00004866 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004867 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004868 }
4869 }
danielk1977e339d652008-06-28 11:23:00 +00004870
4871#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004872 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00004873#endif
4874
drhda0e7682008-07-30 15:27:54 +00004875 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004876
drh7ed97b92010-01-20 13:07:21 +00004877
4878#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4879 struct statfs fsInfo;
4880 if( fstatfs(fd, &fsInfo) == -1 ){
4881 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00004882 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
4883 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004884 return SQLITE_IOERR_ACCESS;
4885 }
4886 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4887 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4888 }
4889#endif
4890
4891#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004892#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004893 isAutoProxy = 1;
4894#endif
4895 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004896 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4897 int useProxy = 0;
4898
dan08da86a2009-08-21 17:18:03 +00004899 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4900 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004901 if( envforce!=NULL ){
4902 useProxy = atoi(envforce)>0;
4903 }else{
4904 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004905 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004906 /* In theory, the close(fd) call is sub-optimal. If the file opened
4907 ** with fd is a database file, and there are other connections open
4908 ** on that file that are currently holding advisory locks on it,
4909 ** then the call to close() will cancel those locks. In practice,
4910 ** we're assuming that statfs() doesn't fail very often. At least
4911 ** not while other file descriptors opened by the same process on
4912 ** the same file are working. */
4913 p->lastErrno = errno;
4914 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00004915 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00004916 }
drh0e9365c2011-03-02 02:08:13 +00004917 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004918 rc = SQLITE_IOERR_ACCESS;
4919 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004920 }
4921 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4922 }
4923 if( useProxy ){
4924 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4925 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004926 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004927 if( rc!=SQLITE_OK ){
4928 /* Use unixClose to clean up the resources added in fillInUnixFile
4929 ** and clear all the structure's references. Specifically,
4930 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4931 */
4932 unixClose(pFile);
4933 return rc;
4934 }
aswiftaebf4132008-11-21 00:10:35 +00004935 }
dane946c392009-08-22 11:39:46 +00004936 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004937 }
4938 }
4939#endif
4940
dane946c392009-08-22 11:39:46 +00004941 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4942open_finished:
4943 if( rc!=SQLITE_OK ){
4944 sqlite3_free(p->pUnused);
4945 }
4946 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004947}
4948
dane946c392009-08-22 11:39:46 +00004949
danielk1977b4b47412007-08-17 15:53:36 +00004950/*
danielk1977fee2d252007-08-18 10:59:19 +00004951** Delete the file at zPath. If the dirSync argument is true, fsync()
4952** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004953*/
drh6b9d6dd2008-12-03 19:34:47 +00004954static int unixDelete(
4955 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4956 const char *zPath, /* Name of file to be deleted */
4957 int dirSync /* If true, fsync() directory after deleting file */
4958){
danielk1977fee2d252007-08-18 10:59:19 +00004959 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004960 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004961 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004962 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00004963 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00004964 }
danielk1977d39fa702008-10-16 13:27:40 +00004965#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004966 if( dirSync ){
4967 int fd;
4968 rc = openDirectory(zPath, &fd);
4969 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004970#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004971 if( fsync(fd)==-1 )
4972#else
4973 if( fsync(fd) )
4974#endif
4975 {
dane18d4952011-02-21 11:46:24 +00004976 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00004977 }
drh0e9365c2011-03-02 02:08:13 +00004978 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00004979 }
4980 }
danielk1977d138dd82008-10-15 16:02:48 +00004981#endif
danielk1977fee2d252007-08-18 10:59:19 +00004982 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004983}
4984
danielk197790949c22007-08-17 16:50:38 +00004985/*
4986** Test the existance of or access permissions of file zPath. The
4987** test performed depends on the value of flags:
4988**
4989** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4990** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4991** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4992**
4993** Otherwise return 0.
4994*/
danielk1977861f7452008-06-05 11:39:11 +00004995static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004996 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4997 const char *zPath, /* Path of the file to examine */
4998 int flags, /* What do we want to learn about the zPath file? */
4999 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005000){
rse25c0d1a2007-09-20 08:38:14 +00005001 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005002 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005003 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005004 switch( flags ){
5005 case SQLITE_ACCESS_EXISTS:
5006 amode = F_OK;
5007 break;
5008 case SQLITE_ACCESS_READWRITE:
5009 amode = W_OK|R_OK;
5010 break;
drh50d3f902007-08-27 21:10:36 +00005011 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005012 amode = R_OK;
5013 break;
5014
5015 default:
5016 assert(!"Invalid flags argument");
5017 }
drh99ab3b12011-03-02 15:09:07 +00005018 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005019 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5020 struct stat buf;
5021 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5022 *pResOut = 0;
5023 }
5024 }
danielk1977861f7452008-06-05 11:39:11 +00005025 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005026}
5027
danielk1977b4b47412007-08-17 15:53:36 +00005028
5029/*
5030** Turn a relative pathname into a full pathname. The relative path
5031** is stored as a nul-terminated string in the buffer pointed to by
5032** zPath.
5033**
5034** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5035** (in this case, MAX_PATHNAME bytes). The full-path is written to
5036** this buffer before returning.
5037*/
danielk1977adfb9b02007-09-17 07:02:56 +00005038static int unixFullPathname(
5039 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5040 const char *zPath, /* Possibly relative input path */
5041 int nOut, /* Size of output buffer in bytes */
5042 char *zOut /* Output buffer */
5043){
danielk1977843e65f2007-09-01 16:16:15 +00005044
5045 /* It's odd to simulate an io-error here, but really this is just
5046 ** using the io-error infrastructure to test that SQLite handles this
5047 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005048 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005049 */
5050 SimulateIOError( return SQLITE_ERROR );
5051
drh153c62c2007-08-24 03:51:33 +00005052 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005053 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005054
drh3c7f2dc2007-12-06 13:26:20 +00005055 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005056 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005057 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005058 }else{
5059 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005060 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005061 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005062 }
drhea678832008-12-10 19:26:22 +00005063 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005064 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005065 }
5066 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005067}
5068
drh0ccebe72005-06-07 22:22:50 +00005069
drh761df872006-12-21 01:29:22 +00005070#ifndef SQLITE_OMIT_LOAD_EXTENSION
5071/*
5072** Interfaces for opening a shared library, finding entry points
5073** within the shared library, and closing the shared library.
5074*/
5075#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005076static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5077 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005078 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5079}
danielk197795c8a542007-09-01 06:51:27 +00005080
5081/*
5082** SQLite calls this function immediately after a call to unixDlSym() or
5083** unixDlOpen() fails (returns a null pointer). If a more detailed error
5084** message is available, it is written to zBufOut. If no error message
5085** is available, zBufOut is left unmodified and SQLite uses a default
5086** error message.
5087*/
danielk1977397d65f2008-11-19 11:35:39 +00005088static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005089 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005090 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005091 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005092 zErr = dlerror();
5093 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005094 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005095 }
drh6c7d5c52008-11-21 20:32:33 +00005096 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005097}
drh1875f7a2008-12-08 18:19:17 +00005098static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5099 /*
5100 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5101 ** cast into a pointer to a function. And yet the library dlsym() routine
5102 ** returns a void* which is really a pointer to a function. So how do we
5103 ** use dlsym() with -pedantic-errors?
5104 **
5105 ** Variable x below is defined to be a pointer to a function taking
5106 ** parameters void* and const char* and returning a pointer to a function.
5107 ** We initialize x by assigning it a pointer to the dlsym() function.
5108 ** (That assignment requires a cast.) Then we call the function that
5109 ** x points to.
5110 **
5111 ** This work-around is unlikely to work correctly on any system where
5112 ** you really cannot cast a function pointer into void*. But then, on the
5113 ** other hand, dlsym() will not work on such a system either, so we have
5114 ** not really lost anything.
5115 */
5116 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005117 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005118 x = (void(*(*)(void*,const char*))(void))dlsym;
5119 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005120}
danielk1977397d65f2008-11-19 11:35:39 +00005121static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5122 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005123 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005124}
danielk1977b4b47412007-08-17 15:53:36 +00005125#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5126 #define unixDlOpen 0
5127 #define unixDlError 0
5128 #define unixDlSym 0
5129 #define unixDlClose 0
5130#endif
5131
5132/*
danielk197790949c22007-08-17 16:50:38 +00005133** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005134*/
danielk1977397d65f2008-11-19 11:35:39 +00005135static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5136 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005137 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005138
drhbbd42a62004-05-22 17:41:58 +00005139 /* We have to initialize zBuf to prevent valgrind from reporting
5140 ** errors. The reports issued by valgrind are incorrect - we would
5141 ** prefer that the randomness be increased by making use of the
5142 ** uninitialized space in zBuf - but valgrind errors tend to worry
5143 ** some users. Rather than argue, it seems easier just to initialize
5144 ** the whole array and silence valgrind, even if that means less randomness
5145 ** in the random seed.
5146 **
5147 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005148 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005149 ** tests repeatable.
5150 */
danielk1977b4b47412007-08-17 15:53:36 +00005151 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005152#if !defined(SQLITE_TEST)
5153 {
drh842b8642005-01-21 17:53:17 +00005154 int pid, fd;
drh99ab3b12011-03-02 15:09:07 +00005155 fd = osOpen("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005156 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005157 time_t t;
5158 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005159 memcpy(zBuf, &t, sizeof(t));
5160 pid = getpid();
5161 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005162 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005163 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005164 }else{
drhe562be52011-03-02 18:01:10 +00005165 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005166 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005167 }
drhbbd42a62004-05-22 17:41:58 +00005168 }
5169#endif
drh72cbd072008-10-14 17:58:38 +00005170 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005171}
5172
danielk1977b4b47412007-08-17 15:53:36 +00005173
drhbbd42a62004-05-22 17:41:58 +00005174/*
5175** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005176** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005177** The return value is the number of microseconds of sleep actually
5178** requested from the underlying operating system, a number which
5179** might be greater than or equal to the argument, but not less
5180** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005181*/
danielk1977397d65f2008-11-19 11:35:39 +00005182static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005183#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005184 struct timespec sp;
5185
5186 sp.tv_sec = microseconds / 1000000;
5187 sp.tv_nsec = (microseconds % 1000000) * 1000;
5188 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005189 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005190 return microseconds;
5191#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005192 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005193 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005194 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005195#else
danielk1977b4b47412007-08-17 15:53:36 +00005196 int seconds = (microseconds+999999)/1000000;
5197 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005198 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005199 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005200#endif
drh88f474a2006-01-02 20:00:12 +00005201}
5202
5203/*
drh6b9d6dd2008-12-03 19:34:47 +00005204** The following variable, if set to a non-zero value, is interpreted as
5205** the number of seconds since 1970 and is used to set the result of
5206** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005207*/
5208#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005209int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005210#endif
5211
5212/*
drhb7e8ea22010-05-03 14:32:30 +00005213** Find the current time (in Universal Coordinated Time). Write into *piNow
5214** the current time and date as a Julian Day number times 86_400_000. In
5215** other words, write into *piNow the number of milliseconds since the Julian
5216** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5217** proleptic Gregorian calendar.
5218**
5219** On success, return 0. Return 1 if the time and date cannot be found.
5220*/
5221static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5222 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5223#if defined(NO_GETTOD)
5224 time_t t;
5225 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005226 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005227#elif OS_VXWORKS
5228 struct timespec sNow;
5229 clock_gettime(CLOCK_REALTIME, &sNow);
5230 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5231#else
5232 struct timeval sNow;
5233 gettimeofday(&sNow, 0);
5234 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5235#endif
5236
5237#ifdef SQLITE_TEST
5238 if( sqlite3_current_time ){
5239 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5240 }
5241#endif
5242 UNUSED_PARAMETER(NotUsed);
5243 return 0;
5244}
5245
5246/*
drhbbd42a62004-05-22 17:41:58 +00005247** Find the current time (in Universal Coordinated Time). Write the
5248** current time and date as a Julian Day number into *prNow and
5249** return 0. Return 1 if the time and date cannot be found.
5250*/
danielk1977397d65f2008-11-19 11:35:39 +00005251static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005252 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005253 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005254 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005255 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005256 return 0;
5257}
danielk1977b4b47412007-08-17 15:53:36 +00005258
drh6b9d6dd2008-12-03 19:34:47 +00005259/*
5260** We added the xGetLastError() method with the intention of providing
5261** better low-level error messages when operating-system problems come up
5262** during SQLite operation. But so far, none of that has been implemented
5263** in the core. So this routine is never called. For now, it is merely
5264** a place-holder.
5265*/
danielk1977397d65f2008-11-19 11:35:39 +00005266static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5267 UNUSED_PARAMETER(NotUsed);
5268 UNUSED_PARAMETER(NotUsed2);
5269 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005270 return 0;
5271}
5272
drhf2424c52010-04-26 00:04:55 +00005273
5274/*
drh734c9862008-11-28 15:37:20 +00005275************************ End of sqlite3_vfs methods ***************************
5276******************************************************************************/
5277
drh715ff302008-12-03 22:32:44 +00005278/******************************************************************************
5279************************** Begin Proxy Locking ********************************
5280**
5281** Proxy locking is a "uber-locking-method" in this sense: It uses the
5282** other locking methods on secondary lock files. Proxy locking is a
5283** meta-layer over top of the primitive locking implemented above. For
5284** this reason, the division that implements of proxy locking is deferred
5285** until late in the file (here) after all of the other I/O methods have
5286** been defined - so that the primitive locking methods are available
5287** as services to help with the implementation of proxy locking.
5288**
5289****
5290**
5291** The default locking schemes in SQLite use byte-range locks on the
5292** database file to coordinate safe, concurrent access by multiple readers
5293** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5294** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5295** as POSIX read & write locks over fixed set of locations (via fsctl),
5296** on AFP and SMB only exclusive byte-range locks are available via fsctl
5297** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5298** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5299** address in the shared range is taken for a SHARED lock, the entire
5300** shared range is taken for an EXCLUSIVE lock):
5301**
5302** PENDING_BYTE 0x40000000
5303** RESERVED_BYTE 0x40000001
5304** SHARED_RANGE 0x40000002 -> 0x40000200
5305**
5306** This works well on the local file system, but shows a nearly 100x
5307** slowdown in read performance on AFP because the AFP client disables
5308** the read cache when byte-range locks are present. Enabling the read
5309** cache exposes a cache coherency problem that is present on all OS X
5310** supported network file systems. NFS and AFP both observe the
5311** close-to-open semantics for ensuring cache coherency
5312** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5313** address the requirements for concurrent database access by multiple
5314** readers and writers
5315** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5316**
5317** To address the performance and cache coherency issues, proxy file locking
5318** changes the way database access is controlled by limiting access to a
5319** single host at a time and moving file locks off of the database file
5320** and onto a proxy file on the local file system.
5321**
5322**
5323** Using proxy locks
5324** -----------------
5325**
5326** C APIs
5327**
5328** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5329** <proxy_path> | ":auto:");
5330** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5331**
5332**
5333** SQL pragmas
5334**
5335** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5336** PRAGMA [database.]lock_proxy_file
5337**
5338** Specifying ":auto:" means that if there is a conch file with a matching
5339** host ID in it, the proxy path in the conch file will be used, otherwise
5340** a proxy path based on the user's temp dir
5341** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5342** actual proxy file name is generated from the name and path of the
5343** database file. For example:
5344**
5345** For database path "/Users/me/foo.db"
5346** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5347**
5348** Once a lock proxy is configured for a database connection, it can not
5349** be removed, however it may be switched to a different proxy path via
5350** the above APIs (assuming the conch file is not being held by another
5351** connection or process).
5352**
5353**
5354** How proxy locking works
5355** -----------------------
5356**
5357** Proxy file locking relies primarily on two new supporting files:
5358**
5359** * conch file to limit access to the database file to a single host
5360** at a time
5361**
5362** * proxy file to act as a proxy for the advisory locks normally
5363** taken on the database
5364**
5365** The conch file - to use a proxy file, sqlite must first "hold the conch"
5366** by taking an sqlite-style shared lock on the conch file, reading the
5367** contents and comparing the host's unique host ID (see below) and lock
5368** proxy path against the values stored in the conch. The conch file is
5369** stored in the same directory as the database file and the file name
5370** is patterned after the database file name as ".<databasename>-conch".
5371** If the conch file does not exist, or it's contents do not match the
5372** host ID and/or proxy path, then the lock is escalated to an exclusive
5373** lock and the conch file contents is updated with the host ID and proxy
5374** path and the lock is downgraded to a shared lock again. If the conch
5375** is held by another process (with a shared lock), the exclusive lock
5376** will fail and SQLITE_BUSY is returned.
5377**
5378** The proxy file - a single-byte file used for all advisory file locks
5379** normally taken on the database file. This allows for safe sharing
5380** of the database file for multiple readers and writers on the same
5381** host (the conch ensures that they all use the same local lock file).
5382**
drh715ff302008-12-03 22:32:44 +00005383** Requesting the lock proxy does not immediately take the conch, it is
5384** only taken when the first request to lock database file is made.
5385** This matches the semantics of the traditional locking behavior, where
5386** opening a connection to a database file does not take a lock on it.
5387** The shared lock and an open file descriptor are maintained until
5388** the connection to the database is closed.
5389**
5390** The proxy file and the lock file are never deleted so they only need
5391** to be created the first time they are used.
5392**
5393** Configuration options
5394** ---------------------
5395**
5396** SQLITE_PREFER_PROXY_LOCKING
5397**
5398** Database files accessed on non-local file systems are
5399** automatically configured for proxy locking, lock files are
5400** named automatically using the same logic as
5401** PRAGMA lock_proxy_file=":auto:"
5402**
5403** SQLITE_PROXY_DEBUG
5404**
5405** Enables the logging of error messages during host id file
5406** retrieval and creation
5407**
drh715ff302008-12-03 22:32:44 +00005408** LOCKPROXYDIR
5409**
5410** Overrides the default directory used for lock proxy files that
5411** are named automatically via the ":auto:" setting
5412**
5413** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5414**
5415** Permissions to use when creating a directory for storing the
5416** lock proxy files, only used when LOCKPROXYDIR is not set.
5417**
5418**
5419** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5420** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5421** force proxy locking to be used for every database file opened, and 0
5422** will force automatic proxy locking to be disabled for all database
5423** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5424** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5425*/
5426
5427/*
5428** Proxy locking is only available on MacOSX
5429*/
drhd2cb50b2009-01-09 21:41:17 +00005430#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005431
drh715ff302008-12-03 22:32:44 +00005432/*
5433** The proxyLockingContext has the path and file structures for the remote
5434** and local proxy files in it
5435*/
5436typedef struct proxyLockingContext proxyLockingContext;
5437struct proxyLockingContext {
5438 unixFile *conchFile; /* Open conch file */
5439 char *conchFilePath; /* Name of the conch file */
5440 unixFile *lockProxy; /* Open proxy lock file */
5441 char *lockProxyPath; /* Name of the proxy lock file */
5442 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005443 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005444 void *oldLockingContext; /* Original lockingcontext to restore on close */
5445 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5446};
5447
drh7ed97b92010-01-20 13:07:21 +00005448/*
5449** The proxy lock file path for the database at dbPath is written into lPath,
5450** which must point to valid, writable memory large enough for a maxLen length
5451** file path.
drh715ff302008-12-03 22:32:44 +00005452*/
drh715ff302008-12-03 22:32:44 +00005453static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5454 int len;
5455 int dbLen;
5456 int i;
5457
5458#ifdef LOCKPROXYDIR
5459 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5460#else
5461# ifdef _CS_DARWIN_USER_TEMP_DIR
5462 {
drh7ed97b92010-01-20 13:07:21 +00005463 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005464 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5465 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005466 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005467 }
drh7ed97b92010-01-20 13:07:21 +00005468 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005469 }
5470# else
5471 len = strlcpy(lPath, "/tmp/", maxLen);
5472# endif
5473#endif
5474
5475 if( lPath[len-1]!='/' ){
5476 len = strlcat(lPath, "/", maxLen);
5477 }
5478
5479 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005480 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005481 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005482 char c = dbPath[i];
5483 lPath[i+len] = (c=='/')?'_':c;
5484 }
5485 lPath[i+len]='\0';
5486 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005487 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005488 return SQLITE_OK;
5489}
5490
drh7ed97b92010-01-20 13:07:21 +00005491/*
5492 ** Creates the lock file and any missing directories in lockPath
5493 */
5494static int proxyCreateLockPath(const char *lockPath){
5495 int i, len;
5496 char buf[MAXPATHLEN];
5497 int start = 0;
5498
5499 assert(lockPath!=NULL);
5500 /* try to create all the intermediate directories */
5501 len = (int)strlen(lockPath);
5502 buf[0] = lockPath[0];
5503 for( i=1; i<len; i++ ){
5504 if( lockPath[i] == '/' && (i - start > 0) ){
5505 /* only mkdir if leaf dir != "." or "/" or ".." */
5506 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5507 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5508 buf[i]='\0';
5509 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5510 int err=errno;
5511 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005512 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005513 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005514 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005515 return err;
5516 }
5517 }
5518 }
5519 start=i+1;
5520 }
5521 buf[i] = lockPath[i];
5522 }
drh308c2a52010-05-14 11:30:18 +00005523 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005524 return 0;
5525}
5526
drh715ff302008-12-03 22:32:44 +00005527/*
5528** Create a new VFS file descriptor (stored in memory obtained from
5529** sqlite3_malloc) and open the file named "path" in the file descriptor.
5530**
5531** The caller is responsible not only for closing the file descriptor
5532** but also for freeing the memory associated with the file descriptor.
5533*/
drh7ed97b92010-01-20 13:07:21 +00005534static int proxyCreateUnixFile(
5535 const char *path, /* path for the new unixFile */
5536 unixFile **ppFile, /* unixFile created and returned by ref */
5537 int islockfile /* if non zero missing dirs will be created */
5538) {
5539 int fd = -1;
5540 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005541 unixFile *pNew;
5542 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005543 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005544 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005545 int terrno = 0;
5546 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005547
drh7ed97b92010-01-20 13:07:21 +00005548 /* 1. first try to open/create the file
5549 ** 2. if that fails, and this is a lock file (not-conch), try creating
5550 ** the parent directories and then try again.
5551 ** 3. if that fails, try to open the file read-only
5552 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5553 */
5554 pUnused = findReusableFd(path, openFlags);
5555 if( pUnused ){
5556 fd = pUnused->fd;
5557 }else{
5558 pUnused = sqlite3_malloc(sizeof(*pUnused));
5559 if( !pUnused ){
5560 return SQLITE_NOMEM;
5561 }
5562 }
5563 if( fd<0 ){
drh99ab3b12011-03-02 15:09:07 +00005564 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005565 terrno = errno;
5566 if( fd<0 && errno==ENOENT && islockfile ){
5567 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh99ab3b12011-03-02 15:09:07 +00005568 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005569 }
5570 }
5571 }
5572 if( fd<0 ){
5573 openFlags = O_RDONLY;
drh99ab3b12011-03-02 15:09:07 +00005574 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005575 terrno = errno;
5576 }
5577 if( fd<0 ){
5578 if( islockfile ){
5579 return SQLITE_BUSY;
5580 }
5581 switch (terrno) {
5582 case EACCES:
5583 return SQLITE_PERM;
5584 case EIO:
5585 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5586 default:
drh9978c972010-02-23 17:36:32 +00005587 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005588 }
5589 }
5590
5591 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5592 if( pNew==NULL ){
5593 rc = SQLITE_NOMEM;
5594 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005595 }
5596 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005597 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005598 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005599 pUnused->fd = fd;
5600 pUnused->flags = openFlags;
5601 pNew->pUnused = pUnused;
5602
5603 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5604 if( rc==SQLITE_OK ){
5605 *ppFile = pNew;
5606 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005607 }
drh7ed97b92010-01-20 13:07:21 +00005608end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005609 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005610 sqlite3_free(pNew);
5611 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005612 return rc;
5613}
5614
drh7ed97b92010-01-20 13:07:21 +00005615#ifdef SQLITE_TEST
5616/* simulate multiple hosts by creating unique hostid file paths */
5617int sqlite3_hostid_num = 0;
5618#endif
5619
5620#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5621
drh0ab216a2010-07-02 17:10:40 +00005622/* Not always defined in the headers as it ought to be */
5623extern int gethostuuid(uuid_t id, const struct timespec *wait);
5624
drh7ed97b92010-01-20 13:07:21 +00005625/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5626** bytes of writable memory.
5627*/
5628static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005629 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5630 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005631#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5632 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005633 {
5634 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5635 if( gethostuuid(pHostID, &timeout) ){
5636 int err = errno;
5637 if( pError ){
5638 *pError = err;
5639 }
5640 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005641 }
drh7ed97b92010-01-20 13:07:21 +00005642 }
drhe8b0c9b2010-09-25 14:13:17 +00005643#endif
drh7ed97b92010-01-20 13:07:21 +00005644#ifdef SQLITE_TEST
5645 /* simulate multiple hosts by creating unique hostid file paths */
5646 if( sqlite3_hostid_num != 0){
5647 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5648 }
5649#endif
5650
5651 return SQLITE_OK;
5652}
5653
5654/* The conch file contains the header, host id and lock file path
5655 */
5656#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5657#define PROXY_HEADERLEN 1 /* conch file header length */
5658#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5659#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5660
5661/*
5662** Takes an open conch file, copies the contents to a new path and then moves
5663** it back. The newly created file's file descriptor is assigned to the
5664** conch file structure and finally the original conch file descriptor is
5665** closed. Returns zero if successful.
5666*/
5667static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5668 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5669 unixFile *conchFile = pCtx->conchFile;
5670 char tPath[MAXPATHLEN];
5671 char buf[PROXY_MAXCONCHLEN];
5672 char *cPath = pCtx->conchFilePath;
5673 size_t readLen = 0;
5674 size_t pathLen = 0;
5675 char errmsg[64] = "";
5676 int fd = -1;
5677 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005678 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005679
5680 /* create a new path by replace the trailing '-conch' with '-break' */
5681 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5682 if( pathLen>MAXPATHLEN || pathLen<6 ||
5683 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005684 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005685 goto end_breaklock;
5686 }
5687 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005688 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005689 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005690 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005691 goto end_breaklock;
5692 }
5693 /* write it out to the temporary break file */
drh99ab3b12011-03-02 15:09:07 +00005694 fd = osOpen(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005695 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005696 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005697 goto end_breaklock;
5698 }
drhe562be52011-03-02 18:01:10 +00005699 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005700 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005701 goto end_breaklock;
5702 }
5703 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005704 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005705 goto end_breaklock;
5706 }
5707 rc = 0;
5708 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005709 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005710 conchFile->h = fd;
5711 conchFile->openFlags = O_RDWR | O_CREAT;
5712
5713end_breaklock:
5714 if( rc ){
5715 if( fd>=0 ){
5716 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005717 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005718 }
5719 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5720 }
5721 return rc;
5722}
5723
5724/* Take the requested lock on the conch file and break a stale lock if the
5725** host id matches.
5726*/
5727static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5728 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5729 unixFile *conchFile = pCtx->conchFile;
5730 int rc = SQLITE_OK;
5731 int nTries = 0;
5732 struct timespec conchModTime;
5733
5734 do {
5735 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5736 nTries ++;
5737 if( rc==SQLITE_BUSY ){
5738 /* If the lock failed (busy):
5739 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5740 * 2nd try: fail if the mod time changed or host id is different, wait
5741 * 10 sec and try again
5742 * 3rd try: break the lock unless the mod time has changed.
5743 */
5744 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005745 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005746 pFile->lastErrno = errno;
5747 return SQLITE_IOERR_LOCK;
5748 }
5749
5750 if( nTries==1 ){
5751 conchModTime = buf.st_mtimespec;
5752 usleep(500000); /* wait 0.5 sec and try the lock again*/
5753 continue;
5754 }
5755
5756 assert( nTries>1 );
5757 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5758 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5759 return SQLITE_BUSY;
5760 }
5761
5762 if( nTries==2 ){
5763 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005764 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005765 if( len<0 ){
5766 pFile->lastErrno = errno;
5767 return SQLITE_IOERR_LOCK;
5768 }
5769 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5770 /* don't break the lock if the host id doesn't match */
5771 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5772 return SQLITE_BUSY;
5773 }
5774 }else{
5775 /* don't break the lock on short read or a version mismatch */
5776 return SQLITE_BUSY;
5777 }
5778 usleep(10000000); /* wait 10 sec and try the lock again */
5779 continue;
5780 }
5781
5782 assert( nTries==3 );
5783 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5784 rc = SQLITE_OK;
5785 if( lockType==EXCLUSIVE_LOCK ){
5786 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5787 }
5788 if( !rc ){
5789 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5790 }
5791 }
5792 }
5793 } while( rc==SQLITE_BUSY && nTries<3 );
5794
5795 return rc;
5796}
5797
5798/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005799** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5800** lockPath means that the lockPath in the conch file will be used if the
5801** host IDs match, or a new lock path will be generated automatically
5802** and written to the conch file.
5803*/
5804static int proxyTakeConch(unixFile *pFile){
5805 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5806
drh7ed97b92010-01-20 13:07:21 +00005807 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005808 return SQLITE_OK;
5809 }else{
5810 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005811 uuid_t myHostID;
5812 int pError = 0;
5813 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005814 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005815 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005816 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005817 int createConch = 0;
5818 int hostIdMatch = 0;
5819 int readLen = 0;
5820 int tryOldLockPath = 0;
5821 int forceNewLockPath = 0;
5822
drh308c2a52010-05-14 11:30:18 +00005823 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5824 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005825
drh7ed97b92010-01-20 13:07:21 +00005826 rc = proxyGetHostID(myHostID, &pError);
5827 if( (rc&0xff)==SQLITE_IOERR ){
5828 pFile->lastErrno = pError;
5829 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005830 }
drh7ed97b92010-01-20 13:07:21 +00005831 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005832 if( rc!=SQLITE_OK ){
5833 goto end_takeconch;
5834 }
drh7ed97b92010-01-20 13:07:21 +00005835 /* read the existing conch file */
5836 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5837 if( readLen<0 ){
5838 /* I/O error: lastErrno set by seekAndRead */
5839 pFile->lastErrno = conchFile->lastErrno;
5840 rc = SQLITE_IOERR_READ;
5841 goto end_takeconch;
5842 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5843 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5844 /* a short read or version format mismatch means we need to create a new
5845 ** conch file.
5846 */
5847 createConch = 1;
5848 }
5849 /* if the host id matches and the lock path already exists in the conch
5850 ** we'll try to use the path there, if we can't open that path, we'll
5851 ** retry with a new auto-generated path
5852 */
5853 do { /* in case we need to try again for an :auto: named lock file */
5854
5855 if( !createConch && !forceNewLockPath ){
5856 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5857 PROXY_HOSTIDLEN);
5858 /* if the conch has data compare the contents */
5859 if( !pCtx->lockProxyPath ){
5860 /* for auto-named local lock file, just check the host ID and we'll
5861 ** use the local lock file path that's already in there
5862 */
5863 if( hostIdMatch ){
5864 size_t pathLen = (readLen - PROXY_PATHINDEX);
5865
5866 if( pathLen>=MAXPATHLEN ){
5867 pathLen=MAXPATHLEN-1;
5868 }
5869 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5870 lockPath[pathLen] = 0;
5871 tempLockPath = lockPath;
5872 tryOldLockPath = 1;
5873 /* create a copy of the lock path if the conch is taken */
5874 goto end_takeconch;
5875 }
5876 }else if( hostIdMatch
5877 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5878 readLen-PROXY_PATHINDEX)
5879 ){
5880 /* conch host and lock path match */
5881 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005882 }
drh7ed97b92010-01-20 13:07:21 +00005883 }
5884
5885 /* if the conch isn't writable and doesn't match, we can't take it */
5886 if( (conchFile->openFlags&O_RDWR) == 0 ){
5887 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005888 goto end_takeconch;
5889 }
drh7ed97b92010-01-20 13:07:21 +00005890
5891 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005892 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005893 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5894 tempLockPath = lockPath;
5895 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005896 }
drh7ed97b92010-01-20 13:07:21 +00005897
5898 /* update conch with host and path (this will fail if other process
5899 ** has a shared lock already), if the host id matches, use the big
5900 ** stick.
drh715ff302008-12-03 22:32:44 +00005901 */
drh7ed97b92010-01-20 13:07:21 +00005902 futimes(conchFile->h, NULL);
5903 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005904 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005905 /* We are trying for an exclusive lock but another thread in this
5906 ** same process is still holding a shared lock. */
5907 rc = SQLITE_BUSY;
5908 } else {
5909 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005910 }
drh715ff302008-12-03 22:32:44 +00005911 }else{
drh7ed97b92010-01-20 13:07:21 +00005912 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005913 }
drh7ed97b92010-01-20 13:07:21 +00005914 if( rc==SQLITE_OK ){
5915 char writeBuffer[PROXY_MAXCONCHLEN];
5916 int writeSize = 0;
5917
5918 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5919 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5920 if( pCtx->lockProxyPath!=NULL ){
5921 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5922 }else{
5923 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5924 }
5925 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00005926 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00005927 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5928 fsync(conchFile->h);
5929 /* If we created a new conch file (not just updated the contents of a
5930 ** valid conch file), try to match the permissions of the database
5931 */
5932 if( rc==SQLITE_OK && createConch ){
5933 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005934 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00005935 if( err==0 ){
5936 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5937 S_IROTH|S_IWOTH);
5938 /* try to match the database file R/W permissions, ignore failure */
5939#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00005940 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00005941#else
drhff812312011-02-23 13:33:46 +00005942 do{
drhe562be52011-03-02 18:01:10 +00005943 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00005944 }while( rc==(-1) && errno==EINTR );
5945 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00005946 int code = errno;
5947 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5948 cmode, code, strerror(code));
5949 } else {
5950 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5951 }
5952 }else{
5953 int code = errno;
5954 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5955 err, code, strerror(code));
5956#endif
5957 }
drh715ff302008-12-03 22:32:44 +00005958 }
5959 }
drh7ed97b92010-01-20 13:07:21 +00005960 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5961
5962 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005963 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005964 if( rc==SQLITE_OK && pFile->openFlags ){
5965 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00005966 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005967 }
5968 pFile->h = -1;
drh99ab3b12011-03-02 15:09:07 +00005969 int fd = osOpen(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00005970 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005971 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005972 if( fd>=0 ){
5973 pFile->h = fd;
5974 }else{
drh9978c972010-02-23 17:36:32 +00005975 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005976 during locking */
5977 }
5978 }
5979 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5980 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5981 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5982 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5983 /* we couldn't create the proxy lock file with the old lock file path
5984 ** so try again via auto-naming
5985 */
5986 forceNewLockPath = 1;
5987 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005988 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005989 }
5990 }
5991 if( rc==SQLITE_OK ){
5992 /* Need to make a copy of path if we extracted the value
5993 ** from the conch file or the path was allocated on the stack
5994 */
5995 if( tempLockPath ){
5996 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5997 if( !pCtx->lockProxyPath ){
5998 rc = SQLITE_NOMEM;
5999 }
6000 }
6001 }
6002 if( rc==SQLITE_OK ){
6003 pCtx->conchHeld = 1;
6004
6005 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6006 afpLockingContext *afpCtx;
6007 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6008 afpCtx->dbPath = pCtx->lockProxyPath;
6009 }
6010 } else {
6011 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6012 }
drh308c2a52010-05-14 11:30:18 +00006013 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6014 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006015 return rc;
drh308c2a52010-05-14 11:30:18 +00006016 } while (1); /* in case we need to retry the :auto: lock file -
6017 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006018 }
6019}
6020
6021/*
6022** If pFile holds a lock on a conch file, then release that lock.
6023*/
6024static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006025 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006026 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6027 unixFile *conchFile; /* Name of the conch file */
6028
6029 pCtx = (proxyLockingContext *)pFile->lockingContext;
6030 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006031 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006032 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006033 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006034 if( pCtx->conchHeld>0 ){
6035 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6036 }
drh715ff302008-12-03 22:32:44 +00006037 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006038 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6039 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006040 return rc;
6041}
6042
6043/*
6044** Given the name of a database file, compute the name of its conch file.
6045** Store the conch filename in memory obtained from sqlite3_malloc().
6046** Make *pConchPath point to the new name. Return SQLITE_OK on success
6047** or SQLITE_NOMEM if unable to obtain memory.
6048**
6049** The caller is responsible for ensuring that the allocated memory
6050** space is eventually freed.
6051**
6052** *pConchPath is set to NULL if a memory allocation error occurs.
6053*/
6054static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6055 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006056 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006057 char *conchPath; /* buffer in which to construct conch name */
6058
6059 /* Allocate space for the conch filename and initialize the name to
6060 ** the name of the original database file. */
6061 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6062 if( conchPath==0 ){
6063 return SQLITE_NOMEM;
6064 }
6065 memcpy(conchPath, dbPath, len+1);
6066
6067 /* now insert a "." before the last / character */
6068 for( i=(len-1); i>=0; i-- ){
6069 if( conchPath[i]=='/' ){
6070 i++;
6071 break;
6072 }
6073 }
6074 conchPath[i]='.';
6075 while ( i<len ){
6076 conchPath[i+1]=dbPath[i];
6077 i++;
6078 }
6079
6080 /* append the "-conch" suffix to the file */
6081 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006082 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006083
6084 return SQLITE_OK;
6085}
6086
6087
6088/* Takes a fully configured proxy locking-style unix file and switches
6089** the local lock file path
6090*/
6091static int switchLockProxyPath(unixFile *pFile, const char *path) {
6092 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6093 char *oldPath = pCtx->lockProxyPath;
6094 int rc = SQLITE_OK;
6095
drh308c2a52010-05-14 11:30:18 +00006096 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006097 return SQLITE_BUSY;
6098 }
6099
6100 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6101 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6102 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6103 return SQLITE_OK;
6104 }else{
6105 unixFile *lockProxy = pCtx->lockProxy;
6106 pCtx->lockProxy=NULL;
6107 pCtx->conchHeld = 0;
6108 if( lockProxy!=NULL ){
6109 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6110 if( rc ) return rc;
6111 sqlite3_free(lockProxy);
6112 }
6113 sqlite3_free(oldPath);
6114 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6115 }
6116
6117 return rc;
6118}
6119
6120/*
6121** pFile is a file that has been opened by a prior xOpen call. dbPath
6122** is a string buffer at least MAXPATHLEN+1 characters in size.
6123**
6124** This routine find the filename associated with pFile and writes it
6125** int dbPath.
6126*/
6127static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006128#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006129 if( pFile->pMethod == &afpIoMethods ){
6130 /* afp style keeps a reference to the db path in the filePath field
6131 ** of the struct */
drhea678832008-12-10 19:26:22 +00006132 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006133 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6134 } else
drh715ff302008-12-03 22:32:44 +00006135#endif
6136 if( pFile->pMethod == &dotlockIoMethods ){
6137 /* dot lock style uses the locking context to store the dot lock
6138 ** file path */
6139 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6140 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6141 }else{
6142 /* all other styles use the locking context to store the db file path */
6143 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006144 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006145 }
6146 return SQLITE_OK;
6147}
6148
6149/*
6150** Takes an already filled in unix file and alters it so all file locking
6151** will be performed on the local proxy lock file. The following fields
6152** are preserved in the locking context so that they can be restored and
6153** the unix structure properly cleaned up at close time:
6154** ->lockingContext
6155** ->pMethod
6156*/
6157static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6158 proxyLockingContext *pCtx;
6159 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6160 char *lockPath=NULL;
6161 int rc = SQLITE_OK;
6162
drh308c2a52010-05-14 11:30:18 +00006163 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006164 return SQLITE_BUSY;
6165 }
6166 proxyGetDbPathForUnixFile(pFile, dbPath);
6167 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6168 lockPath=NULL;
6169 }else{
6170 lockPath=(char *)path;
6171 }
6172
drh308c2a52010-05-14 11:30:18 +00006173 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6174 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006175
6176 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6177 if( pCtx==0 ){
6178 return SQLITE_NOMEM;
6179 }
6180 memset(pCtx, 0, sizeof(*pCtx));
6181
6182 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6183 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006184 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6185 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6186 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6187 ** (c) the file system is read-only, then enable no-locking access.
6188 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6189 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6190 */
6191 struct statfs fsInfo;
6192 struct stat conchInfo;
6193 int goLockless = 0;
6194
drh99ab3b12011-03-02 15:09:07 +00006195 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006196 int err = errno;
6197 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6198 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6199 }
6200 }
6201 if( goLockless ){
6202 pCtx->conchHeld = -1; /* read only FS/ lockless */
6203 rc = SQLITE_OK;
6204 }
6205 }
drh715ff302008-12-03 22:32:44 +00006206 }
6207 if( rc==SQLITE_OK && lockPath ){
6208 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6209 }
6210
6211 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006212 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6213 if( pCtx->dbPath==NULL ){
6214 rc = SQLITE_NOMEM;
6215 }
6216 }
6217 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006218 /* all memory is allocated, proxys are created and assigned,
6219 ** switch the locking context and pMethod then return.
6220 */
drh715ff302008-12-03 22:32:44 +00006221 pCtx->oldLockingContext = pFile->lockingContext;
6222 pFile->lockingContext = pCtx;
6223 pCtx->pOldMethod = pFile->pMethod;
6224 pFile->pMethod = &proxyIoMethods;
6225 }else{
6226 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006227 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006228 sqlite3_free(pCtx->conchFile);
6229 }
drhd56b1212010-08-11 06:14:15 +00006230 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006231 sqlite3_free(pCtx->conchFilePath);
6232 sqlite3_free(pCtx);
6233 }
drh308c2a52010-05-14 11:30:18 +00006234 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6235 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006236 return rc;
6237}
6238
6239
6240/*
6241** This routine handles sqlite3_file_control() calls that are specific
6242** to proxy locking.
6243*/
6244static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6245 switch( op ){
6246 case SQLITE_GET_LOCKPROXYFILE: {
6247 unixFile *pFile = (unixFile*)id;
6248 if( pFile->pMethod == &proxyIoMethods ){
6249 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6250 proxyTakeConch(pFile);
6251 if( pCtx->lockProxyPath ){
6252 *(const char **)pArg = pCtx->lockProxyPath;
6253 }else{
6254 *(const char **)pArg = ":auto: (not held)";
6255 }
6256 } else {
6257 *(const char **)pArg = NULL;
6258 }
6259 return SQLITE_OK;
6260 }
6261 case SQLITE_SET_LOCKPROXYFILE: {
6262 unixFile *pFile = (unixFile*)id;
6263 int rc = SQLITE_OK;
6264 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6265 if( pArg==NULL || (const char *)pArg==0 ){
6266 if( isProxyStyle ){
6267 /* turn off proxy locking - not supported */
6268 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6269 }else{
6270 /* turn off proxy locking - already off - NOOP */
6271 rc = SQLITE_OK;
6272 }
6273 }else{
6274 const char *proxyPath = (const char *)pArg;
6275 if( isProxyStyle ){
6276 proxyLockingContext *pCtx =
6277 (proxyLockingContext*)pFile->lockingContext;
6278 if( !strcmp(pArg, ":auto:")
6279 || (pCtx->lockProxyPath &&
6280 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6281 ){
6282 rc = SQLITE_OK;
6283 }else{
6284 rc = switchLockProxyPath(pFile, proxyPath);
6285 }
6286 }else{
6287 /* turn on proxy file locking */
6288 rc = proxyTransformUnixFile(pFile, proxyPath);
6289 }
6290 }
6291 return rc;
6292 }
6293 default: {
6294 assert( 0 ); /* The call assures that only valid opcodes are sent */
6295 }
6296 }
6297 /*NOTREACHED*/
6298 return SQLITE_ERROR;
6299}
6300
6301/*
6302** Within this division (the proxying locking implementation) the procedures
6303** above this point are all utilities. The lock-related methods of the
6304** proxy-locking sqlite3_io_method object follow.
6305*/
6306
6307
6308/*
6309** This routine checks if there is a RESERVED lock held on the specified
6310** file by this or any other process. If such a lock is held, set *pResOut
6311** to a non-zero value otherwise *pResOut is set to zero. The return value
6312** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6313*/
6314static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6315 unixFile *pFile = (unixFile*)id;
6316 int rc = proxyTakeConch(pFile);
6317 if( rc==SQLITE_OK ){
6318 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006319 if( pCtx->conchHeld>0 ){
6320 unixFile *proxy = pCtx->lockProxy;
6321 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6322 }else{ /* conchHeld < 0 is lockless */
6323 pResOut=0;
6324 }
drh715ff302008-12-03 22:32:44 +00006325 }
6326 return rc;
6327}
6328
6329/*
drh308c2a52010-05-14 11:30:18 +00006330** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006331** of the following:
6332**
6333** (1) SHARED_LOCK
6334** (2) RESERVED_LOCK
6335** (3) PENDING_LOCK
6336** (4) EXCLUSIVE_LOCK
6337**
6338** Sometimes when requesting one lock state, additional lock states
6339** are inserted in between. The locking might fail on one of the later
6340** transitions leaving the lock state different from what it started but
6341** still short of its goal. The following chart shows the allowed
6342** transitions and the inserted intermediate states:
6343**
6344** UNLOCKED -> SHARED
6345** SHARED -> RESERVED
6346** SHARED -> (PENDING) -> EXCLUSIVE
6347** RESERVED -> (PENDING) -> EXCLUSIVE
6348** PENDING -> EXCLUSIVE
6349**
6350** This routine will only increase a lock. Use the sqlite3OsUnlock()
6351** routine to lower a locking level.
6352*/
drh308c2a52010-05-14 11:30:18 +00006353static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006354 unixFile *pFile = (unixFile*)id;
6355 int rc = proxyTakeConch(pFile);
6356 if( rc==SQLITE_OK ){
6357 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006358 if( pCtx->conchHeld>0 ){
6359 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006360 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6361 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006362 }else{
6363 /* conchHeld < 0 is lockless */
6364 }
drh715ff302008-12-03 22:32:44 +00006365 }
6366 return rc;
6367}
6368
6369
6370/*
drh308c2a52010-05-14 11:30:18 +00006371** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006372** must be either NO_LOCK or SHARED_LOCK.
6373**
6374** If the locking level of the file descriptor is already at or below
6375** the requested locking level, this routine is a no-op.
6376*/
drh308c2a52010-05-14 11:30:18 +00006377static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006378 unixFile *pFile = (unixFile*)id;
6379 int rc = proxyTakeConch(pFile);
6380 if( rc==SQLITE_OK ){
6381 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006382 if( pCtx->conchHeld>0 ){
6383 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006384 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6385 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006386 }else{
6387 /* conchHeld < 0 is lockless */
6388 }
drh715ff302008-12-03 22:32:44 +00006389 }
6390 return rc;
6391}
6392
6393/*
6394** Close a file that uses proxy locks.
6395*/
6396static int proxyClose(sqlite3_file *id) {
6397 if( id ){
6398 unixFile *pFile = (unixFile*)id;
6399 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6400 unixFile *lockProxy = pCtx->lockProxy;
6401 unixFile *conchFile = pCtx->conchFile;
6402 int rc = SQLITE_OK;
6403
6404 if( lockProxy ){
6405 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6406 if( rc ) return rc;
6407 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6408 if( rc ) return rc;
6409 sqlite3_free(lockProxy);
6410 pCtx->lockProxy = 0;
6411 }
6412 if( conchFile ){
6413 if( pCtx->conchHeld ){
6414 rc = proxyReleaseConch(pFile);
6415 if( rc ) return rc;
6416 }
6417 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6418 if( rc ) return rc;
6419 sqlite3_free(conchFile);
6420 }
drhd56b1212010-08-11 06:14:15 +00006421 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006422 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006423 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006424 /* restore the original locking context and pMethod then close it */
6425 pFile->lockingContext = pCtx->oldLockingContext;
6426 pFile->pMethod = pCtx->pOldMethod;
6427 sqlite3_free(pCtx);
6428 return pFile->pMethod->xClose(id);
6429 }
6430 return SQLITE_OK;
6431}
6432
6433
6434
drhd2cb50b2009-01-09 21:41:17 +00006435#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006436/*
6437** The proxy locking style is intended for use with AFP filesystems.
6438** And since AFP is only supported on MacOSX, the proxy locking is also
6439** restricted to MacOSX.
6440**
6441**
6442******************* End of the proxy lock implementation **********************
6443******************************************************************************/
6444
drh734c9862008-11-28 15:37:20 +00006445/*
danielk1977e339d652008-06-28 11:23:00 +00006446** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006447**
6448** This routine registers all VFS implementations for unix-like operating
6449** systems. This routine, and the sqlite3_os_end() routine that follows,
6450** should be the only routines in this file that are visible from other
6451** files.
drh6b9d6dd2008-12-03 19:34:47 +00006452**
6453** This routine is called once during SQLite initialization and by a
6454** single thread. The memory allocation and mutex subsystems have not
6455** necessarily been initialized when this routine is called, and so they
6456** should not be used.
drh153c62c2007-08-24 03:51:33 +00006457*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006458int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006459 /*
6460 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006461 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6462 ** to the "finder" function. (pAppData is a pointer to a pointer because
6463 ** silly C90 rules prohibit a void* from being cast to a function pointer
6464 ** and so we have to go through the intermediate pointer to avoid problems
6465 ** when compiling with -pedantic-errors on GCC.)
6466 **
6467 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006468 ** finder-function. The finder-function returns a pointer to the
6469 ** sqlite_io_methods object that implements the desired locking
6470 ** behaviors. See the division above that contains the IOMETHODS
6471 ** macro for addition information on finder-functions.
6472 **
6473 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6474 ** object. But the "autolockIoFinder" available on MacOSX does a little
6475 ** more than that; it looks at the filesystem type that hosts the
6476 ** database file and tries to choose an locking method appropriate for
6477 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006478 */
drh7708e972008-11-29 00:56:52 +00006479 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006480 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006481 sizeof(unixFile), /* szOsFile */ \
6482 MAX_PATHNAME, /* mxPathname */ \
6483 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006484 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006485 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006486 unixOpen, /* xOpen */ \
6487 unixDelete, /* xDelete */ \
6488 unixAccess, /* xAccess */ \
6489 unixFullPathname, /* xFullPathname */ \
6490 unixDlOpen, /* xDlOpen */ \
6491 unixDlError, /* xDlError */ \
6492 unixDlSym, /* xDlSym */ \
6493 unixDlClose, /* xDlClose */ \
6494 unixRandomness, /* xRandomness */ \
6495 unixSleep, /* xSleep */ \
6496 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006497 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006498 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006499 unixSetSystemCall, /* xSetSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006500 }
6501
drh6b9d6dd2008-12-03 19:34:47 +00006502 /*
6503 ** All default VFSes for unix are contained in the following array.
6504 **
6505 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6506 ** by the SQLite core when the VFS is registered. So the following
6507 ** array cannot be const.
6508 */
danielk1977e339d652008-06-28 11:23:00 +00006509 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006510#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006511 UNIXVFS("unix", autolockIoFinder ),
6512#else
6513 UNIXVFS("unix", posixIoFinder ),
6514#endif
6515 UNIXVFS("unix-none", nolockIoFinder ),
6516 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006517#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006518 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006519#endif
6520#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006521 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006522#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006523 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006524#endif
chw78a13182009-04-07 05:35:03 +00006525#endif
drhd2cb50b2009-01-09 21:41:17 +00006526#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006527 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006528 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006529 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006530#endif
drh153c62c2007-08-24 03:51:33 +00006531 };
drh6b9d6dd2008-12-03 19:34:47 +00006532 unsigned int i; /* Loop counter */
6533
6534 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006535 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006536 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006537 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006538 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006539}
danielk1977e339d652008-06-28 11:23:00 +00006540
6541/*
drh6b9d6dd2008-12-03 19:34:47 +00006542** Shutdown the operating system interface.
6543**
6544** Some operating systems might need to do some cleanup in this routine,
6545** to release dynamically allocated objects. But not on unix.
6546** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006547*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006548int sqlite3_os_end(void){
6549 return SQLITE_OK;
6550}
drhdce8bdb2007-08-16 13:01:44 +00006551
danielk197729bafea2008-06-26 10:41:19 +00006552#endif /* SQLITE_OS_UNIX */