blob: 79038a5846cc433667069d884d924d3f136f1dcc [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
drh1df30962011-03-02 19:06:42 +0000379** "unix" VFSes. Return SQLITE_OK opon successfully updating the
380** system call pointer, or SQLITE_NOTFOUND if there is no configurable
381** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000382*/
383static int unixSetSystemCall(
384 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
385 const char *zName, /* Name of system call to override */
386 void *pNewFunc /* Pointer to new system call value */
387){
388 int i;
drh1df30962011-03-02 19:06:42 +0000389 int rc = SQLITE_NOTFOUND;
drh99ab3b12011-03-02 15:09:07 +0000390 if( zName==0 ){
391 /* If no zName is given, restore all system calls to their default
392 ** settings and return NULL
393 */
394 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
395 if( aSyscall[i].pDefault ){
396 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh1df30962011-03-02 19:06:42 +0000397 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000398 }
399 }
400 }else{
401 /* If zName is specified, operate on only the one system call
402 ** specified.
403 */
404 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
405 if( strcmp(zName, aSyscall[i].zName)==0 ){
406 if( aSyscall[i].pDefault==0 ){
407 aSyscall[i].pDefault = aSyscall[i].pCurrent;
408 }
drh1df30962011-03-02 19:06:42 +0000409 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000410 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
411 aSyscall[i].pCurrent = pNewFunc;
412 break;
413 }
414 }
415 }
416 return rc;
417}
418
drh1df30962011-03-02 19:06:42 +0000419/*
420** Return the value of a system call. Return NULL if zName is not a
421** recognized system call name. NULL is also returned if the system call
422** is currently undefined.
423*/
424static void *unixGetSystemCall(sqlite3_vfs *pNotUsed, const char *zName){
425 int i;
426 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
427 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
428 }
429 return 0;
430}
431
432/*
433** Return the name of the first system call after zName. If zName==NULL
434** then return the name of the first system call. Return NULL if zName
435** is the last system call or if zName is not the name of a valid
436** system call.
437*/
438static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
439 int i;
440 if( zName==0 ){
441 i = -1;
442 }else{
443 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0])-1; i++){
444 if( strcmp(zName, aSyscall[0].zName)==0 ) break;
445 }
446 }
447 for(i++; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
448 if( aSyscall[0].pCurrent!=0 ) return aSyscall[0].zName;
449 }
450 return 0;
451}
452
drhad4f1e52011-03-04 15:43:57 +0000453/*
454** Retry open() calls that fail due to EINTR
455*/
456static int robust_open(const char *z, int f, int m){
457 int rc;
458 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
459 return rc;
460}
danielk197713adf8a2004-06-03 16:08:41 +0000461
drh107886a2008-11-21 22:21:50 +0000462/*
dan9359c7b2009-08-21 08:29:10 +0000463** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000464** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000465** vxworksFileId objects used by this file, all of which may be
466** shared by multiple threads.
467**
468** Function unixMutexHeld() is used to assert() that the global mutex
469** is held when required. This function is only used as part of assert()
470** statements. e.g.
471**
472** unixEnterMutex()
473** assert( unixMutexHeld() );
474** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000475*/
476static void unixEnterMutex(void){
477 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
478}
479static void unixLeaveMutex(void){
480 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
481}
dan9359c7b2009-08-21 08:29:10 +0000482#ifdef SQLITE_DEBUG
483static int unixMutexHeld(void) {
484 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
485}
486#endif
drh107886a2008-11-21 22:21:50 +0000487
drh734c9862008-11-28 15:37:20 +0000488
489#ifdef SQLITE_DEBUG
490/*
491** Helper function for printing out trace information from debugging
492** binaries. This returns the string represetation of the supplied
493** integer lock-type.
494*/
drh308c2a52010-05-14 11:30:18 +0000495static const char *azFileLock(int eFileLock){
496 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000497 case NO_LOCK: return "NONE";
498 case SHARED_LOCK: return "SHARED";
499 case RESERVED_LOCK: return "RESERVED";
500 case PENDING_LOCK: return "PENDING";
501 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000502 }
503 return "ERROR";
504}
505#endif
506
507#ifdef SQLITE_LOCK_TRACE
508/*
509** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000510**
drh734c9862008-11-28 15:37:20 +0000511** This routine is used for troubleshooting locks on multithreaded
512** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
513** command-line option on the compiler. This code is normally
514** turned off.
515*/
516static int lockTrace(int fd, int op, struct flock *p){
517 char *zOpName, *zType;
518 int s;
519 int savedErrno;
520 if( op==F_GETLK ){
521 zOpName = "GETLK";
522 }else if( op==F_SETLK ){
523 zOpName = "SETLK";
524 }else{
drh99ab3b12011-03-02 15:09:07 +0000525 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000526 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
527 return s;
528 }
529 if( p->l_type==F_RDLCK ){
530 zType = "RDLCK";
531 }else if( p->l_type==F_WRLCK ){
532 zType = "WRLCK";
533 }else if( p->l_type==F_UNLCK ){
534 zType = "UNLCK";
535 }else{
536 assert( 0 );
537 }
538 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000539 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000540 savedErrno = errno;
541 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
542 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
543 (int)p->l_pid, s);
544 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
545 struct flock l2;
546 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000547 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000548 if( l2.l_type==F_RDLCK ){
549 zType = "RDLCK";
550 }else if( l2.l_type==F_WRLCK ){
551 zType = "WRLCK";
552 }else if( l2.l_type==F_UNLCK ){
553 zType = "UNLCK";
554 }else{
555 assert( 0 );
556 }
557 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
558 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
559 }
560 errno = savedErrno;
561 return s;
562}
drh99ab3b12011-03-02 15:09:07 +0000563#undef osFcntl
564#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000565#endif /* SQLITE_LOCK_TRACE */
566
drhff812312011-02-23 13:33:46 +0000567/*
568** Retry ftruncate() calls that fail due to EINTR
569*/
drhff812312011-02-23 13:33:46 +0000570static int robust_ftruncate(int h, sqlite3_int64 sz){
571 int rc;
drh99ab3b12011-03-02 15:09:07 +0000572 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000573 return rc;
574}
drh734c9862008-11-28 15:37:20 +0000575
576/*
577** This routine translates a standard POSIX errno code into something
578** useful to the clients of the sqlite3 functions. Specifically, it is
579** intended to translate a variety of "try again" errors into SQLITE_BUSY
580** and a variety of "please close the file descriptor NOW" errors into
581** SQLITE_IOERR
582**
583** Errors during initialization of locks, or file system support for locks,
584** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
585*/
586static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
587 switch (posixError) {
588 case 0:
589 return SQLITE_OK;
590
591 case EAGAIN:
592 case ETIMEDOUT:
593 case EBUSY:
594 case EINTR:
595 case ENOLCK:
596 /* random NFS retry error, unless during file system support
597 * introspection, in which it actually means what it says */
598 return SQLITE_BUSY;
599
600 case EACCES:
601 /* EACCES is like EAGAIN during locking operations, but not any other time*/
602 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
603 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
604 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
605 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
606 return SQLITE_BUSY;
607 }
608 /* else fall through */
609 case EPERM:
610 return SQLITE_PERM;
611
612 case EDEADLK:
613 return SQLITE_IOERR_BLOCKED;
614
615#if EOPNOTSUPP!=ENOTSUP
616 case EOPNOTSUPP:
617 /* something went terribly awry, unless during file system support
618 * introspection, in which it actually means what it says */
619#endif
620#ifdef ENOTSUP
621 case ENOTSUP:
622 /* invalid fd, unless during file system support introspection, in which
623 * it actually means what it says */
624#endif
625 case EIO:
626 case EBADF:
627 case EINVAL:
628 case ENOTCONN:
629 case ENODEV:
630 case ENXIO:
631 case ENOENT:
632 case ESTALE:
633 case ENOSYS:
634 /* these should force the client to close the file and reconnect */
635
636 default:
637 return sqliteIOErr;
638 }
639}
640
641
642
643/******************************************************************************
644****************** Begin Unique File ID Utility Used By VxWorks ***************
645**
646** On most versions of unix, we can get a unique ID for a file by concatenating
647** the device number and the inode number. But this does not work on VxWorks.
648** On VxWorks, a unique file id must be based on the canonical filename.
649**
650** A pointer to an instance of the following structure can be used as a
651** unique file ID in VxWorks. Each instance of this structure contains
652** a copy of the canonical filename. There is also a reference count.
653** The structure is reclaimed when the number of pointers to it drops to
654** zero.
655**
656** There are never very many files open at one time and lookups are not
657** a performance-critical path, so it is sufficient to put these
658** structures on a linked list.
659*/
660struct vxworksFileId {
661 struct vxworksFileId *pNext; /* Next in a list of them all */
662 int nRef; /* Number of references to this one */
663 int nName; /* Length of the zCanonicalName[] string */
664 char *zCanonicalName; /* Canonical filename */
665};
666
667#if OS_VXWORKS
668/*
drh9b35ea62008-11-29 02:20:26 +0000669** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000670** variable:
671*/
672static struct vxworksFileId *vxworksFileList = 0;
673
674/*
675** Simplify a filename into its canonical form
676** by making the following changes:
677**
678** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000679** * convert /./ into just /
680** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000681**
682** Changes are made in-place. Return the new name length.
683**
684** The original filename is in z[0..n-1]. Return the number of
685** characters in the simplified name.
686*/
687static int vxworksSimplifyName(char *z, int n){
688 int i, j;
689 while( n>1 && z[n-1]=='/' ){ n--; }
690 for(i=j=0; i<n; i++){
691 if( z[i]=='/' ){
692 if( z[i+1]=='/' ) continue;
693 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
694 i += 1;
695 continue;
696 }
697 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
698 while( j>0 && z[j-1]!='/' ){ j--; }
699 if( j>0 ){ j--; }
700 i += 2;
701 continue;
702 }
703 }
704 z[j++] = z[i];
705 }
706 z[j] = 0;
707 return j;
708}
709
710/*
711** Find a unique file ID for the given absolute pathname. Return
712** a pointer to the vxworksFileId object. This pointer is the unique
713** file ID.
714**
715** The nRef field of the vxworksFileId object is incremented before
716** the object is returned. A new vxworksFileId object is created
717** and added to the global list if necessary.
718**
719** If a memory allocation error occurs, return NULL.
720*/
721static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
722 struct vxworksFileId *pNew; /* search key and new file ID */
723 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
724 int n; /* Length of zAbsoluteName string */
725
726 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000727 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000728 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
729 if( pNew==0 ) return 0;
730 pNew->zCanonicalName = (char*)&pNew[1];
731 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
732 n = vxworksSimplifyName(pNew->zCanonicalName, n);
733
734 /* Search for an existing entry that matching the canonical name.
735 ** If found, increment the reference count and return a pointer to
736 ** the existing file ID.
737 */
738 unixEnterMutex();
739 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
740 if( pCandidate->nName==n
741 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
742 ){
743 sqlite3_free(pNew);
744 pCandidate->nRef++;
745 unixLeaveMutex();
746 return pCandidate;
747 }
748 }
749
750 /* No match was found. We will make a new file ID */
751 pNew->nRef = 1;
752 pNew->nName = n;
753 pNew->pNext = vxworksFileList;
754 vxworksFileList = pNew;
755 unixLeaveMutex();
756 return pNew;
757}
758
759/*
760** Decrement the reference count on a vxworksFileId object. Free
761** the object when the reference count reaches zero.
762*/
763static void vxworksReleaseFileId(struct vxworksFileId *pId){
764 unixEnterMutex();
765 assert( pId->nRef>0 );
766 pId->nRef--;
767 if( pId->nRef==0 ){
768 struct vxworksFileId **pp;
769 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
770 assert( *pp==pId );
771 *pp = pId->pNext;
772 sqlite3_free(pId);
773 }
774 unixLeaveMutex();
775}
776#endif /* OS_VXWORKS */
777/*************** End of Unique File ID Utility Used By VxWorks ****************
778******************************************************************************/
779
780
781/******************************************************************************
782*************************** Posix Advisory Locking ****************************
783**
drh9b35ea62008-11-29 02:20:26 +0000784** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000785** section 6.5.2.2 lines 483 through 490 specify that when a process
786** sets or clears a lock, that operation overrides any prior locks set
787** by the same process. It does not explicitly say so, but this implies
788** that it overrides locks set by the same process using a different
789** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000790**
791** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000792** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
793**
794** Suppose ./file1 and ./file2 are really the same file (because
795** one is a hard or symbolic link to the other) then if you set
796** an exclusive lock on fd1, then try to get an exclusive lock
797** on fd2, it works. I would have expected the second lock to
798** fail since there was already a lock on the file due to fd1.
799** But not so. Since both locks came from the same process, the
800** second overrides the first, even though they were on different
801** file descriptors opened on different file names.
802**
drh734c9862008-11-28 15:37:20 +0000803** This means that we cannot use POSIX locks to synchronize file access
804** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000805** to synchronize access for threads in separate processes, but not
806** threads within the same process.
807**
808** To work around the problem, SQLite has to manage file locks internally
809** on its own. Whenever a new database is opened, we have to find the
810** specific inode of the database file (the inode is determined by the
811** st_dev and st_ino fields of the stat structure that fstat() fills in)
812** and check for locks already existing on that inode. When locks are
813** created or removed, we have to look at our own internal record of the
814** locks to see if another thread has previously set a lock on that same
815** inode.
816**
drh9b35ea62008-11-29 02:20:26 +0000817** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
818** For VxWorks, we have to use the alternative unique ID system based on
819** canonical filename and implemented in the previous division.)
820**
danielk1977ad94b582007-08-20 06:44:22 +0000821** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000822** descriptor. It is now a structure that holds the integer file
823** descriptor and a pointer to a structure that describes the internal
824** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000825** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000826** point to the same locking structure. The locking structure keeps
827** a reference count (so we will know when to delete it) and a "cnt"
828** field that tells us its internal lock status. cnt==0 means the
829** file is unlocked. cnt==-1 means the file has an exclusive lock.
830** cnt>0 means there are cnt shared locks on the file.
831**
832** Any attempt to lock or unlock a file first checks the locking
833** structure. The fcntl() system call is only invoked to set a
834** POSIX lock if the internal lock structure transitions between
835** a locked and an unlocked state.
836**
drh734c9862008-11-28 15:37:20 +0000837** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000838**
839** If you close a file descriptor that points to a file that has locks,
840** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000841** released. To work around this problem, each unixInodeInfo object
842** maintains a count of the number of pending locks on tha inode.
843** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000844** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000845** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000846** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000847** be closed and that list is walked (and cleared) when the last lock
848** clears.
849**
drh9b35ea62008-11-29 02:20:26 +0000850** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000851**
drh9b35ea62008-11-29 02:20:26 +0000852** Many older versions of linux use the LinuxThreads library which is
853** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000854** A cannot be modified or overridden by a different thread B.
855** Only thread A can modify the lock. Locking behavior is correct
856** if the appliation uses the newer Native Posix Thread Library (NPTL)
857** on linux - with NPTL a lock created by thread A can override locks
858** in thread B. But there is no way to know at compile-time which
859** threading library is being used. So there is no way to know at
860** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000861** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000862** current process.
drh5fdae772004-06-29 03:29:00 +0000863**
drh8af6c222010-05-14 12:43:01 +0000864** SQLite used to support LinuxThreads. But support for LinuxThreads
865** was dropped beginning with version 3.7.0. SQLite will still work with
866** LinuxThreads provided that (1) there is no more than one connection
867** per database file in the same process and (2) database connections
868** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000869*/
870
871/*
872** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000873** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000874*/
875struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000876 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000877#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000878 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000879#else
drh107886a2008-11-21 22:21:50 +0000880 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000881#endif
882};
883
884/*
drhbbd42a62004-05-22 17:41:58 +0000885** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000886** inode. Or, on LinuxThreads, there is one of these structures for
887** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000888**
danielk1977ad94b582007-08-20 06:44:22 +0000889** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000890** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000891** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000892*/
drh8af6c222010-05-14 12:43:01 +0000893struct unixInodeInfo {
894 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000895 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000896 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000897 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000898 unixShmNode *pShmNode; /* Shared memory associated with this inode */
899 int nLock; /* Number of outstanding file locks */
900 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
901 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
902 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000903#if defined(SQLITE_ENABLE_LOCKING_STYLE)
904 unsigned long long sharedByte; /* for AFP simulated shared lock */
905#endif
drh6c7d5c52008-11-21 20:32:33 +0000906#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000907 sem_t *pSem; /* Named POSIX semaphore */
908 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000909#endif
drhbbd42a62004-05-22 17:41:58 +0000910};
911
drhda0e7682008-07-30 15:27:54 +0000912/*
drh8af6c222010-05-14 12:43:01 +0000913** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000914*/
drhd91c68f2010-05-14 14:52:25 +0000915static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000916
drh5fdae772004-06-29 03:29:00 +0000917/*
dane18d4952011-02-21 11:46:24 +0000918**
919** This function - unixLogError_x(), is only ever called via the macro
920** unixLogError().
921**
922** It is invoked after an error occurs in an OS function and errno has been
923** set. It logs a message using sqlite3_log() containing the current value of
924** errno and, if possible, the human-readable equivalent from strerror() or
925** strerror_r().
926**
927** The first argument passed to the macro should be the error code that
928** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
929** The two subsequent arguments should be the name of the OS function that
930** failed (e.g. "unlink", "open") and the the associated file-system path,
931** if any.
932*/
drh0e9365c2011-03-02 02:08:13 +0000933#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
934static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000935 int errcode, /* SQLite error code */
936 const char *zFunc, /* Name of OS function that failed */
937 const char *zPath, /* File path associated with error */
938 int iLine /* Source line number where error occurred */
939){
940 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000941 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000942
943 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
944 ** the strerror() function to obtain the human-readable error message
945 ** equivalent to errno. Otherwise, use strerror_r().
946 */
947#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
948 char aErr[80];
949 memset(aErr, 0, sizeof(aErr));
950 zErr = aErr;
951
952 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
953 ** assume that the system provides the the GNU version of strerror_r() that
954 ** returns a pointer to a buffer containing the error message. That pointer
955 ** may point to aErr[], or it may point to some static storage somewhere.
956 ** Otherwise, assume that the system provides the POSIX version of
957 ** strerror_r(), which always writes an error message into aErr[].
958 **
959 ** If the code incorrectly assumes that it is the POSIX version that is
960 ** available, the error message will often be an empty string. Not a
961 ** huge problem. Incorrectly concluding that the GNU version is available
962 ** could lead to a segfault though.
963 */
964#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
965 zErr =
966# endif
drh0e9365c2011-03-02 02:08:13 +0000967 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000968
969#elif SQLITE_THREADSAFE
970 /* This is a threadsafe build, but strerror_r() is not available. */
971 zErr = "";
972#else
973 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000974 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000975#endif
976
977 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000978 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000979 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000980 "os_unix.c:%d: (%d) %s(%s) - %s",
981 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000982 );
983
984 return errcode;
985}
986
drh0e9365c2011-03-02 02:08:13 +0000987/*
988** Close a file descriptor.
989**
990** We assume that close() almost always works, since it is only in a
991** very sick application or on a very sick platform that it might fail.
992** If it does fail, simply leak the file descriptor, but do log the
993** error.
994**
995** Note that it is not safe to retry close() after EINTR since the
996** file descriptor might have already been reused by another thread.
997** So we don't even try to recover from an EINTR. Just log the error
998** and move on.
999*/
1000static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001001 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001002 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1003 pFile ? pFile->zPath : 0, lineno);
1004 }
1005}
dane18d4952011-02-21 11:46:24 +00001006
1007/*
danb0ac3e32010-06-16 10:55:42 +00001008** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001009*/
drh0e9365c2011-03-02 02:08:13 +00001010static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001011 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001012 UnixUnusedFd *p;
1013 UnixUnusedFd *pNext;
1014 for(p=pInode->pUnused; p; p=pNext){
1015 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001016 robust_close(pFile, p->fd, __LINE__);
1017 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001018 }
drh0e9365c2011-03-02 02:08:13 +00001019 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001020}
1021
1022/*
drh8af6c222010-05-14 12:43:01 +00001023** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001024**
1025** The mutex entered using the unixEnterMutex() function must be held
1026** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001027*/
danb0ac3e32010-06-16 10:55:42 +00001028static void releaseInodeInfo(unixFile *pFile){
1029 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001030 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001031 if( pInode ){
1032 pInode->nRef--;
1033 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001034 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001035 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001036 if( pInode->pPrev ){
1037 assert( pInode->pPrev->pNext==pInode );
1038 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001039 }else{
drh8af6c222010-05-14 12:43:01 +00001040 assert( inodeList==pInode );
1041 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001042 }
drh8af6c222010-05-14 12:43:01 +00001043 if( pInode->pNext ){
1044 assert( pInode->pNext->pPrev==pInode );
1045 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001046 }
drh8af6c222010-05-14 12:43:01 +00001047 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001048 }
drhbbd42a62004-05-22 17:41:58 +00001049 }
1050}
1051
1052/*
drh8af6c222010-05-14 12:43:01 +00001053** Given a file descriptor, locate the unixInodeInfo object that
1054** describes that file descriptor. Create a new one if necessary. The
1055** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001056**
dan9359c7b2009-08-21 08:29:10 +00001057** The mutex entered using the unixEnterMutex() function must be held
1058** when this function is called.
1059**
drh6c7d5c52008-11-21 20:32:33 +00001060** Return an appropriate error code.
1061*/
drh8af6c222010-05-14 12:43:01 +00001062static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001063 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001064 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001065){
1066 int rc; /* System call return code */
1067 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001068 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1069 struct stat statbuf; /* Low-level file information */
1070 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001071
dan9359c7b2009-08-21 08:29:10 +00001072 assert( unixMutexHeld() );
1073
drh6c7d5c52008-11-21 20:32:33 +00001074 /* Get low-level information about the file that we can used to
1075 ** create a unique name for the file.
1076 */
1077 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001078 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001079 if( rc!=0 ){
1080 pFile->lastErrno = errno;
1081#ifdef EOVERFLOW
1082 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1083#endif
1084 return SQLITE_IOERR;
1085 }
1086
drheb0d74f2009-02-03 15:27:02 +00001087#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001088 /* On OS X on an msdos filesystem, the inode number is reported
1089 ** incorrectly for zero-size files. See ticket #3260. To work
1090 ** around this problem (we consider it a bug in OS X, not SQLite)
1091 ** we always increase the file size to 1 by writing a single byte
1092 ** prior to accessing the inode number. The one byte written is
1093 ** an ASCII 'S' character which also happens to be the first byte
1094 ** in the header of every SQLite database. In this way, if there
1095 ** is a race condition such that another thread has already populated
1096 ** the first page of the database, no damage is done.
1097 */
drh7ed97b92010-01-20 13:07:21 +00001098 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001099 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001100 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001101 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001102 return SQLITE_IOERR;
1103 }
drh99ab3b12011-03-02 15:09:07 +00001104 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001105 if( rc!=0 ){
1106 pFile->lastErrno = errno;
1107 return SQLITE_IOERR;
1108 }
1109 }
drheb0d74f2009-02-03 15:27:02 +00001110#endif
drh6c7d5c52008-11-21 20:32:33 +00001111
drh8af6c222010-05-14 12:43:01 +00001112 memset(&fileId, 0, sizeof(fileId));
1113 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001114#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001115 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001116#else
drh8af6c222010-05-14 12:43:01 +00001117 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001118#endif
drh8af6c222010-05-14 12:43:01 +00001119 pInode = inodeList;
1120 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1121 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001122 }
drh8af6c222010-05-14 12:43:01 +00001123 if( pInode==0 ){
1124 pInode = sqlite3_malloc( sizeof(*pInode) );
1125 if( pInode==0 ){
1126 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001127 }
drh8af6c222010-05-14 12:43:01 +00001128 memset(pInode, 0, sizeof(*pInode));
1129 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1130 pInode->nRef = 1;
1131 pInode->pNext = inodeList;
1132 pInode->pPrev = 0;
1133 if( inodeList ) inodeList->pPrev = pInode;
1134 inodeList = pInode;
1135 }else{
1136 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001137 }
drh8af6c222010-05-14 12:43:01 +00001138 *ppInode = pInode;
1139 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001140}
drh6c7d5c52008-11-21 20:32:33 +00001141
aswift5b1a2562008-08-22 00:22:35 +00001142
1143/*
danielk197713adf8a2004-06-03 16:08:41 +00001144** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001145** file by this or any other process. If such a lock is held, set *pResOut
1146** to a non-zero value otherwise *pResOut is set to zero. The return value
1147** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001148*/
danielk1977861f7452008-06-05 11:39:11 +00001149static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001150 int rc = SQLITE_OK;
1151 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001152 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001153
danielk1977861f7452008-06-05 11:39:11 +00001154 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1155
drh054889e2005-11-30 03:20:31 +00001156 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001157 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001158
1159 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001160 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001161 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001162 }
1163
drh2ac3ee92004-06-07 16:27:46 +00001164 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001165 */
danielk197709480a92009-02-09 05:32:32 +00001166#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001167 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001168 struct flock lock;
1169 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001170 lock.l_start = RESERVED_BYTE;
1171 lock.l_len = 1;
1172 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001173 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001174 int tErrno = errno;
1175 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1176 pFile->lastErrno = tErrno;
1177 } else if( lock.l_type!=F_UNLCK ){
1178 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001179 }
1180 }
danielk197709480a92009-02-09 05:32:32 +00001181#endif
danielk197713adf8a2004-06-03 16:08:41 +00001182
drh6c7d5c52008-11-21 20:32:33 +00001183 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001184 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001185
aswift5b1a2562008-08-22 00:22:35 +00001186 *pResOut = reserved;
1187 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001188}
1189
1190/*
drh308c2a52010-05-14 11:30:18 +00001191** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001192** of the following:
1193**
drh2ac3ee92004-06-07 16:27:46 +00001194** (1) SHARED_LOCK
1195** (2) RESERVED_LOCK
1196** (3) PENDING_LOCK
1197** (4) EXCLUSIVE_LOCK
1198**
drhb3e04342004-06-08 00:47:47 +00001199** Sometimes when requesting one lock state, additional lock states
1200** are inserted in between. The locking might fail on one of the later
1201** transitions leaving the lock state different from what it started but
1202** still short of its goal. The following chart shows the allowed
1203** transitions and the inserted intermediate states:
1204**
1205** UNLOCKED -> SHARED
1206** SHARED -> RESERVED
1207** SHARED -> (PENDING) -> EXCLUSIVE
1208** RESERVED -> (PENDING) -> EXCLUSIVE
1209** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001210**
drha6abd042004-06-09 17:37:22 +00001211** This routine will only increase a lock. Use the sqlite3OsUnlock()
1212** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001213*/
drh308c2a52010-05-14 11:30:18 +00001214static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001215 /* The following describes the implementation of the various locks and
1216 ** lock transitions in terms of the POSIX advisory shared and exclusive
1217 ** lock primitives (called read-locks and write-locks below, to avoid
1218 ** confusion with SQLite lock names). The algorithms are complicated
1219 ** slightly in order to be compatible with windows systems simultaneously
1220 ** accessing the same database file, in case that is ever required.
1221 **
1222 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1223 ** byte', each single bytes at well known offsets, and the 'shared byte
1224 ** range', a range of 510 bytes at a well known offset.
1225 **
1226 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1227 ** byte'. If this is successful, a random byte from the 'shared byte
1228 ** range' is read-locked and the lock on the 'pending byte' released.
1229 **
danielk197790ba3bd2004-06-25 08:32:25 +00001230 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1231 ** A RESERVED lock is implemented by grabbing a write-lock on the
1232 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001233 **
1234 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001235 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1236 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1237 ** obtained, but existing SHARED locks are allowed to persist. A process
1238 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1239 ** This property is used by the algorithm for rolling back a journal file
1240 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001241 **
danielk197790ba3bd2004-06-25 08:32:25 +00001242 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1243 ** implemented by obtaining a write-lock on the entire 'shared byte
1244 ** range'. Since all other locks require a read-lock on one of the bytes
1245 ** within this range, this ensures that no other locks are held on the
1246 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001247 **
1248 ** The reason a single byte cannot be used instead of the 'shared byte
1249 ** range' is that some versions of windows do not support read-locks. By
1250 ** locking a random byte from a range, concurrent SHARED locks may exist
1251 ** even if the locking primitive used is always a write-lock.
1252 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001253 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001254 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001255 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001256 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001257 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001258 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001259
drh054889e2005-11-30 03:20:31 +00001260 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001261 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1262 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001263 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001264
1265 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001266 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001267 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001268 */
drh308c2a52010-05-14 11:30:18 +00001269 if( pFile->eFileLock>=eFileLock ){
1270 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1271 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001272 return SQLITE_OK;
1273 }
1274
drh0c2694b2009-09-03 16:23:44 +00001275 /* Make sure the locking sequence is correct.
1276 ** (1) We never move from unlocked to anything higher than shared lock.
1277 ** (2) SQLite never explicitly requests a pendig lock.
1278 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001279 */
drh308c2a52010-05-14 11:30:18 +00001280 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1281 assert( eFileLock!=PENDING_LOCK );
1282 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001283
drh8af6c222010-05-14 12:43:01 +00001284 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001285 */
drh6c7d5c52008-11-21 20:32:33 +00001286 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001287 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001288
danielk1977ad94b582007-08-20 06:44:22 +00001289 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001290 ** handle that precludes the requested lock, return BUSY.
1291 */
drh8af6c222010-05-14 12:43:01 +00001292 if( (pFile->eFileLock!=pInode->eFileLock &&
1293 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 ){
1295 rc = SQLITE_BUSY;
1296 goto end_lock;
1297 }
1298
1299 /* If a SHARED lock is requested, and some thread using this PID already
1300 ** has a SHARED or RESERVED lock, then increment reference counts and
1301 ** return SQLITE_OK.
1302 */
drh308c2a52010-05-14 11:30:18 +00001303 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001304 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001305 assert( eFileLock==SHARED_LOCK );
1306 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001307 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001308 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001309 pInode->nShared++;
1310 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001311 goto end_lock;
1312 }
1313
danielk19779a1d0ab2004-06-01 14:09:28 +00001314
drh3cde3bb2004-06-12 02:17:14 +00001315 /* A PENDING lock is needed before acquiring a SHARED lock and before
1316 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1317 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001318 */
drh0c2694b2009-09-03 16:23:44 +00001319 lock.l_len = 1L;
1320 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001321 if( eFileLock==SHARED_LOCK
1322 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001323 ){
drh308c2a52010-05-14 11:30:18 +00001324 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001325 lock.l_start = PENDING_BYTE;
drh99ab3b12011-03-02 15:09:07 +00001326 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001327 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001328 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001329 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1330 if( IS_LOCK_ERROR(rc) ){
1331 pFile->lastErrno = tErrno;
1332 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001333 goto end_lock;
1334 }
drh3cde3bb2004-06-12 02:17:14 +00001335 }
1336
1337
1338 /* If control gets to this point, then actually go ahead and make
1339 ** operating system calls for the specified lock.
1340 */
drh308c2a52010-05-14 11:30:18 +00001341 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001342 assert( pInode->nShared==0 );
1343 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001344
drh2ac3ee92004-06-07 16:27:46 +00001345 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001346 lock.l_start = SHARED_FIRST;
1347 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001348 if( (s = osFcntl(pFile->h, F_SETLK, &lock))==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001349 tErrno = errno;
1350 }
drh2ac3ee92004-06-07 16:27:46 +00001351 /* Drop the temporary PENDING lock */
1352 lock.l_start = PENDING_BYTE;
1353 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 lock.l_type = F_UNLCK;
drh99ab3b12011-03-02 15:09:07 +00001355 if( osFcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001356 if( s != -1 ){
1357 /* This could happen with a network mount */
1358 tErrno = errno;
1359 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1360 if( IS_LOCK_ERROR(rc) ){
1361 pFile->lastErrno = tErrno;
1362 }
1363 goto end_lock;
1364 }
drh2b4b5962005-06-15 17:47:55 +00001365 }
drhe2396a12007-03-29 20:19:58 +00001366 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001367 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1368 if( IS_LOCK_ERROR(rc) ){
1369 pFile->lastErrno = tErrno;
1370 }
drhbbd42a62004-05-22 17:41:58 +00001371 }else{
drh308c2a52010-05-14 11:30:18 +00001372 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001373 pInode->nLock++;
1374 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001375 }
drh8af6c222010-05-14 12:43:01 +00001376 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001377 /* We are trying for an exclusive lock but another thread in this
1378 ** same process is still holding a shared lock. */
1379 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001380 }else{
drh3cde3bb2004-06-12 02:17:14 +00001381 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001382 ** assumed that there is a SHARED or greater lock on the file
1383 ** already.
1384 */
drh308c2a52010-05-14 11:30:18 +00001385 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001386 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001387 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001389 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001390 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001392 lock.l_start = SHARED_FIRST;
1393 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001394 break;
1395 default:
1396 assert(0);
1397 }
drh99ab3b12011-03-02 15:09:07 +00001398 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001399 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001400 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001401 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1402 if( IS_LOCK_ERROR(rc) ){
1403 pFile->lastErrno = tErrno;
1404 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001405 }
drhbbd42a62004-05-22 17:41:58 +00001406 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001407
drh8f941bc2009-01-14 23:03:40 +00001408
1409#ifndef NDEBUG
1410 /* Set up the transaction-counter change checking flags when
1411 ** transitioning from a SHARED to a RESERVED lock. The change
1412 ** from SHARED to RESERVED marks the beginning of a normal
1413 ** write operation (not a hot journal rollback).
1414 */
1415 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001416 && pFile->eFileLock<=SHARED_LOCK
1417 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001418 ){
1419 pFile->transCntrChng = 0;
1420 pFile->dbUpdate = 0;
1421 pFile->inNormalWrite = 1;
1422 }
1423#endif
1424
1425
danielk1977ecb2a962004-06-02 06:30:16 +00001426 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001427 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001428 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001429 }else if( eFileLock==EXCLUSIVE_LOCK ){
1430 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001431 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001432 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001433
1434end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001435 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001436 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1437 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001438 return rc;
1439}
1440
1441/*
dan08da86a2009-08-21 17:18:03 +00001442** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001443** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001444*/
1445static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001446 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001447 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001448 p->pNext = pInode->pUnused;
1449 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001450 pFile->h = -1;
1451 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001452}
1453
1454/*
drh308c2a52010-05-14 11:30:18 +00001455** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001456** must be either NO_LOCK or SHARED_LOCK.
1457**
1458** If the locking level of the file descriptor is already at or below
1459** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001460**
1461** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1462** the byte range is divided into 2 parts and the first part is unlocked then
1463** set to a read lock, then the other part is simply unlocked. This works
1464** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1465** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001466*/
drh308c2a52010-05-14 11:30:18 +00001467static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001468 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001469 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001470 struct flock lock;
1471 int rc = SQLITE_OK;
1472 int h;
drh0c2694b2009-09-03 16:23:44 +00001473 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001474
drh054889e2005-11-30 03:20:31 +00001475 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001476 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001477 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001478 getpid()));
drha6abd042004-06-09 17:37:22 +00001479
drh308c2a52010-05-14 11:30:18 +00001480 assert( eFileLock<=SHARED_LOCK );
1481 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001482 return SQLITE_OK;
1483 }
drh6c7d5c52008-11-21 20:32:33 +00001484 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001485 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001486 pInode = pFile->pInode;
1487 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001488 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001489 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001490 SimulateIOErrorBenign(1);
1491 SimulateIOError( h=(-1) )
1492 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001493
1494#ifndef NDEBUG
1495 /* When reducing a lock such that other processes can start
1496 ** reading the database file again, make sure that the
1497 ** transaction counter was updated if any part of the database
1498 ** file changed. If the transaction counter is not updated,
1499 ** other connections to the same file might not realize that
1500 ** the file has changed and hence might not know to flush their
1501 ** cache. The use of a stale cache can lead to database corruption.
1502 */
dan7c246102010-04-12 19:00:29 +00001503#if 0
drh8f941bc2009-01-14 23:03:40 +00001504 assert( pFile->inNormalWrite==0
1505 || pFile->dbUpdate==0
1506 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001507#endif
drh8f941bc2009-01-14 23:03:40 +00001508 pFile->inNormalWrite = 0;
1509#endif
1510
drh7ed97b92010-01-20 13:07:21 +00001511 /* downgrading to a shared lock on NFS involves clearing the write lock
1512 ** before establishing the readlock - to avoid a race condition we downgrade
1513 ** the lock in 2 blocks, so that part of the range will be covered by a
1514 ** write lock until the rest is covered by a read lock:
1515 ** 1: [WWWWW]
1516 ** 2: [....W]
1517 ** 3: [RRRRW]
1518 ** 4: [RRRR.]
1519 */
drh308c2a52010-05-14 11:30:18 +00001520 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001521
1522#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1523 assert( handleNFSUnlock==0 );
1524#endif
1525#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001526 if( handleNFSUnlock ){
1527 off_t divSize = SHARED_SIZE - 1;
1528
1529 lock.l_type = F_UNLCK;
1530 lock.l_whence = SEEK_SET;
1531 lock.l_start = SHARED_FIRST;
1532 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001533 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001534 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001535 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1536 if( IS_LOCK_ERROR(rc) ){
1537 pFile->lastErrno = tErrno;
1538 }
1539 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001540 }
drh7ed97b92010-01-20 13:07:21 +00001541 lock.l_type = F_RDLCK;
1542 lock.l_whence = SEEK_SET;
1543 lock.l_start = SHARED_FIRST;
1544 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001545 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001546 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001547 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1548 if( IS_LOCK_ERROR(rc) ){
1549 pFile->lastErrno = tErrno;
1550 }
1551 goto end_unlock;
1552 }
1553 lock.l_type = F_UNLCK;
1554 lock.l_whence = SEEK_SET;
1555 lock.l_start = SHARED_FIRST+divSize;
1556 lock.l_len = SHARED_SIZE-divSize;
drh99ab3b12011-03-02 15:09:07 +00001557 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001558 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001559 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1560 if( IS_LOCK_ERROR(rc) ){
1561 pFile->lastErrno = tErrno;
1562 }
1563 goto end_unlock;
1564 }
drh30f776f2011-02-25 03:25:07 +00001565 }else
1566#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1567 {
drh7ed97b92010-01-20 13:07:21 +00001568 lock.l_type = F_RDLCK;
1569 lock.l_whence = SEEK_SET;
1570 lock.l_start = SHARED_FIRST;
1571 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001572 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001573 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001574 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1575 if( IS_LOCK_ERROR(rc) ){
1576 pFile->lastErrno = tErrno;
1577 }
1578 goto end_unlock;
1579 }
drh9c105bb2004-10-02 20:38:28 +00001580 }
1581 }
drhbbd42a62004-05-22 17:41:58 +00001582 lock.l_type = F_UNLCK;
1583 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001584 lock.l_start = PENDING_BYTE;
1585 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh99ab3b12011-03-02 15:09:07 +00001586 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001587 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001588 }else{
drh0c2694b2009-09-03 16:23:44 +00001589 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001590 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1591 if( IS_LOCK_ERROR(rc) ){
1592 pFile->lastErrno = tErrno;
1593 }
drhcd731cf2009-03-28 23:23:02 +00001594 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001595 }
drhbbd42a62004-05-22 17:41:58 +00001596 }
drh308c2a52010-05-14 11:30:18 +00001597 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001598 /* Decrement the shared lock counter. Release the lock using an
1599 ** OS call only when all threads in this same process have released
1600 ** the lock.
1601 */
drh8af6c222010-05-14 12:43:01 +00001602 pInode->nShared--;
1603 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001604 lock.l_type = F_UNLCK;
1605 lock.l_whence = SEEK_SET;
1606 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001607 SimulateIOErrorBenign(1);
1608 SimulateIOError( h=(-1) )
1609 SimulateIOErrorBenign(0);
drh99ab3b12011-03-02 15:09:07 +00001610 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001611 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001612 }else{
drh0c2694b2009-09-03 16:23:44 +00001613 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001614 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001615 if( IS_LOCK_ERROR(rc) ){
1616 pFile->lastErrno = tErrno;
1617 }
drh8af6c222010-05-14 12:43:01 +00001618 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001619 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001620 }
drha6abd042004-06-09 17:37:22 +00001621 }
1622
drhbbd42a62004-05-22 17:41:58 +00001623 /* Decrement the count of locks against this same file. When the
1624 ** count reaches zero, close any other file descriptors whose close
1625 ** was deferred because of outstanding locks.
1626 */
drh8af6c222010-05-14 12:43:01 +00001627 pInode->nLock--;
1628 assert( pInode->nLock>=0 );
1629 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001630 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001631 }
1632 }
aswift5b1a2562008-08-22 00:22:35 +00001633
1634end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001635 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001636 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001637 return rc;
drhbbd42a62004-05-22 17:41:58 +00001638}
1639
1640/*
drh308c2a52010-05-14 11:30:18 +00001641** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001642** must be either NO_LOCK or SHARED_LOCK.
1643**
1644** If the locking level of the file descriptor is already at or below
1645** the requested locking level, this routine is a no-op.
1646*/
drh308c2a52010-05-14 11:30:18 +00001647static int unixUnlock(sqlite3_file *id, int eFileLock){
1648 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001649}
1650
1651/*
danielk1977e339d652008-06-28 11:23:00 +00001652** This function performs the parts of the "close file" operation
1653** common to all locking schemes. It closes the directory and file
1654** handles, if they are valid, and sets all fields of the unixFile
1655** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001656**
1657** It is *not* necessary to hold the mutex when this routine is called,
1658** even on VxWorks. A mutex will be acquired on VxWorks by the
1659** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001660*/
1661static int closeUnixFile(sqlite3_file *id){
1662 unixFile *pFile = (unixFile*)id;
1663 if( pFile ){
1664 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001665 robust_close(pFile, pFile->dirfd, __LINE__);
1666 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001667 }
1668 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001669 robust_close(pFile, pFile->h, __LINE__);
1670 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001671 }
drh6c7d5c52008-11-21 20:32:33 +00001672#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001673 if( pFile->pId ){
1674 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001675 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001676 }
drh107886a2008-11-21 22:21:50 +00001677 vxworksReleaseFileId(pFile->pId);
1678 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001679 }
1680#endif
drhff59a112010-05-14 20:15:51 +00001681 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001682 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001683 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001684 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001685 }
1686 return SQLITE_OK;
1687}
1688
1689/*
danielk1977e3026632004-06-22 11:29:02 +00001690** Close a file.
1691*/
danielk197762079062007-08-15 17:08:46 +00001692static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001693 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001694 if( id ){
1695 unixFile *pFile = (unixFile *)id;
1696 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001697 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001698 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001699 /* If there are outstanding locks, do not actually close the file just
1700 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001701 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001702 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001703 */
dan08da86a2009-08-21 17:18:03 +00001704 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001705 }
danb0ac3e32010-06-16 10:55:42 +00001706 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001707 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001708 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001709 }
aswiftaebf4132008-11-21 00:10:35 +00001710 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001711}
1712
drh734c9862008-11-28 15:37:20 +00001713/************** End of the posix advisory lock implementation *****************
1714******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001715
drh734c9862008-11-28 15:37:20 +00001716/******************************************************************************
1717****************************** No-op Locking **********************************
1718**
1719** Of the various locking implementations available, this is by far the
1720** simplest: locking is ignored. No attempt is made to lock the database
1721** file for reading or writing.
1722**
1723** This locking mode is appropriate for use on read-only databases
1724** (ex: databases that are burned into CD-ROM, for example.) It can
1725** also be used if the application employs some external mechanism to
1726** prevent simultaneous access of the same database by two or more
1727** database connections. But there is a serious risk of database
1728** corruption if this locking mode is used in situations where multiple
1729** database connections are accessing the same database file at the same
1730** time and one or more of those connections are writing.
1731*/
drhbfe66312006-10-03 17:40:40 +00001732
drh734c9862008-11-28 15:37:20 +00001733static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1734 UNUSED_PARAMETER(NotUsed);
1735 *pResOut = 0;
1736 return SQLITE_OK;
1737}
drh734c9862008-11-28 15:37:20 +00001738static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1739 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1740 return SQLITE_OK;
1741}
drh734c9862008-11-28 15:37:20 +00001742static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1743 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1744 return SQLITE_OK;
1745}
1746
1747/*
drh9b35ea62008-11-29 02:20:26 +00001748** Close the file.
drh734c9862008-11-28 15:37:20 +00001749*/
1750static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001751 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001752}
1753
1754/******************* End of the no-op lock implementation *********************
1755******************************************************************************/
1756
1757/******************************************************************************
1758************************* Begin dot-file Locking ******************************
1759**
drh0c2694b2009-09-03 16:23:44 +00001760** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001761** files in order to control access to the database. This works on just
1762** about every filesystem imaginable. But there are serious downsides:
1763**
1764** (1) There is zero concurrency. A single reader blocks all other
1765** connections from reading or writing the database.
1766**
1767** (2) An application crash or power loss can leave stale lock files
1768** sitting around that need to be cleared manually.
1769**
1770** Nevertheless, a dotlock is an appropriate locking mode for use if no
1771** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001772**
1773** Dotfile locking works by creating a file in the same directory as the
1774** database and with the same name but with a ".lock" extension added.
1775** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1776** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001777*/
1778
1779/*
1780** The file suffix added to the data base filename in order to create the
1781** lock file.
1782*/
1783#define DOTLOCK_SUFFIX ".lock"
1784
drh7708e972008-11-29 00:56:52 +00001785/*
1786** This routine checks if there is a RESERVED lock held on the specified
1787** file by this or any other process. If such a lock is held, set *pResOut
1788** to a non-zero value otherwise *pResOut is set to zero. The return value
1789** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1790**
1791** In dotfile locking, either a lock exists or it does not. So in this
1792** variation of CheckReservedLock(), *pResOut is set to true if any lock
1793** is held on the file and false if the file is unlocked.
1794*/
drh734c9862008-11-28 15:37:20 +00001795static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1796 int rc = SQLITE_OK;
1797 int reserved = 0;
1798 unixFile *pFile = (unixFile*)id;
1799
1800 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1801
1802 assert( pFile );
1803
1804 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001805 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001806 /* Either this connection or some other connection in the same process
1807 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001808 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001809 }else{
1810 /* The lock is held if and only if the lockfile exists */
1811 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001812 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001813 }
drh308c2a52010-05-14 11:30:18 +00001814 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001815 *pResOut = reserved;
1816 return rc;
1817}
1818
drh7708e972008-11-29 00:56:52 +00001819/*
drh308c2a52010-05-14 11:30:18 +00001820** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001821** of the following:
1822**
1823** (1) SHARED_LOCK
1824** (2) RESERVED_LOCK
1825** (3) PENDING_LOCK
1826** (4) EXCLUSIVE_LOCK
1827**
1828** Sometimes when requesting one lock state, additional lock states
1829** are inserted in between. The locking might fail on one of the later
1830** transitions leaving the lock state different from what it started but
1831** still short of its goal. The following chart shows the allowed
1832** transitions and the inserted intermediate states:
1833**
1834** UNLOCKED -> SHARED
1835** SHARED -> RESERVED
1836** SHARED -> (PENDING) -> EXCLUSIVE
1837** RESERVED -> (PENDING) -> EXCLUSIVE
1838** PENDING -> EXCLUSIVE
1839**
1840** This routine will only increase a lock. Use the sqlite3OsUnlock()
1841** routine to lower a locking level.
1842**
1843** With dotfile locking, we really only support state (4): EXCLUSIVE.
1844** But we track the other locking levels internally.
1845*/
drh308c2a52010-05-14 11:30:18 +00001846static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001847 unixFile *pFile = (unixFile*)id;
1848 int fd;
1849 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001850 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001851
drh7708e972008-11-29 00:56:52 +00001852
1853 /* If we have any lock, then the lock file already exists. All we have
1854 ** to do is adjust our internal record of the lock level.
1855 */
drh308c2a52010-05-14 11:30:18 +00001856 if( pFile->eFileLock > NO_LOCK ){
1857 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001858#if !OS_VXWORKS
1859 /* Always update the timestamp on the old file */
1860 utimes(zLockFile, NULL);
1861#endif
drh7708e972008-11-29 00:56:52 +00001862 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001863 }
1864
1865 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001866 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001867 if( fd<0 ){
1868 /* failed to open/create the file, someone else may have stolen the lock */
1869 int tErrno = errno;
1870 if( EEXIST == tErrno ){
1871 rc = SQLITE_BUSY;
1872 } else {
1873 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1874 if( IS_LOCK_ERROR(rc) ){
1875 pFile->lastErrno = tErrno;
1876 }
1877 }
drh7708e972008-11-29 00:56:52 +00001878 return rc;
drh734c9862008-11-28 15:37:20 +00001879 }
drh0e9365c2011-03-02 02:08:13 +00001880 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001881
1882 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001883 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001884 return rc;
1885}
1886
drh7708e972008-11-29 00:56:52 +00001887/*
drh308c2a52010-05-14 11:30:18 +00001888** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001889** must be either NO_LOCK or SHARED_LOCK.
1890**
1891** If the locking level of the file descriptor is already at or below
1892** the requested locking level, this routine is a no-op.
1893**
1894** When the locking level reaches NO_LOCK, delete the lock file.
1895*/
drh308c2a52010-05-14 11:30:18 +00001896static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001897 unixFile *pFile = (unixFile*)id;
1898 char *zLockFile = (char *)pFile->lockingContext;
1899
1900 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001901 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1902 pFile->eFileLock, getpid()));
1903 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001904
1905 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001906 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001907 return SQLITE_OK;
1908 }
drh7708e972008-11-29 00:56:52 +00001909
1910 /* To downgrade to shared, simply update our internal notion of the
1911 ** lock state. No need to mess with the file on disk.
1912 */
drh308c2a52010-05-14 11:30:18 +00001913 if( eFileLock==SHARED_LOCK ){
1914 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001915 return SQLITE_OK;
1916 }
1917
drh7708e972008-11-29 00:56:52 +00001918 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001919 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001920 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001921 int rc = 0;
1922 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001923 if( ENOENT != tErrno ){
1924 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1925 }
1926 if( IS_LOCK_ERROR(rc) ){
1927 pFile->lastErrno = tErrno;
1928 }
1929 return rc;
1930 }
drh308c2a52010-05-14 11:30:18 +00001931 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001932 return SQLITE_OK;
1933}
1934
1935/*
drh9b35ea62008-11-29 02:20:26 +00001936** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001937*/
1938static int dotlockClose(sqlite3_file *id) {
1939 int rc;
1940 if( id ){
1941 unixFile *pFile = (unixFile*)id;
1942 dotlockUnlock(id, NO_LOCK);
1943 sqlite3_free(pFile->lockingContext);
1944 }
drh734c9862008-11-28 15:37:20 +00001945 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001946 return rc;
1947}
1948/****************** End of the dot-file lock implementation *******************
1949******************************************************************************/
1950
1951/******************************************************************************
1952************************** Begin flock Locking ********************************
1953**
1954** Use the flock() system call to do file locking.
1955**
drh6b9d6dd2008-12-03 19:34:47 +00001956** flock() locking is like dot-file locking in that the various
1957** fine-grain locking levels supported by SQLite are collapsed into
1958** a single exclusive lock. In other words, SHARED, RESERVED, and
1959** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1960** still works when you do this, but concurrency is reduced since
1961** only a single process can be reading the database at a time.
1962**
drh734c9862008-11-28 15:37:20 +00001963** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1964** compiling for VXWORKS.
1965*/
1966#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001967
drh6b9d6dd2008-12-03 19:34:47 +00001968/*
drhff812312011-02-23 13:33:46 +00001969** Retry flock() calls that fail with EINTR
1970*/
1971#ifdef EINTR
1972static int robust_flock(int fd, int op){
1973 int rc;
1974 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
1975 return rc;
1976}
1977#else
drh5c819272011-02-23 14:00:12 +00001978# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00001979#endif
1980
1981
1982/*
drh6b9d6dd2008-12-03 19:34:47 +00001983** This routine checks if there is a RESERVED lock held on the specified
1984** file by this or any other process. If such a lock is held, set *pResOut
1985** to a non-zero value otherwise *pResOut is set to zero. The return value
1986** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1987*/
drh734c9862008-11-28 15:37:20 +00001988static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1989 int rc = SQLITE_OK;
1990 int reserved = 0;
1991 unixFile *pFile = (unixFile*)id;
1992
1993 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1994
1995 assert( pFile );
1996
1997 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001998 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001999 reserved = 1;
2000 }
2001
2002 /* Otherwise see if some other process holds it. */
2003 if( !reserved ){
2004 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002005 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002006 if( !lrc ){
2007 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002008 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002009 if ( lrc ) {
2010 int tErrno = errno;
2011 /* unlock failed with an error */
2012 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2013 if( IS_LOCK_ERROR(lrc) ){
2014 pFile->lastErrno = tErrno;
2015 rc = lrc;
2016 }
2017 }
2018 } else {
2019 int tErrno = errno;
2020 reserved = 1;
2021 /* someone else might have it reserved */
2022 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2023 if( IS_LOCK_ERROR(lrc) ){
2024 pFile->lastErrno = tErrno;
2025 rc = lrc;
2026 }
2027 }
2028 }
drh308c2a52010-05-14 11:30:18 +00002029 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002030
2031#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2032 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2033 rc = SQLITE_OK;
2034 reserved=1;
2035 }
2036#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2037 *pResOut = reserved;
2038 return rc;
2039}
2040
drh6b9d6dd2008-12-03 19:34:47 +00002041/*
drh308c2a52010-05-14 11:30:18 +00002042** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002043** of the following:
2044**
2045** (1) SHARED_LOCK
2046** (2) RESERVED_LOCK
2047** (3) PENDING_LOCK
2048** (4) EXCLUSIVE_LOCK
2049**
2050** Sometimes when requesting one lock state, additional lock states
2051** are inserted in between. The locking might fail on one of the later
2052** transitions leaving the lock state different from what it started but
2053** still short of its goal. The following chart shows the allowed
2054** transitions and the inserted intermediate states:
2055**
2056** UNLOCKED -> SHARED
2057** SHARED -> RESERVED
2058** SHARED -> (PENDING) -> EXCLUSIVE
2059** RESERVED -> (PENDING) -> EXCLUSIVE
2060** PENDING -> EXCLUSIVE
2061**
2062** flock() only really support EXCLUSIVE locks. We track intermediate
2063** lock states in the sqlite3_file structure, but all locks SHARED or
2064** above are really EXCLUSIVE locks and exclude all other processes from
2065** access the file.
2066**
2067** This routine will only increase a lock. Use the sqlite3OsUnlock()
2068** routine to lower a locking level.
2069*/
drh308c2a52010-05-14 11:30:18 +00002070static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002071 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002072 unixFile *pFile = (unixFile*)id;
2073
2074 assert( pFile );
2075
2076 /* if we already have a lock, it is exclusive.
2077 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002078 if (pFile->eFileLock > NO_LOCK) {
2079 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002080 return SQLITE_OK;
2081 }
2082
2083 /* grab an exclusive lock */
2084
drhff812312011-02-23 13:33:46 +00002085 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002086 int tErrno = errno;
2087 /* didn't get, must be busy */
2088 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2089 if( IS_LOCK_ERROR(rc) ){
2090 pFile->lastErrno = tErrno;
2091 }
2092 } else {
2093 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002094 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002095 }
drh308c2a52010-05-14 11:30:18 +00002096 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2097 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002098#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2099 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2100 rc = SQLITE_BUSY;
2101 }
2102#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2103 return rc;
2104}
2105
drh6b9d6dd2008-12-03 19:34:47 +00002106
2107/*
drh308c2a52010-05-14 11:30:18 +00002108** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002109** must be either NO_LOCK or SHARED_LOCK.
2110**
2111** If the locking level of the file descriptor is already at or below
2112** the requested locking level, this routine is a no-op.
2113*/
drh308c2a52010-05-14 11:30:18 +00002114static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002115 unixFile *pFile = (unixFile*)id;
2116
2117 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002118 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2119 pFile->eFileLock, getpid()));
2120 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002121
2122 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002123 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002124 return SQLITE_OK;
2125 }
2126
2127 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002128 if (eFileLock==SHARED_LOCK) {
2129 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002130 return SQLITE_OK;
2131 }
2132
2133 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002134 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002135 if (rc) {
2136 int r, tErrno = errno;
2137 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2138 if( IS_LOCK_ERROR(r) ){
2139 pFile->lastErrno = tErrno;
2140 }
2141#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2142 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2143 r = SQLITE_BUSY;
2144 }
2145#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2146
2147 return r;
2148 } else {
drh308c2a52010-05-14 11:30:18 +00002149 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002150 return SQLITE_OK;
2151 }
2152}
2153
2154/*
2155** Close a file.
2156*/
2157static int flockClose(sqlite3_file *id) {
2158 if( id ){
2159 flockUnlock(id, NO_LOCK);
2160 }
2161 return closeUnixFile(id);
2162}
2163
2164#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2165
2166/******************* End of the flock lock implementation *********************
2167******************************************************************************/
2168
2169/******************************************************************************
2170************************ Begin Named Semaphore Locking ************************
2171**
2172** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002173**
2174** Semaphore locking is like dot-lock and flock in that it really only
2175** supports EXCLUSIVE locking. Only a single process can read or write
2176** the database file at a time. This reduces potential concurrency, but
2177** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002178*/
2179#if OS_VXWORKS
2180
drh6b9d6dd2008-12-03 19:34:47 +00002181/*
2182** This routine checks if there is a RESERVED lock held on the specified
2183** file by this or any other process. If such a lock is held, set *pResOut
2184** to a non-zero value otherwise *pResOut is set to zero. The return value
2185** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2186*/
drh734c9862008-11-28 15:37:20 +00002187static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2188 int rc = SQLITE_OK;
2189 int reserved = 0;
2190 unixFile *pFile = (unixFile*)id;
2191
2192 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2193
2194 assert( pFile );
2195
2196 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002197 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002198 reserved = 1;
2199 }
2200
2201 /* Otherwise see if some other process holds it. */
2202 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002203 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002204 struct stat statBuf;
2205
2206 if( sem_trywait(pSem)==-1 ){
2207 int tErrno = errno;
2208 if( EAGAIN != tErrno ){
2209 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2210 pFile->lastErrno = tErrno;
2211 } else {
2212 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002213 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002214 }
2215 }else{
2216 /* we could have it if we want it */
2217 sem_post(pSem);
2218 }
2219 }
drh308c2a52010-05-14 11:30:18 +00002220 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002221
2222 *pResOut = reserved;
2223 return rc;
2224}
2225
drh6b9d6dd2008-12-03 19:34:47 +00002226/*
drh308c2a52010-05-14 11:30:18 +00002227** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002228** of the following:
2229**
2230** (1) SHARED_LOCK
2231** (2) RESERVED_LOCK
2232** (3) PENDING_LOCK
2233** (4) EXCLUSIVE_LOCK
2234**
2235** Sometimes when requesting one lock state, additional lock states
2236** are inserted in between. The locking might fail on one of the later
2237** transitions leaving the lock state different from what it started but
2238** still short of its goal. The following chart shows the allowed
2239** transitions and the inserted intermediate states:
2240**
2241** UNLOCKED -> SHARED
2242** SHARED -> RESERVED
2243** SHARED -> (PENDING) -> EXCLUSIVE
2244** RESERVED -> (PENDING) -> EXCLUSIVE
2245** PENDING -> EXCLUSIVE
2246**
2247** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2248** lock states in the sqlite3_file structure, but all locks SHARED or
2249** above are really EXCLUSIVE locks and exclude all other processes from
2250** access the file.
2251**
2252** This routine will only increase a lock. Use the sqlite3OsUnlock()
2253** routine to lower a locking level.
2254*/
drh308c2a52010-05-14 11:30:18 +00002255static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002256 unixFile *pFile = (unixFile*)id;
2257 int fd;
drh8af6c222010-05-14 12:43:01 +00002258 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002259 int rc = SQLITE_OK;
2260
2261 /* if we already have a lock, it is exclusive.
2262 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002263 if (pFile->eFileLock > NO_LOCK) {
2264 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002265 rc = SQLITE_OK;
2266 goto sem_end_lock;
2267 }
2268
2269 /* lock semaphore now but bail out when already locked. */
2270 if( sem_trywait(pSem)==-1 ){
2271 rc = SQLITE_BUSY;
2272 goto sem_end_lock;
2273 }
2274
2275 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002276 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002277
2278 sem_end_lock:
2279 return rc;
2280}
2281
drh6b9d6dd2008-12-03 19:34:47 +00002282/*
drh308c2a52010-05-14 11:30:18 +00002283** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002284** must be either NO_LOCK or SHARED_LOCK.
2285**
2286** If the locking level of the file descriptor is already at or below
2287** the requested locking level, this routine is a no-op.
2288*/
drh308c2a52010-05-14 11:30:18 +00002289static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002290 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002291 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002292
2293 assert( pFile );
2294 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002295 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2296 pFile->eFileLock, getpid()));
2297 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002298
2299 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002300 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002301 return SQLITE_OK;
2302 }
2303
2304 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002305 if (eFileLock==SHARED_LOCK) {
2306 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002307 return SQLITE_OK;
2308 }
2309
2310 /* no, really unlock. */
2311 if ( sem_post(pSem)==-1 ) {
2312 int rc, tErrno = errno;
2313 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2314 if( IS_LOCK_ERROR(rc) ){
2315 pFile->lastErrno = tErrno;
2316 }
2317 return rc;
2318 }
drh308c2a52010-05-14 11:30:18 +00002319 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002320 return SQLITE_OK;
2321}
2322
2323/*
2324 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002325 */
drh734c9862008-11-28 15:37:20 +00002326static int semClose(sqlite3_file *id) {
2327 if( id ){
2328 unixFile *pFile = (unixFile*)id;
2329 semUnlock(id, NO_LOCK);
2330 assert( pFile );
2331 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002332 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002333 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002334 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002335 }
2336 return SQLITE_OK;
2337}
2338
2339#endif /* OS_VXWORKS */
2340/*
2341** Named semaphore locking is only available on VxWorks.
2342**
2343*************** End of the named semaphore lock implementation ****************
2344******************************************************************************/
2345
2346
2347/******************************************************************************
2348*************************** Begin AFP Locking *********************************
2349**
2350** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2351** on Apple Macintosh computers - both OS9 and OSX.
2352**
2353** Third-party implementations of AFP are available. But this code here
2354** only works on OSX.
2355*/
2356
drhd2cb50b2009-01-09 21:41:17 +00002357#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002358/*
2359** The afpLockingContext structure contains all afp lock specific state
2360*/
drhbfe66312006-10-03 17:40:40 +00002361typedef struct afpLockingContext afpLockingContext;
2362struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002363 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002364 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002365};
2366
2367struct ByteRangeLockPB2
2368{
2369 unsigned long long offset; /* offset to first byte to lock */
2370 unsigned long long length; /* nbr of bytes to lock */
2371 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2372 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2373 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2374 int fd; /* file desc to assoc this lock with */
2375};
2376
drhfd131da2007-08-07 17:13:03 +00002377#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002378
drh6b9d6dd2008-12-03 19:34:47 +00002379/*
2380** This is a utility for setting or clearing a bit-range lock on an
2381** AFP filesystem.
2382**
2383** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2384*/
2385static int afpSetLock(
2386 const char *path, /* Name of the file to be locked or unlocked */
2387 unixFile *pFile, /* Open file descriptor on path */
2388 unsigned long long offset, /* First byte to be locked */
2389 unsigned long long length, /* Number of bytes to lock */
2390 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002391){
drh6b9d6dd2008-12-03 19:34:47 +00002392 struct ByteRangeLockPB2 pb;
2393 int err;
drhbfe66312006-10-03 17:40:40 +00002394
2395 pb.unLockFlag = setLockFlag ? 0 : 1;
2396 pb.startEndFlag = 0;
2397 pb.offset = offset;
2398 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002399 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002400
drh308c2a52010-05-14 11:30:18 +00002401 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002402 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002403 offset, length));
drhbfe66312006-10-03 17:40:40 +00002404 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2405 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002406 int rc;
2407 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002408 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2409 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002410#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2411 rc = SQLITE_BUSY;
2412#else
drh734c9862008-11-28 15:37:20 +00002413 rc = sqliteErrorFromPosixError(tErrno,
2414 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002415#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002416 if( IS_LOCK_ERROR(rc) ){
2417 pFile->lastErrno = tErrno;
2418 }
2419 return rc;
drhbfe66312006-10-03 17:40:40 +00002420 } else {
aswift5b1a2562008-08-22 00:22:35 +00002421 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002422 }
2423}
2424
drh6b9d6dd2008-12-03 19:34:47 +00002425/*
2426** This routine checks if there is a RESERVED lock held on the specified
2427** file by this or any other process. If such a lock is held, set *pResOut
2428** to a non-zero value otherwise *pResOut is set to zero. The return value
2429** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2430*/
danielk1977e339d652008-06-28 11:23:00 +00002431static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002432 int rc = SQLITE_OK;
2433 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002434 unixFile *pFile = (unixFile*)id;
2435
aswift5b1a2562008-08-22 00:22:35 +00002436 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2437
2438 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002439 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002440 if( context->reserved ){
2441 *pResOut = 1;
2442 return SQLITE_OK;
2443 }
drh8af6c222010-05-14 12:43:01 +00002444 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002445
2446 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002447 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002448 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002449 }
2450
2451 /* Otherwise see if some other process holds it.
2452 */
aswift5b1a2562008-08-22 00:22:35 +00002453 if( !reserved ){
2454 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002455 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002456 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002457 /* if we succeeded in taking the reserved lock, unlock it to restore
2458 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002459 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002460 } else {
2461 /* if we failed to get the lock then someone else must have it */
2462 reserved = 1;
2463 }
2464 if( IS_LOCK_ERROR(lrc) ){
2465 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002466 }
2467 }
drhbfe66312006-10-03 17:40:40 +00002468
drh7ed97b92010-01-20 13:07:21 +00002469 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002470 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002471
2472 *pResOut = reserved;
2473 return rc;
drhbfe66312006-10-03 17:40:40 +00002474}
2475
drh6b9d6dd2008-12-03 19:34:47 +00002476/*
drh308c2a52010-05-14 11:30:18 +00002477** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002478** of the following:
2479**
2480** (1) SHARED_LOCK
2481** (2) RESERVED_LOCK
2482** (3) PENDING_LOCK
2483** (4) EXCLUSIVE_LOCK
2484**
2485** Sometimes when requesting one lock state, additional lock states
2486** are inserted in between. The locking might fail on one of the later
2487** transitions leaving the lock state different from what it started but
2488** still short of its goal. The following chart shows the allowed
2489** transitions and the inserted intermediate states:
2490**
2491** UNLOCKED -> SHARED
2492** SHARED -> RESERVED
2493** SHARED -> (PENDING) -> EXCLUSIVE
2494** RESERVED -> (PENDING) -> EXCLUSIVE
2495** PENDING -> EXCLUSIVE
2496**
2497** This routine will only increase a lock. Use the sqlite3OsUnlock()
2498** routine to lower a locking level.
2499*/
drh308c2a52010-05-14 11:30:18 +00002500static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002501 int rc = SQLITE_OK;
2502 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002503 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002504 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002505
2506 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002507 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2508 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002509 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002510
drhbfe66312006-10-03 17:40:40 +00002511 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002512 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002513 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002514 */
drh308c2a52010-05-14 11:30:18 +00002515 if( pFile->eFileLock>=eFileLock ){
2516 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2517 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002518 return SQLITE_OK;
2519 }
2520
2521 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002522 ** (1) We never move from unlocked to anything higher than shared lock.
2523 ** (2) SQLite never explicitly requests a pendig lock.
2524 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002525 */
drh308c2a52010-05-14 11:30:18 +00002526 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2527 assert( eFileLock!=PENDING_LOCK );
2528 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002529
drh8af6c222010-05-14 12:43:01 +00002530 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002531 */
drh6c7d5c52008-11-21 20:32:33 +00002532 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002533 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002534
2535 /* If some thread using this PID has a lock via a different unixFile*
2536 ** handle that precludes the requested lock, return BUSY.
2537 */
drh8af6c222010-05-14 12:43:01 +00002538 if( (pFile->eFileLock!=pInode->eFileLock &&
2539 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002540 ){
2541 rc = SQLITE_BUSY;
2542 goto afp_end_lock;
2543 }
2544
2545 /* If a SHARED lock is requested, and some thread using this PID already
2546 ** has a SHARED or RESERVED lock, then increment reference counts and
2547 ** return SQLITE_OK.
2548 */
drh308c2a52010-05-14 11:30:18 +00002549 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002550 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002551 assert( eFileLock==SHARED_LOCK );
2552 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002553 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002554 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002555 pInode->nShared++;
2556 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002557 goto afp_end_lock;
2558 }
drhbfe66312006-10-03 17:40:40 +00002559
2560 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002561 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2562 ** be released.
2563 */
drh308c2a52010-05-14 11:30:18 +00002564 if( eFileLock==SHARED_LOCK
2565 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002566 ){
2567 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002568 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002569 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002570 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002571 goto afp_end_lock;
2572 }
2573 }
2574
2575 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002576 ** operating system calls for the specified lock.
2577 */
drh308c2a52010-05-14 11:30:18 +00002578 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002579 int lrc1, lrc2, lrc1Errno;
2580 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002581
drh8af6c222010-05-14 12:43:01 +00002582 assert( pInode->nShared==0 );
2583 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002584
2585 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002586 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002587 /* note that the quality of the randomness doesn't matter that much */
2588 lk = random();
drh8af6c222010-05-14 12:43:01 +00002589 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002590 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002591 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002592 if( IS_LOCK_ERROR(lrc1) ){
2593 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002594 }
aswift5b1a2562008-08-22 00:22:35 +00002595 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002596 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002597
aswift5b1a2562008-08-22 00:22:35 +00002598 if( IS_LOCK_ERROR(lrc1) ) {
2599 pFile->lastErrno = lrc1Errno;
2600 rc = lrc1;
2601 goto afp_end_lock;
2602 } else if( IS_LOCK_ERROR(lrc2) ){
2603 rc = lrc2;
2604 goto afp_end_lock;
2605 } else if( lrc1 != SQLITE_OK ) {
2606 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002607 } else {
drh308c2a52010-05-14 11:30:18 +00002608 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002609 pInode->nLock++;
2610 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002611 }
drh8af6c222010-05-14 12:43:01 +00002612 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002613 /* We are trying for an exclusive lock but another thread in this
2614 ** same process is still holding a shared lock. */
2615 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002616 }else{
2617 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2618 ** assumed that there is a SHARED or greater lock on the file
2619 ** already.
2620 */
2621 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002622 assert( 0!=pFile->eFileLock );
2623 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002624 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002625 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002626 if( !failed ){
2627 context->reserved = 1;
2628 }
drhbfe66312006-10-03 17:40:40 +00002629 }
drh308c2a52010-05-14 11:30:18 +00002630 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002631 /* Acquire an EXCLUSIVE lock */
2632
2633 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002634 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002635 */
drh6b9d6dd2008-12-03 19:34:47 +00002636 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002637 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002638 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002639 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002640 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002641 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002642 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002643 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002644 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2645 ** a critical I/O error
2646 */
2647 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2648 SQLITE_IOERR_LOCK;
2649 goto afp_end_lock;
2650 }
2651 }else{
aswift5b1a2562008-08-22 00:22:35 +00002652 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002653 }
2654 }
aswift5b1a2562008-08-22 00:22:35 +00002655 if( failed ){
2656 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002657 }
2658 }
2659
2660 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002661 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002662 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002663 }else if( eFileLock==EXCLUSIVE_LOCK ){
2664 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002665 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002666 }
2667
2668afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002669 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002670 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2671 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002672 return rc;
2673}
2674
2675/*
drh308c2a52010-05-14 11:30:18 +00002676** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002677** must be either NO_LOCK or SHARED_LOCK.
2678**
2679** If the locking level of the file descriptor is already at or below
2680** the requested locking level, this routine is a no-op.
2681*/
drh308c2a52010-05-14 11:30:18 +00002682static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002683 int rc = SQLITE_OK;
2684 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002685 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002686 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2687 int skipShared = 0;
2688#ifdef SQLITE_TEST
2689 int h = pFile->h;
2690#endif
drhbfe66312006-10-03 17:40:40 +00002691
2692 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002693 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002694 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002695 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002696
drh308c2a52010-05-14 11:30:18 +00002697 assert( eFileLock<=SHARED_LOCK );
2698 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002699 return SQLITE_OK;
2700 }
drh6c7d5c52008-11-21 20:32:33 +00002701 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002702 pInode = pFile->pInode;
2703 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002704 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002705 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002706 SimulateIOErrorBenign(1);
2707 SimulateIOError( h=(-1) )
2708 SimulateIOErrorBenign(0);
2709
2710#ifndef NDEBUG
2711 /* When reducing a lock such that other processes can start
2712 ** reading the database file again, make sure that the
2713 ** transaction counter was updated if any part of the database
2714 ** file changed. If the transaction counter is not updated,
2715 ** other connections to the same file might not realize that
2716 ** the file has changed and hence might not know to flush their
2717 ** cache. The use of a stale cache can lead to database corruption.
2718 */
2719 assert( pFile->inNormalWrite==0
2720 || pFile->dbUpdate==0
2721 || pFile->transCntrChng==1 );
2722 pFile->inNormalWrite = 0;
2723#endif
aswiftaebf4132008-11-21 00:10:35 +00002724
drh308c2a52010-05-14 11:30:18 +00002725 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002726 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002727 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002728 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002729 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002730 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2731 } else {
2732 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002733 }
2734 }
drh308c2a52010-05-14 11:30:18 +00002735 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002736 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002737 }
drh308c2a52010-05-14 11:30:18 +00002738 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002739 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2740 if( !rc ){
2741 context->reserved = 0;
2742 }
aswiftaebf4132008-11-21 00:10:35 +00002743 }
drh8af6c222010-05-14 12:43:01 +00002744 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2745 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002746 }
aswiftaebf4132008-11-21 00:10:35 +00002747 }
drh308c2a52010-05-14 11:30:18 +00002748 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002749
drh7ed97b92010-01-20 13:07:21 +00002750 /* Decrement the shared lock counter. Release the lock using an
2751 ** OS call only when all threads in this same process have released
2752 ** the lock.
2753 */
drh8af6c222010-05-14 12:43:01 +00002754 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2755 pInode->nShared--;
2756 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002757 SimulateIOErrorBenign(1);
2758 SimulateIOError( h=(-1) )
2759 SimulateIOErrorBenign(0);
2760 if( !skipShared ){
2761 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2762 }
2763 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002764 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002765 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002766 }
2767 }
2768 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002769 pInode->nLock--;
2770 assert( pInode->nLock>=0 );
2771 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002772 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002773 }
2774 }
drhbfe66312006-10-03 17:40:40 +00002775 }
drh7ed97b92010-01-20 13:07:21 +00002776
drh6c7d5c52008-11-21 20:32:33 +00002777 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002778 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002779 return rc;
2780}
2781
2782/*
drh339eb0b2008-03-07 15:34:11 +00002783** Close a file & cleanup AFP specific locking context
2784*/
danielk1977e339d652008-06-28 11:23:00 +00002785static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002786 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002787 if( id ){
2788 unixFile *pFile = (unixFile*)id;
2789 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002790 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002791 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002792 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002793 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002794 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002795 ** the last lock is cleared.
2796 */
dan08da86a2009-08-21 17:18:03 +00002797 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002798 }
danb0ac3e32010-06-16 10:55:42 +00002799 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002800 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002801 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002802 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002803 }
drh7ed97b92010-01-20 13:07:21 +00002804 return rc;
drhbfe66312006-10-03 17:40:40 +00002805}
2806
drhd2cb50b2009-01-09 21:41:17 +00002807#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002808/*
2809** The code above is the AFP lock implementation. The code is specific
2810** to MacOSX and does not work on other unix platforms. No alternative
2811** is available. If you don't compile for a mac, then the "unix-afp"
2812** VFS is not available.
2813**
2814********************* End of the AFP lock implementation **********************
2815******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002816
drh7ed97b92010-01-20 13:07:21 +00002817/******************************************************************************
2818*************************** Begin NFS Locking ********************************/
2819
2820#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2821/*
drh308c2a52010-05-14 11:30:18 +00002822 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002823 ** must be either NO_LOCK or SHARED_LOCK.
2824 **
2825 ** If the locking level of the file descriptor is already at or below
2826 ** the requested locking level, this routine is a no-op.
2827 */
drh308c2a52010-05-14 11:30:18 +00002828static int nfsUnlock(sqlite3_file *id, int eFileLock){
2829 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002830}
2831
2832#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2833/*
2834** The code above is the NFS lock implementation. The code is specific
2835** to MacOSX and does not work on other unix platforms. No alternative
2836** is available.
2837**
2838********************* End of the NFS lock implementation **********************
2839******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002840
2841/******************************************************************************
2842**************** Non-locking sqlite3_file methods *****************************
2843**
2844** The next division contains implementations for all methods of the
2845** sqlite3_file object other than the locking methods. The locking
2846** methods were defined in divisions above (one locking method per
2847** division). Those methods that are common to all locking modes
2848** are gather together into this division.
2849*/
drhbfe66312006-10-03 17:40:40 +00002850
2851/*
drh734c9862008-11-28 15:37:20 +00002852** Seek to the offset passed as the second argument, then read cnt
2853** bytes into pBuf. Return the number of bytes actually read.
2854**
2855** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2856** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2857** one system to another. Since SQLite does not define USE_PREAD
2858** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2859** See tickets #2741 and #2681.
2860**
2861** To avoid stomping the errno value on a failed read the lastErrno value
2862** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002863*/
drh734c9862008-11-28 15:37:20 +00002864static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2865 int got;
drh7ed97b92010-01-20 13:07:21 +00002866#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002867 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002868#endif
drh734c9862008-11-28 15:37:20 +00002869 TIMER_START;
2870#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002871 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002872 SimulateIOError( got = -1 );
2873#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002874 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002875 SimulateIOError( got = -1 );
2876#else
2877 newOffset = lseek(id->h, offset, SEEK_SET);
2878 SimulateIOError( newOffset-- );
2879 if( newOffset!=offset ){
2880 if( newOffset == -1 ){
2881 ((unixFile*)id)->lastErrno = errno;
2882 }else{
2883 ((unixFile*)id)->lastErrno = 0;
2884 }
2885 return -1;
2886 }
drhe562be52011-03-02 18:01:10 +00002887 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002888#endif
2889 TIMER_END;
2890 if( got<0 ){
2891 ((unixFile*)id)->lastErrno = errno;
2892 }
drh308c2a52010-05-14 11:30:18 +00002893 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002894 return got;
drhbfe66312006-10-03 17:40:40 +00002895}
2896
2897/*
drh734c9862008-11-28 15:37:20 +00002898** Read data from a file into a buffer. Return SQLITE_OK if all
2899** bytes were read successfully and SQLITE_IOERR if anything goes
2900** wrong.
drh339eb0b2008-03-07 15:34:11 +00002901*/
drh734c9862008-11-28 15:37:20 +00002902static int unixRead(
2903 sqlite3_file *id,
2904 void *pBuf,
2905 int amt,
2906 sqlite3_int64 offset
2907){
dan08da86a2009-08-21 17:18:03 +00002908 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002909 int got;
2910 assert( id );
drh08c6d442009-02-09 17:34:07 +00002911
dan08da86a2009-08-21 17:18:03 +00002912 /* If this is a database file (not a journal, master-journal or temp
2913 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002914#if 0
dane946c392009-08-22 11:39:46 +00002915 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002916 || offset>=PENDING_BYTE+512
2917 || offset+amt<=PENDING_BYTE
2918 );
dan7c246102010-04-12 19:00:29 +00002919#endif
drh08c6d442009-02-09 17:34:07 +00002920
dan08da86a2009-08-21 17:18:03 +00002921 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002922 if( got==amt ){
2923 return SQLITE_OK;
2924 }else if( got<0 ){
2925 /* lastErrno set by seekAndRead */
2926 return SQLITE_IOERR_READ;
2927 }else{
dan08da86a2009-08-21 17:18:03 +00002928 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002929 /* Unread parts of the buffer must be zero-filled */
2930 memset(&((char*)pBuf)[got], 0, amt-got);
2931 return SQLITE_IOERR_SHORT_READ;
2932 }
2933}
2934
2935/*
2936** Seek to the offset in id->offset then read cnt bytes into pBuf.
2937** Return the number of bytes actually read. Update the offset.
2938**
2939** To avoid stomping the errno value on a failed write the lastErrno value
2940** is set before returning.
2941*/
2942static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2943 int got;
drh7ed97b92010-01-20 13:07:21 +00002944#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002945 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002946#endif
drh734c9862008-11-28 15:37:20 +00002947 TIMER_START;
2948#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002949 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002950#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002951 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002952#else
2953 newOffset = lseek(id->h, offset, SEEK_SET);
2954 if( newOffset!=offset ){
2955 if( newOffset == -1 ){
2956 ((unixFile*)id)->lastErrno = errno;
2957 }else{
2958 ((unixFile*)id)->lastErrno = 0;
2959 }
2960 return -1;
2961 }
drhe562be52011-03-02 18:01:10 +00002962 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002963#endif
2964 TIMER_END;
2965 if( got<0 ){
2966 ((unixFile*)id)->lastErrno = errno;
2967 }
2968
drh308c2a52010-05-14 11:30:18 +00002969 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002970 return got;
2971}
2972
2973
2974/*
2975** Write data from a buffer into a file. Return SQLITE_OK on success
2976** or some other error code on failure.
2977*/
2978static int unixWrite(
2979 sqlite3_file *id,
2980 const void *pBuf,
2981 int amt,
2982 sqlite3_int64 offset
2983){
dan08da86a2009-08-21 17:18:03 +00002984 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002985 int wrote = 0;
2986 assert( id );
2987 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002988
dan08da86a2009-08-21 17:18:03 +00002989 /* If this is a database file (not a journal, master-journal or temp
2990 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002991#if 0
dane946c392009-08-22 11:39:46 +00002992 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002993 || offset>=PENDING_BYTE+512
2994 || offset+amt<=PENDING_BYTE
2995 );
dan7c246102010-04-12 19:00:29 +00002996#endif
drh08c6d442009-02-09 17:34:07 +00002997
drh8f941bc2009-01-14 23:03:40 +00002998#ifndef NDEBUG
2999 /* If we are doing a normal write to a database file (as opposed to
3000 ** doing a hot-journal rollback or a write to some file other than a
3001 ** normal database file) then record the fact that the database
3002 ** has changed. If the transaction counter is modified, record that
3003 ** fact too.
3004 */
dan08da86a2009-08-21 17:18:03 +00003005 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003006 pFile->dbUpdate = 1; /* The database has been modified */
3007 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003008 int rc;
drh8f941bc2009-01-14 23:03:40 +00003009 char oldCntr[4];
3010 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003011 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003012 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003013 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003014 pFile->transCntrChng = 1; /* The transaction counter has changed */
3015 }
3016 }
3017 }
3018#endif
3019
dan08da86a2009-08-21 17:18:03 +00003020 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003021 amt -= wrote;
3022 offset += wrote;
3023 pBuf = &((char*)pBuf)[wrote];
3024 }
3025 SimulateIOError(( wrote=(-1), amt=1 ));
3026 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003027
drh734c9862008-11-28 15:37:20 +00003028 if( amt>0 ){
3029 if( wrote<0 ){
3030 /* lastErrno set by seekAndWrite */
3031 return SQLITE_IOERR_WRITE;
3032 }else{
dan08da86a2009-08-21 17:18:03 +00003033 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003034 return SQLITE_FULL;
3035 }
3036 }
dan6e09d692010-07-27 18:34:15 +00003037
drh734c9862008-11-28 15:37:20 +00003038 return SQLITE_OK;
3039}
3040
3041#ifdef SQLITE_TEST
3042/*
3043** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003044** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003045*/
3046int sqlite3_sync_count = 0;
3047int sqlite3_fullsync_count = 0;
3048#endif
3049
3050/*
drh89240432009-03-25 01:06:01 +00003051** We do not trust systems to provide a working fdatasync(). Some do.
3052** Others do no. To be safe, we will stick with the (slower) fsync().
3053** If you know that your system does support fdatasync() correctly,
3054** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003055*/
drh89240432009-03-25 01:06:01 +00003056#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003057# define fdatasync fsync
3058#endif
3059
3060/*
3061** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3062** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3063** only available on Mac OS X. But that could change.
3064*/
3065#ifdef F_FULLFSYNC
3066# define HAVE_FULLFSYNC 1
3067#else
3068# define HAVE_FULLFSYNC 0
3069#endif
3070
3071
3072/*
3073** The fsync() system call does not work as advertised on many
3074** unix systems. The following procedure is an attempt to make
3075** it work better.
3076**
3077** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3078** for testing when we want to run through the test suite quickly.
3079** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3080** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3081** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003082**
3083** SQLite sets the dataOnly flag if the size of the file is unchanged.
3084** The idea behind dataOnly is that it should only write the file content
3085** to disk, not the inode. We only set dataOnly if the file size is
3086** unchanged since the file size is part of the inode. However,
3087** Ted Ts'o tells us that fdatasync() will also write the inode if the
3088** file size has changed. The only real difference between fdatasync()
3089** and fsync(), Ted tells us, is that fdatasync() will not flush the
3090** inode if the mtime or owner or other inode attributes have changed.
3091** We only care about the file size, not the other file attributes, so
3092** as far as SQLite is concerned, an fdatasync() is always adequate.
3093** So, we always use fdatasync() if it is available, regardless of
3094** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003095*/
3096static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003097 int rc;
drh734c9862008-11-28 15:37:20 +00003098
3099 /* The following "ifdef/elif/else/" block has the same structure as
3100 ** the one below. It is replicated here solely to avoid cluttering
3101 ** up the real code with the UNUSED_PARAMETER() macros.
3102 */
3103#ifdef SQLITE_NO_SYNC
3104 UNUSED_PARAMETER(fd);
3105 UNUSED_PARAMETER(fullSync);
3106 UNUSED_PARAMETER(dataOnly);
3107#elif HAVE_FULLFSYNC
3108 UNUSED_PARAMETER(dataOnly);
3109#else
3110 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003111 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003112#endif
3113
3114 /* Record the number of times that we do a normal fsync() and
3115 ** FULLSYNC. This is used during testing to verify that this procedure
3116 ** gets called with the correct arguments.
3117 */
3118#ifdef SQLITE_TEST
3119 if( fullSync ) sqlite3_fullsync_count++;
3120 sqlite3_sync_count++;
3121#endif
3122
3123 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3124 ** no-op
3125 */
3126#ifdef SQLITE_NO_SYNC
3127 rc = SQLITE_OK;
3128#elif HAVE_FULLFSYNC
3129 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003130 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003131 }else{
3132 rc = 1;
3133 }
3134 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003135 ** It shouldn't be possible for fullfsync to fail on the local
3136 ** file system (on OSX), so failure indicates that FULLFSYNC
3137 ** isn't supported for this file system. So, attempt an fsync
3138 ** and (for now) ignore the overhead of a superfluous fcntl call.
3139 ** It'd be better to detect fullfsync support once and avoid
3140 ** the fcntl call every time sync is called.
3141 */
drh734c9862008-11-28 15:37:20 +00003142 if( rc ) rc = fsync(fd);
3143
drh7ed97b92010-01-20 13:07:21 +00003144#elif defined(__APPLE__)
3145 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3146 ** so currently we default to the macro that redefines fdatasync to fsync
3147 */
3148 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003149#else
drh0b647ff2009-03-21 14:41:04 +00003150 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003151#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003152 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003153 rc = fsync(fd);
3154 }
drh0b647ff2009-03-21 14:41:04 +00003155#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003156#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3157
3158 if( OS_VXWORKS && rc!= -1 ){
3159 rc = 0;
3160 }
chw97185482008-11-17 08:05:31 +00003161 return rc;
drhbfe66312006-10-03 17:40:40 +00003162}
3163
drh734c9862008-11-28 15:37:20 +00003164/*
3165** Make sure all writes to a particular file are committed to disk.
3166**
3167** If dataOnly==0 then both the file itself and its metadata (file
3168** size, access time, etc) are synced. If dataOnly!=0 then only the
3169** file data is synced.
3170**
3171** Under Unix, also make sure that the directory entry for the file
3172** has been created by fsync-ing the directory that contains the file.
3173** If we do not do this and we encounter a power failure, the directory
3174** entry for the journal might not exist after we reboot. The next
3175** SQLite to access the file will not know that the journal exists (because
3176** the directory entry for the journal was never created) and the transaction
3177** will not roll back - possibly leading to database corruption.
3178*/
3179static int unixSync(sqlite3_file *id, int flags){
3180 int rc;
3181 unixFile *pFile = (unixFile*)id;
3182
3183 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3184 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3185
3186 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3187 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3188 || (flags&0x0F)==SQLITE_SYNC_FULL
3189 );
3190
3191 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3192 ** line is to test that doing so does not cause any problems.
3193 */
3194 SimulateDiskfullError( return SQLITE_FULL );
3195
3196 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003197 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003198 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3199 SimulateIOError( rc=1 );
3200 if( rc ){
3201 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003202 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003203 }
3204 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003205 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3206 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003207#ifndef SQLITE_DISABLE_DIRSYNC
3208 /* The directory sync is only attempted if full_fsync is
3209 ** turned off or unavailable. If a full_fsync occurred above,
3210 ** then the directory sync is superfluous.
3211 */
3212 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3213 /*
3214 ** We have received multiple reports of fsync() returning
3215 ** errors when applied to directories on certain file systems.
3216 ** A failed directory sync is not a big deal. So it seems
3217 ** better to ignore the error. Ticket #1657
3218 */
3219 /* pFile->lastErrno = errno; */
3220 /* return SQLITE_IOERR; */
3221 }
3222#endif
drh0e9365c2011-03-02 02:08:13 +00003223 /* Only need to sync once, so close the directory when we are done */
3224 robust_close(pFile, pFile->dirfd, __LINE__);
3225 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003226 }
3227 return rc;
3228}
3229
3230/*
3231** Truncate an open file to a specified size
3232*/
3233static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003234 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003235 int rc;
dan6e09d692010-07-27 18:34:15 +00003236 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003237 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003238
3239 /* If the user has configured a chunk-size for this file, truncate the
3240 ** file so that it consists of an integer number of chunks (i.e. the
3241 ** actual file size after the operation may be larger than the requested
3242 ** size).
3243 */
3244 if( pFile->szChunk ){
3245 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3246 }
3247
drhff812312011-02-23 13:33:46 +00003248 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003249 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003250 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003251 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003252 }else{
drh3313b142009-11-06 04:13:18 +00003253#ifndef NDEBUG
3254 /* If we are doing a normal write to a database file (as opposed to
3255 ** doing a hot-journal rollback or a write to some file other than a
3256 ** normal database file) and we truncate the file to zero length,
3257 ** that effectively updates the change counter. This might happen
3258 ** when restoring a database using the backup API from a zero-length
3259 ** source.
3260 */
dan6e09d692010-07-27 18:34:15 +00003261 if( pFile->inNormalWrite && nByte==0 ){
3262 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003263 }
3264#endif
3265
drh734c9862008-11-28 15:37:20 +00003266 return SQLITE_OK;
3267 }
3268}
3269
3270/*
3271** Determine the current size of a file in bytes
3272*/
3273static int unixFileSize(sqlite3_file *id, i64 *pSize){
3274 int rc;
3275 struct stat buf;
3276 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003277 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003278 SimulateIOError( rc=1 );
3279 if( rc!=0 ){
3280 ((unixFile*)id)->lastErrno = errno;
3281 return SQLITE_IOERR_FSTAT;
3282 }
3283 *pSize = buf.st_size;
3284
drh8af6c222010-05-14 12:43:01 +00003285 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003286 ** writes a single byte into that file in order to work around a bug
3287 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3288 ** layers, we need to report this file size as zero even though it is
3289 ** really 1. Ticket #3260.
3290 */
3291 if( *pSize==1 ) *pSize = 0;
3292
3293
3294 return SQLITE_OK;
3295}
3296
drhd2cb50b2009-01-09 21:41:17 +00003297#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003298/*
3299** Handler for proxy-locking file-control verbs. Defined below in the
3300** proxying locking division.
3301*/
3302static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003303#endif
drh715ff302008-12-03 22:32:44 +00003304
dan502019c2010-07-28 14:26:17 +00003305/*
3306** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3307** file-control operation.
3308**
3309** If the user has configured a chunk-size for this file, it could be
3310** that the file needs to be extended at this point. Otherwise, the
3311** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3312*/
3313static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3314 if( pFile->szChunk ){
3315 i64 nSize; /* Required file size */
3316 struct stat buf; /* Used to hold return values of fstat() */
3317
drh99ab3b12011-03-02 15:09:07 +00003318 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003319
3320 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3321 if( nSize>(i64)buf.st_size ){
3322#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003323 int rc;
3324 do{
drhe562be52011-03-02 18:01:10 +00003325 rc = osFallocate(pFile->.h, buf.st_size, nSize-buf.st_size;
drhff812312011-02-23 13:33:46 +00003326 }while( rc<0 && errno=EINTR );
3327 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003328#else
3329 /* If the OS does not have posix_fallocate(), fake it. First use
3330 ** ftruncate() to set the file size, then write a single byte to
3331 ** the last byte in each block within the extended region. This
3332 ** is the same technique used by glibc to implement posix_fallocate()
3333 ** on systems that do not have a real fallocate() system call.
3334 */
3335 int nBlk = buf.st_blksize; /* File-system block size */
3336 i64 iWrite; /* Next offset to write to */
3337 int nWrite; /* Return value from seekAndWrite() */
3338
drhff812312011-02-23 13:33:46 +00003339 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003340 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003341 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003342 }
3343 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3344 do {
3345 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3346 iWrite += nBlk;
3347 } while( nWrite==1 && iWrite<nSize );
3348 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3349#endif
3350 }
3351 }
3352
3353 return SQLITE_OK;
3354}
danielk1977ad94b582007-08-20 06:44:22 +00003355
danielk1977e3026632004-06-22 11:29:02 +00003356/*
drh9e33c2c2007-08-31 18:34:59 +00003357** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003358*/
drhcc6bb3e2007-08-31 16:11:35 +00003359static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003360 switch( op ){
3361 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003362 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003363 return SQLITE_OK;
3364 }
drh7708e972008-11-29 00:56:52 +00003365 case SQLITE_LAST_ERRNO: {
3366 *(int*)pArg = ((unixFile*)id)->lastErrno;
3367 return SQLITE_OK;
3368 }
dan6e09d692010-07-27 18:34:15 +00003369 case SQLITE_FCNTL_CHUNK_SIZE: {
3370 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003371 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003372 }
drh9ff27ec2010-05-19 19:26:05 +00003373 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003374 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003375 }
drh8f941bc2009-01-14 23:03:40 +00003376#ifndef NDEBUG
3377 /* The pager calls this method to signal that it has done
3378 ** a rollback and that the database is therefore unchanged and
3379 ** it hence it is OK for the transaction change counter to be
3380 ** unchanged.
3381 */
3382 case SQLITE_FCNTL_DB_UNCHANGED: {
3383 ((unixFile*)id)->dbUpdate = 0;
3384 return SQLITE_OK;
3385 }
3386#endif
drhd2cb50b2009-01-09 21:41:17 +00003387#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003388 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003389 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003390 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003391 }
drhd2cb50b2009-01-09 21:41:17 +00003392#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003393 case SQLITE_FCNTL_SYNC_OMITTED: {
3394 return SQLITE_OK; /* A no-op */
3395 }
drh9e33c2c2007-08-31 18:34:59 +00003396 }
drh0b52b7d2011-01-26 19:46:22 +00003397 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003398}
3399
3400/*
danielk1977a3d4c882007-03-23 10:08:38 +00003401** Return the sector size in bytes of the underlying block device for
3402** the specified file. This is almost always 512 bytes, but may be
3403** larger for some devices.
3404**
3405** SQLite code assumes this function cannot fail. It also assumes that
3406** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003407** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003408** same for both.
3409*/
danielk1977397d65f2008-11-19 11:35:39 +00003410static int unixSectorSize(sqlite3_file *NotUsed){
3411 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003412 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003413}
3414
danielk197790949c22007-08-17 16:50:38 +00003415/*
danielk1977397d65f2008-11-19 11:35:39 +00003416** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003417*/
danielk1977397d65f2008-11-19 11:35:39 +00003418static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3419 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003420 return 0;
3421}
3422
drhd9e5c4f2010-05-12 18:01:39 +00003423#ifndef SQLITE_OMIT_WAL
3424
3425
3426/*
drhd91c68f2010-05-14 14:52:25 +00003427** Object used to represent an shared memory buffer.
3428**
3429** When multiple threads all reference the same wal-index, each thread
3430** has its own unixShm object, but they all point to a single instance
3431** of this unixShmNode object. In other words, each wal-index is opened
3432** only once per process.
3433**
3434** Each unixShmNode object is connected to a single unixInodeInfo object.
3435** We could coalesce this object into unixInodeInfo, but that would mean
3436** every open file that does not use shared memory (in other words, most
3437** open files) would have to carry around this extra information. So
3438** the unixInodeInfo object contains a pointer to this unixShmNode object
3439** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003440**
3441** unixMutexHeld() must be true when creating or destroying
3442** this object or while reading or writing the following fields:
3443**
3444** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003445**
3446** The following fields are read-only after the object is created:
3447**
3448** fid
3449** zFilename
3450**
drhd91c68f2010-05-14 14:52:25 +00003451** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003452** unixMutexHeld() is true when reading or writing any other field
3453** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003454*/
drhd91c68f2010-05-14 14:52:25 +00003455struct unixShmNode {
3456 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003457 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003458 char *zFilename; /* Name of the mmapped file */
3459 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003460 int szRegion; /* Size of shared-memory regions */
3461 int nRegion; /* Size of array apRegion */
3462 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003463 int nRef; /* Number of unixShm objects pointing to this */
3464 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003465#ifdef SQLITE_DEBUG
3466 u8 exclMask; /* Mask of exclusive locks held */
3467 u8 sharedMask; /* Mask of shared locks held */
3468 u8 nextShmId; /* Next available unixShm.id value */
3469#endif
3470};
3471
3472/*
drhd9e5c4f2010-05-12 18:01:39 +00003473** Structure used internally by this VFS to record the state of an
3474** open shared memory connection.
3475**
drhd91c68f2010-05-14 14:52:25 +00003476** The following fields are initialized when this object is created and
3477** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003478**
drhd91c68f2010-05-14 14:52:25 +00003479** unixShm.pFile
3480** unixShm.id
3481**
3482** All other fields are read/write. The unixShm.pFile->mutex must be held
3483** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003484*/
3485struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003486 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3487 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003488 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003489 u16 sharedMask; /* Mask of shared locks held */
3490 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003491#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003492 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003493#endif
3494};
3495
3496/*
drhd9e5c4f2010-05-12 18:01:39 +00003497** Constants used for locking
3498*/
drhbd9676c2010-06-23 17:58:38 +00003499#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003500#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003501
drhd9e5c4f2010-05-12 18:01:39 +00003502/*
drh73b64e42010-05-30 19:55:15 +00003503** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003504**
3505** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3506** otherwise.
3507*/
3508static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003509 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3510 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003511 int ofst, /* First byte of the locking range */
3512 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003513){
3514 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003515 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003516
drhd91c68f2010-05-14 14:52:25 +00003517 /* Access to the unixShmNode object is serialized by the caller */
3518 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003519
drh73b64e42010-05-30 19:55:15 +00003520 /* Shared locks never span more than one byte */
3521 assert( n==1 || lockType!=F_RDLCK );
3522
3523 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003524 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003525
drhd9e5c4f2010-05-12 18:01:39 +00003526 /* Initialize the locking parameters */
3527 memset(&f, 0, sizeof(f));
3528 f.l_type = lockType;
3529 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003530 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003531 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003532
drh99ab3b12011-03-02 15:09:07 +00003533 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003534 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3535
3536 /* Update the global lock state and do debug tracing */
3537#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003538 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003539 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003540 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003541 if( rc==SQLITE_OK ){
3542 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003543 OSTRACE(("unlock %d ok", ofst));
3544 pShmNode->exclMask &= ~mask;
3545 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003546 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003547 OSTRACE(("read-lock %d ok", ofst));
3548 pShmNode->exclMask &= ~mask;
3549 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003550 }else{
3551 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003552 OSTRACE(("write-lock %d ok", ofst));
3553 pShmNode->exclMask |= mask;
3554 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003555 }
3556 }else{
3557 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003558 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003559 }else if( lockType==F_RDLCK ){
3560 OSTRACE(("read-lock failed"));
3561 }else{
3562 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003563 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003564 }
3565 }
drh20e1f082010-05-31 16:10:12 +00003566 OSTRACE((" - afterwards %03x,%03x\n",
3567 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003568 }
drhd9e5c4f2010-05-12 18:01:39 +00003569#endif
3570
3571 return rc;
3572}
3573
drhd9e5c4f2010-05-12 18:01:39 +00003574
3575/*
drhd91c68f2010-05-14 14:52:25 +00003576** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003577**
3578** This is not a VFS shared-memory method; it is a utility function called
3579** by VFS shared-memory methods.
3580*/
drhd91c68f2010-05-14 14:52:25 +00003581static void unixShmPurge(unixFile *pFd){
3582 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003583 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003584 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003585 int i;
drhd91c68f2010-05-14 14:52:25 +00003586 assert( p->pInode==pFd->pInode );
3587 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003588 for(i=0; i<p->nRegion; i++){
3589 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003590 }
dan18801912010-06-14 14:07:50 +00003591 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003592 if( p->h>=0 ){
3593 robust_close(pFd, p->h, __LINE__);
3594 p->h = -1;
3595 }
drhd91c68f2010-05-14 14:52:25 +00003596 p->pInode->pShmNode = 0;
3597 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003598 }
3599}
3600
3601/*
danda9fe0c2010-07-13 18:44:03 +00003602** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003603** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003604**
drh7234c6d2010-06-19 15:10:09 +00003605** The file used to implement shared-memory is in the same directory
3606** as the open database file and has the same name as the open database
3607** file with the "-shm" suffix added. For example, if the database file
3608** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003609** for shared memory will be called "/home/user1/config.db-shm".
3610**
3611** Another approach to is to use files in /dev/shm or /dev/tmp or an
3612** some other tmpfs mount. But if a file in a different directory
3613** from the database file is used, then differing access permissions
3614** or a chroot() might cause two different processes on the same
3615** database to end up using different files for shared memory -
3616** meaning that their memory would not really be shared - resulting
3617** in database corruption. Nevertheless, this tmpfs file usage
3618** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3619** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3620** option results in an incompatible build of SQLite; builds of SQLite
3621** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3622** same database file at the same time, database corruption will likely
3623** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3624** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003625**
3626** When opening a new shared-memory file, if no other instances of that
3627** file are currently open, in this process or in other processes, then
3628** the file must be truncated to zero length or have its header cleared.
3629*/
danda9fe0c2010-07-13 18:44:03 +00003630static int unixOpenSharedMemory(unixFile *pDbFd){
3631 struct unixShm *p = 0; /* The connection to be opened */
3632 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3633 int rc; /* Result code */
3634 unixInodeInfo *pInode; /* The inode of fd */
3635 char *zShmFilename; /* Name of the file used for SHM */
3636 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003637
danda9fe0c2010-07-13 18:44:03 +00003638 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003639 p = sqlite3_malloc( sizeof(*p) );
3640 if( p==0 ) return SQLITE_NOMEM;
3641 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003642 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003643
danda9fe0c2010-07-13 18:44:03 +00003644 /* Check to see if a unixShmNode object already exists. Reuse an existing
3645 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003646 */
3647 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003648 pInode = pDbFd->pInode;
3649 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003650 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003651 struct stat sStat; /* fstat() info for database file */
3652
3653 /* Call fstat() to figure out the permissions on the database file. If
3654 ** a new *-shm file is created, an attempt will be made to create it
3655 ** with the same permissions. The actual permissions the file is created
3656 ** with are subject to the current umask setting.
3657 */
drh99ab3b12011-03-02 15:09:07 +00003658 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00003659 rc = SQLITE_IOERR_FSTAT;
3660 goto shm_open_err;
3661 }
3662
drha4ced192010-07-15 18:32:40 +00003663#ifdef SQLITE_SHM_DIRECTORY
3664 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3665#else
drh7234c6d2010-06-19 15:10:09 +00003666 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003667#endif
drh7234c6d2010-06-19 15:10:09 +00003668 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003669 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003670 rc = SQLITE_NOMEM;
3671 goto shm_open_err;
3672 }
drhd91c68f2010-05-14 14:52:25 +00003673 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003674 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003675#ifdef SQLITE_SHM_DIRECTORY
3676 sqlite3_snprintf(nShmFilename, zShmFilename,
3677 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3678 (u32)sStat.st_ino, (u32)sStat.st_dev);
3679#else
drh7234c6d2010-06-19 15:10:09 +00003680 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003681#endif
drhd91c68f2010-05-14 14:52:25 +00003682 pShmNode->h = -1;
3683 pDbFd->pInode->pShmNode = pShmNode;
3684 pShmNode->pInode = pDbFd->pInode;
3685 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3686 if( pShmNode->mutex==0 ){
3687 rc = SQLITE_NOMEM;
3688 goto shm_open_err;
3689 }
drhd9e5c4f2010-05-12 18:01:39 +00003690
drhad4f1e52011-03-04 15:43:57 +00003691 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3692 (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003693 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003694 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003695 goto shm_open_err;
3696 }
3697
drhd9e5c4f2010-05-12 18:01:39 +00003698 /* Check to see if another process is holding the dead-man switch.
3699 ** If not, truncate the file to zero length.
3700 */
drhd91c68f2010-05-14 14:52:25 +00003701 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003702 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhff812312011-02-23 13:33:46 +00003703 if( robust_ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003704 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003705 }
3706 }
3707 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003708 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003709 }
3710 if( rc ) goto shm_open_err;
3711 }
3712
drhd91c68f2010-05-14 14:52:25 +00003713 /* Make the new connection a child of the unixShmNode */
3714 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003715#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003716 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003717#endif
drhd91c68f2010-05-14 14:52:25 +00003718 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003719 pDbFd->pShm = p;
3720 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003721
3722 /* The reference count on pShmNode has already been incremented under
3723 ** the cover of the unixEnterMutex() mutex and the pointer from the
3724 ** new (struct unixShm) object to the pShmNode has been set. All that is
3725 ** left to do is to link the new object into the linked list starting
3726 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3727 ** mutex.
3728 */
3729 sqlite3_mutex_enter(pShmNode->mutex);
3730 p->pNext = pShmNode->pFirst;
3731 pShmNode->pFirst = p;
3732 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003733 return SQLITE_OK;
3734
3735 /* Jump here on any error */
3736shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003737 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003738 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003739 unixLeaveMutex();
3740 return rc;
3741}
3742
3743/*
danda9fe0c2010-07-13 18:44:03 +00003744** This function is called to obtain a pointer to region iRegion of the
3745** shared-memory associated with the database file fd. Shared-memory regions
3746** are numbered starting from zero. Each shared-memory region is szRegion
3747** bytes in size.
3748**
3749** If an error occurs, an error code is returned and *pp is set to NULL.
3750**
3751** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3752** region has not been allocated (by any client, including one running in a
3753** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3754** bExtend is non-zero and the requested shared-memory region has not yet
3755** been allocated, it is allocated by this function.
3756**
3757** If the shared-memory region has already been allocated or is allocated by
3758** this call as described above, then it is mapped into this processes
3759** address space (if it is not already), *pp is set to point to the mapped
3760** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003761*/
danda9fe0c2010-07-13 18:44:03 +00003762static int unixShmMap(
3763 sqlite3_file *fd, /* Handle open on database file */
3764 int iRegion, /* Region to retrieve */
3765 int szRegion, /* Size of regions */
3766 int bExtend, /* True to extend file if necessary */
3767 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003768){
danda9fe0c2010-07-13 18:44:03 +00003769 unixFile *pDbFd = (unixFile*)fd;
3770 unixShm *p;
3771 unixShmNode *pShmNode;
3772 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003773
danda9fe0c2010-07-13 18:44:03 +00003774 /* If the shared-memory file has not yet been opened, open it now. */
3775 if( pDbFd->pShm==0 ){
3776 rc = unixOpenSharedMemory(pDbFd);
3777 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003778 }
drhd9e5c4f2010-05-12 18:01:39 +00003779
danda9fe0c2010-07-13 18:44:03 +00003780 p = pDbFd->pShm;
3781 pShmNode = p->pShmNode;
3782 sqlite3_mutex_enter(pShmNode->mutex);
3783 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3784
3785 if( pShmNode->nRegion<=iRegion ){
3786 char **apNew; /* New apRegion[] array */
3787 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3788 struct stat sStat; /* Used by fstat() */
3789
3790 pShmNode->szRegion = szRegion;
3791
3792 /* The requested region is not mapped into this processes address space.
3793 ** Check to see if it has been allocated (i.e. if the wal-index file is
3794 ** large enough to contain the requested region).
3795 */
drh99ab3b12011-03-02 15:09:07 +00003796 if( osFstat(pShmNode->h, &sStat) ){
danda9fe0c2010-07-13 18:44:03 +00003797 rc = SQLITE_IOERR_SHMSIZE;
3798 goto shmpage_out;
3799 }
3800
3801 if( sStat.st_size<nByte ){
3802 /* The requested memory region does not exist. If bExtend is set to
3803 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3804 **
3805 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3806 ** the requested memory region.
3807 */
3808 if( !bExtend ) goto shmpage_out;
drhff812312011-02-23 13:33:46 +00003809 if( robust_ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003810 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003811 goto shmpage_out;
3812 }
3813 }
3814
3815 /* Map the requested memory region into this processes address space. */
3816 apNew = (char **)sqlite3_realloc(
3817 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3818 );
3819 if( !apNew ){
3820 rc = SQLITE_IOERR_NOMEM;
3821 goto shmpage_out;
3822 }
3823 pShmNode->apRegion = apNew;
3824 while(pShmNode->nRegion<=iRegion){
3825 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003826 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003827 );
3828 if( pMem==MAP_FAILED ){
3829 rc = SQLITE_IOERR;
3830 goto shmpage_out;
3831 }
3832 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3833 pShmNode->nRegion++;
3834 }
3835 }
3836
3837shmpage_out:
3838 if( pShmNode->nRegion>iRegion ){
3839 *pp = pShmNode->apRegion[iRegion];
3840 }else{
3841 *pp = 0;
3842 }
3843 sqlite3_mutex_leave(pShmNode->mutex);
3844 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003845}
3846
3847/*
drhd9e5c4f2010-05-12 18:01:39 +00003848** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003849**
3850** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3851** different here than in posix. In xShmLock(), one can go from unlocked
3852** to shared and back or from unlocked to exclusive and back. But one may
3853** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003854*/
3855static int unixShmLock(
3856 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003857 int ofst, /* First lock to acquire or release */
3858 int n, /* Number of locks to acquire or release */
3859 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003860){
drh73b64e42010-05-30 19:55:15 +00003861 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3862 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3863 unixShm *pX; /* For looping over all siblings */
3864 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3865 int rc = SQLITE_OK; /* Result code */
3866 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003867
drhd91c68f2010-05-14 14:52:25 +00003868 assert( pShmNode==pDbFd->pInode->pShmNode );
3869 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003870 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003871 assert( n>=1 );
3872 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3873 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3874 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3875 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3876 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003877
drhc99597c2010-05-31 01:41:15 +00003878 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003879 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003880 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003881 if( flags & SQLITE_SHM_UNLOCK ){
3882 u16 allMask = 0; /* Mask of locks held by siblings */
3883
3884 /* See if any siblings hold this same lock */
3885 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3886 if( pX==p ) continue;
3887 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3888 allMask |= pX->sharedMask;
3889 }
3890
3891 /* Unlock the system-level locks */
3892 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003893 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003894 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003895 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003896 }
drh73b64e42010-05-30 19:55:15 +00003897
3898 /* Undo the local locks */
3899 if( rc==SQLITE_OK ){
3900 p->exclMask &= ~mask;
3901 p->sharedMask &= ~mask;
3902 }
3903 }else if( flags & SQLITE_SHM_SHARED ){
3904 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3905
3906 /* Find out which shared locks are already held by sibling connections.
3907 ** If any sibling already holds an exclusive lock, go ahead and return
3908 ** SQLITE_BUSY.
3909 */
3910 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003911 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003912 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003913 break;
3914 }
3915 allShared |= pX->sharedMask;
3916 }
3917
3918 /* Get shared locks at the system level, if necessary */
3919 if( rc==SQLITE_OK ){
3920 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003921 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003922 }else{
drh73b64e42010-05-30 19:55:15 +00003923 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003924 }
drhd9e5c4f2010-05-12 18:01:39 +00003925 }
drh73b64e42010-05-30 19:55:15 +00003926
3927 /* Get the local shared locks */
3928 if( rc==SQLITE_OK ){
3929 p->sharedMask |= mask;
3930 }
3931 }else{
3932 /* Make sure no sibling connections hold locks that will block this
3933 ** lock. If any do, return SQLITE_BUSY right away.
3934 */
3935 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003936 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3937 rc = SQLITE_BUSY;
3938 break;
3939 }
3940 }
3941
3942 /* Get the exclusive locks at the system level. Then if successful
3943 ** also mark the local connection as being locked.
3944 */
3945 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003946 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003947 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003948 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003949 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003950 }
drhd9e5c4f2010-05-12 18:01:39 +00003951 }
3952 }
drhd91c68f2010-05-14 14:52:25 +00003953 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003954 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3955 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003956 return rc;
3957}
3958
drh286a2882010-05-20 23:51:06 +00003959/*
3960** Implement a memory barrier or memory fence on shared memory.
3961**
3962** All loads and stores begun before the barrier must complete before
3963** any load or store begun after the barrier.
3964*/
3965static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003966 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003967){
drhff828942010-06-26 21:34:06 +00003968 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003969 unixEnterMutex();
3970 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003971}
3972
dan18801912010-06-14 14:07:50 +00003973/*
danda9fe0c2010-07-13 18:44:03 +00003974** Close a connection to shared-memory. Delete the underlying
3975** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003976**
3977** If there is no shared memory associated with the connection then this
3978** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003979*/
danda9fe0c2010-07-13 18:44:03 +00003980static int unixShmUnmap(
3981 sqlite3_file *fd, /* The underlying database file */
3982 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003983){
danda9fe0c2010-07-13 18:44:03 +00003984 unixShm *p; /* The connection to be closed */
3985 unixShmNode *pShmNode; /* The underlying shared-memory file */
3986 unixShm **pp; /* For looping over sibling connections */
3987 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003988
danda9fe0c2010-07-13 18:44:03 +00003989 pDbFd = (unixFile*)fd;
3990 p = pDbFd->pShm;
3991 if( p==0 ) return SQLITE_OK;
3992 pShmNode = p->pShmNode;
3993
3994 assert( pShmNode==pDbFd->pInode->pShmNode );
3995 assert( pShmNode->pInode==pDbFd->pInode );
3996
3997 /* Remove connection p from the set of connections associated
3998 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003999 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004000 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4001 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004002
danda9fe0c2010-07-13 18:44:03 +00004003 /* Free the connection p */
4004 sqlite3_free(p);
4005 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004006 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004007
4008 /* If pShmNode->nRef has reached 0, then close the underlying
4009 ** shared-memory file, too */
4010 unixEnterMutex();
4011 assert( pShmNode->nRef>0 );
4012 pShmNode->nRef--;
4013 if( pShmNode->nRef==0 ){
4014 if( deleteFlag ) unlink(pShmNode->zFilename);
4015 unixShmPurge(pDbFd);
4016 }
4017 unixLeaveMutex();
4018
4019 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004020}
drh286a2882010-05-20 23:51:06 +00004021
danda9fe0c2010-07-13 18:44:03 +00004022
drhd9e5c4f2010-05-12 18:01:39 +00004023#else
drh6b017cc2010-06-14 18:01:46 +00004024# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004025# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004026# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004027# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004028#endif /* #ifndef SQLITE_OMIT_WAL */
4029
drh734c9862008-11-28 15:37:20 +00004030/*
4031** Here ends the implementation of all sqlite3_file methods.
4032**
4033********************** End sqlite3_file Methods *******************************
4034******************************************************************************/
4035
4036/*
drh6b9d6dd2008-12-03 19:34:47 +00004037** This division contains definitions of sqlite3_io_methods objects that
4038** implement various file locking strategies. It also contains definitions
4039** of "finder" functions. A finder-function is used to locate the appropriate
4040** sqlite3_io_methods object for a particular database file. The pAppData
4041** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4042** the correct finder-function for that VFS.
4043**
4044** Most finder functions return a pointer to a fixed sqlite3_io_methods
4045** object. The only interesting finder-function is autolockIoFinder, which
4046** looks at the filesystem type and tries to guess the best locking
4047** strategy from that.
4048**
drh1875f7a2008-12-08 18:19:17 +00004049** For finder-funtion F, two objects are created:
4050**
4051** (1) The real finder-function named "FImpt()".
4052**
dane946c392009-08-22 11:39:46 +00004053** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004054**
4055**
4056** A pointer to the F pointer is used as the pAppData value for VFS
4057** objects. We have to do this instead of letting pAppData point
4058** directly at the finder-function since C90 rules prevent a void*
4059** from be cast into a function pointer.
4060**
drh6b9d6dd2008-12-03 19:34:47 +00004061**
drh7708e972008-11-29 00:56:52 +00004062** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004063**
drh7708e972008-11-29 00:56:52 +00004064** * A constant sqlite3_io_methods object call METHOD that has locking
4065** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4066**
4067** * An I/O method finder function called FINDER that returns a pointer
4068** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004069*/
drhd9e5c4f2010-05-12 18:01:39 +00004070#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004071static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004072 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004073 CLOSE, /* xClose */ \
4074 unixRead, /* xRead */ \
4075 unixWrite, /* xWrite */ \
4076 unixTruncate, /* xTruncate */ \
4077 unixSync, /* xSync */ \
4078 unixFileSize, /* xFileSize */ \
4079 LOCK, /* xLock */ \
4080 UNLOCK, /* xUnlock */ \
4081 CKLOCK, /* xCheckReservedLock */ \
4082 unixFileControl, /* xFileControl */ \
4083 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004084 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004085 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004086 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004087 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004088 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004089}; \
drh0c2694b2009-09-03 16:23:44 +00004090static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4091 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004092 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004093} \
drh0c2694b2009-09-03 16:23:44 +00004094static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004095 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004096
4097/*
4098** Here are all of the sqlite3_io_methods objects for each of the
4099** locking strategies. Functions that return pointers to these methods
4100** are also created.
4101*/
4102IOMETHODS(
4103 posixIoFinder, /* Finder function name */
4104 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004105 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004106 unixClose, /* xClose method */
4107 unixLock, /* xLock method */
4108 unixUnlock, /* xUnlock method */
4109 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004110)
drh7708e972008-11-29 00:56:52 +00004111IOMETHODS(
4112 nolockIoFinder, /* Finder function name */
4113 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004114 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004115 nolockClose, /* xClose method */
4116 nolockLock, /* xLock method */
4117 nolockUnlock, /* xUnlock method */
4118 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004119)
drh7708e972008-11-29 00:56:52 +00004120IOMETHODS(
4121 dotlockIoFinder, /* Finder function name */
4122 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004123 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004124 dotlockClose, /* xClose method */
4125 dotlockLock, /* xLock method */
4126 dotlockUnlock, /* xUnlock method */
4127 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004128)
drh7708e972008-11-29 00:56:52 +00004129
chw78a13182009-04-07 05:35:03 +00004130#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004131IOMETHODS(
4132 flockIoFinder, /* Finder function name */
4133 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004134 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004135 flockClose, /* xClose method */
4136 flockLock, /* xLock method */
4137 flockUnlock, /* xUnlock method */
4138 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004139)
drh7708e972008-11-29 00:56:52 +00004140#endif
4141
drh6c7d5c52008-11-21 20:32:33 +00004142#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004143IOMETHODS(
4144 semIoFinder, /* Finder function name */
4145 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004146 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004147 semClose, /* xClose method */
4148 semLock, /* xLock method */
4149 semUnlock, /* xUnlock method */
4150 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004151)
aswiftaebf4132008-11-21 00:10:35 +00004152#endif
drh7708e972008-11-29 00:56:52 +00004153
drhd2cb50b2009-01-09 21:41:17 +00004154#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004155IOMETHODS(
4156 afpIoFinder, /* Finder function name */
4157 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004158 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004159 afpClose, /* xClose method */
4160 afpLock, /* xLock method */
4161 afpUnlock, /* xUnlock method */
4162 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004163)
drh715ff302008-12-03 22:32:44 +00004164#endif
4165
4166/*
4167** The proxy locking method is a "super-method" in the sense that it
4168** opens secondary file descriptors for the conch and lock files and
4169** it uses proxy, dot-file, AFP, and flock() locking methods on those
4170** secondary files. For this reason, the division that implements
4171** proxy locking is located much further down in the file. But we need
4172** to go ahead and define the sqlite3_io_methods and finder function
4173** for proxy locking here. So we forward declare the I/O methods.
4174*/
drhd2cb50b2009-01-09 21:41:17 +00004175#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004176static int proxyClose(sqlite3_file*);
4177static int proxyLock(sqlite3_file*, int);
4178static int proxyUnlock(sqlite3_file*, int);
4179static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004180IOMETHODS(
4181 proxyIoFinder, /* Finder function name */
4182 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004183 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004184 proxyClose, /* xClose method */
4185 proxyLock, /* xLock method */
4186 proxyUnlock, /* xUnlock method */
4187 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004188)
aswiftaebf4132008-11-21 00:10:35 +00004189#endif
drh7708e972008-11-29 00:56:52 +00004190
drh7ed97b92010-01-20 13:07:21 +00004191/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4192#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4193IOMETHODS(
4194 nfsIoFinder, /* Finder function name */
4195 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004196 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004197 unixClose, /* xClose method */
4198 unixLock, /* xLock method */
4199 nfsUnlock, /* xUnlock method */
4200 unixCheckReservedLock /* xCheckReservedLock method */
4201)
4202#endif
drh7708e972008-11-29 00:56:52 +00004203
drhd2cb50b2009-01-09 21:41:17 +00004204#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004205/*
drh6b9d6dd2008-12-03 19:34:47 +00004206** This "finder" function attempts to determine the best locking strategy
4207** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004208** object that implements that strategy.
4209**
4210** This is for MacOSX only.
4211*/
drh1875f7a2008-12-08 18:19:17 +00004212static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004213 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004214 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004215){
4216 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004217 const char *zFilesystem; /* Filesystem type name */
4218 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004219 } aMap[] = {
4220 { "hfs", &posixIoMethods },
4221 { "ufs", &posixIoMethods },
4222 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004223 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004224 { "webdav", &nolockIoMethods },
4225 { 0, 0 }
4226 };
4227 int i;
4228 struct statfs fsInfo;
4229 struct flock lockInfo;
4230
4231 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004232 /* If filePath==NULL that means we are dealing with a transient file
4233 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004234 return &nolockIoMethods;
4235 }
4236 if( statfs(filePath, &fsInfo) != -1 ){
4237 if( fsInfo.f_flags & MNT_RDONLY ){
4238 return &nolockIoMethods;
4239 }
4240 for(i=0; aMap[i].zFilesystem; i++){
4241 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4242 return aMap[i].pMethods;
4243 }
4244 }
4245 }
4246
4247 /* Default case. Handles, amongst others, "nfs".
4248 ** Test byte-range lock using fcntl(). If the call succeeds,
4249 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004250 */
drh7708e972008-11-29 00:56:52 +00004251 lockInfo.l_len = 1;
4252 lockInfo.l_start = 0;
4253 lockInfo.l_whence = SEEK_SET;
4254 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004255 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004256 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4257 return &nfsIoMethods;
4258 } else {
4259 return &posixIoMethods;
4260 }
drh7708e972008-11-29 00:56:52 +00004261 }else{
4262 return &dotlockIoMethods;
4263 }
4264}
drh0c2694b2009-09-03 16:23:44 +00004265static const sqlite3_io_methods
4266 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004267
drhd2cb50b2009-01-09 21:41:17 +00004268#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004269
chw78a13182009-04-07 05:35:03 +00004270#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4271/*
4272** This "finder" function attempts to determine the best locking strategy
4273** for the database file "filePath". It then returns the sqlite3_io_methods
4274** object that implements that strategy.
4275**
4276** This is for VXWorks only.
4277*/
4278static const sqlite3_io_methods *autolockIoFinderImpl(
4279 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004280 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004281){
4282 struct flock lockInfo;
4283
4284 if( !filePath ){
4285 /* If filePath==NULL that means we are dealing with a transient file
4286 ** that does not need to be locked. */
4287 return &nolockIoMethods;
4288 }
4289
4290 /* Test if fcntl() is supported and use POSIX style locks.
4291 ** Otherwise fall back to the named semaphore method.
4292 */
4293 lockInfo.l_len = 1;
4294 lockInfo.l_start = 0;
4295 lockInfo.l_whence = SEEK_SET;
4296 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004297 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004298 return &posixIoMethods;
4299 }else{
4300 return &semIoMethods;
4301 }
4302}
drh0c2694b2009-09-03 16:23:44 +00004303static const sqlite3_io_methods
4304 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004305
4306#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4307
drh7708e972008-11-29 00:56:52 +00004308/*
4309** An abstract type for a pointer to a IO method finder function:
4310*/
drh0c2694b2009-09-03 16:23:44 +00004311typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004312
aswiftaebf4132008-11-21 00:10:35 +00004313
drh734c9862008-11-28 15:37:20 +00004314/****************************************************************************
4315**************************** sqlite3_vfs methods ****************************
4316**
4317** This division contains the implementation of methods on the
4318** sqlite3_vfs object.
4319*/
4320
danielk1977a3d4c882007-03-23 10:08:38 +00004321/*
danielk1977e339d652008-06-28 11:23:00 +00004322** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004323*/
4324static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004325 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004326 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004327 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004328 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004329 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004330 int noLock, /* Omit locking if true */
4331 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004332){
drh7708e972008-11-29 00:56:52 +00004333 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004334 unixFile *pNew = (unixFile *)pId;
4335 int rc = SQLITE_OK;
4336
drh8af6c222010-05-14 12:43:01 +00004337 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004338
dane946c392009-08-22 11:39:46 +00004339 /* Parameter isDelete is only used on vxworks. Express this explicitly
4340 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004341 */
drh7708e972008-11-29 00:56:52 +00004342 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004343
dan00157392010-10-05 11:33:15 +00004344 /* Usually the path zFilename should not be a relative pathname. The
4345 ** exception is when opening the proxy "conch" file in builds that
4346 ** include the special Apple locking styles.
4347 */
dan00157392010-10-05 11:33:15 +00004348#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004349 assert( zFilename==0 || zFilename[0]=='/'
4350 || pVfs->pAppData==(void*)&autolockIoFinder );
4351#else
4352 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004353#endif
dan00157392010-10-05 11:33:15 +00004354
drh308c2a52010-05-14 11:30:18 +00004355 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004356 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004357 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004358 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004359 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004360
drh6c7d5c52008-11-21 20:32:33 +00004361#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004362 pNew->pId = vxworksFindFileId(zFilename);
4363 if( pNew->pId==0 ){
4364 noLock = 1;
4365 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004366 }
4367#endif
4368
drhda0e7682008-07-30 15:27:54 +00004369 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004370 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004371 }else{
drh0c2694b2009-09-03 16:23:44 +00004372 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004373#if SQLITE_ENABLE_LOCKING_STYLE
4374 /* Cache zFilename in the locking context (AFP and dotlock override) for
4375 ** proxyLock activation is possible (remote proxy is based on db name)
4376 ** zFilename remains valid until file is closed, to support */
4377 pNew->lockingContext = (void*)zFilename;
4378#endif
drhda0e7682008-07-30 15:27:54 +00004379 }
danielk1977e339d652008-06-28 11:23:00 +00004380
drh7ed97b92010-01-20 13:07:21 +00004381 if( pLockingStyle == &posixIoMethods
4382#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4383 || pLockingStyle == &nfsIoMethods
4384#endif
4385 ){
drh7708e972008-11-29 00:56:52 +00004386 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004387 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004388 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004389 /* If an error occured in findInodeInfo(), close the file descriptor
4390 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004391 ** in two scenarios:
4392 **
4393 ** (a) A call to fstat() failed.
4394 ** (b) A malloc failed.
4395 **
4396 ** Scenario (b) may only occur if the process is holding no other
4397 ** file descriptors open on the same file. If there were other file
4398 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004399 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004400 ** handle h - as it is guaranteed that no posix locks will be released
4401 ** by doing so.
4402 **
4403 ** If scenario (a) caused the error then things are not so safe. The
4404 ** implicit assumption here is that if fstat() fails, things are in
4405 ** such bad shape that dropping a lock or two doesn't matter much.
4406 */
drh0e9365c2011-03-02 02:08:13 +00004407 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004408 h = -1;
4409 }
drh7708e972008-11-29 00:56:52 +00004410 unixLeaveMutex();
4411 }
danielk1977e339d652008-06-28 11:23:00 +00004412
drhd2cb50b2009-01-09 21:41:17 +00004413#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004414 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004415 /* AFP locking uses the file path so it needs to be included in
4416 ** the afpLockingContext.
4417 */
4418 afpLockingContext *pCtx;
4419 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4420 if( pCtx==0 ){
4421 rc = SQLITE_NOMEM;
4422 }else{
4423 /* NB: zFilename exists and remains valid until the file is closed
4424 ** according to requirement F11141. So we do not need to make a
4425 ** copy of the filename. */
4426 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004427 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004428 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004429 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004430 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004431 if( rc!=SQLITE_OK ){
4432 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004433 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004434 h = -1;
4435 }
drh7708e972008-11-29 00:56:52 +00004436 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004437 }
drh7708e972008-11-29 00:56:52 +00004438 }
4439#endif
danielk1977e339d652008-06-28 11:23:00 +00004440
drh7708e972008-11-29 00:56:52 +00004441 else if( pLockingStyle == &dotlockIoMethods ){
4442 /* Dotfile locking uses the file path so it needs to be included in
4443 ** the dotlockLockingContext
4444 */
4445 char *zLockFile;
4446 int nFilename;
drhea678832008-12-10 19:26:22 +00004447 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004448 zLockFile = (char *)sqlite3_malloc(nFilename);
4449 if( zLockFile==0 ){
4450 rc = SQLITE_NOMEM;
4451 }else{
4452 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004453 }
drh7708e972008-11-29 00:56:52 +00004454 pNew->lockingContext = zLockFile;
4455 }
danielk1977e339d652008-06-28 11:23:00 +00004456
drh6c7d5c52008-11-21 20:32:33 +00004457#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004458 else if( pLockingStyle == &semIoMethods ){
4459 /* Named semaphore locking uses the file path so it needs to be
4460 ** included in the semLockingContext
4461 */
4462 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004463 rc = findInodeInfo(pNew, &pNew->pInode);
4464 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4465 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004466 int n;
drh2238dcc2009-08-27 17:56:20 +00004467 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004468 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004469 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004470 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004471 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4472 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004473 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004474 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004475 }
chw97185482008-11-17 08:05:31 +00004476 }
drh7708e972008-11-29 00:56:52 +00004477 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004478 }
drh7708e972008-11-29 00:56:52 +00004479#endif
aswift5b1a2562008-08-22 00:22:35 +00004480
4481 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004482#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004483 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004484 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004485 h = -1;
chw97185482008-11-17 08:05:31 +00004486 unlink(zFilename);
4487 isDelete = 0;
4488 }
4489 pNew->isDelete = isDelete;
4490#endif
danielk1977e339d652008-06-28 11:23:00 +00004491 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004492 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4493 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004494 }else{
drh7708e972008-11-29 00:56:52 +00004495 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004496 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004497 }
danielk1977e339d652008-06-28 11:23:00 +00004498 return rc;
drh054889e2005-11-30 03:20:31 +00004499}
drh9c06c952005-11-26 00:25:00 +00004500
danielk1977ad94b582007-08-20 06:44:22 +00004501/*
4502** Open a file descriptor to the directory containing file zFilename.
4503** If successful, *pFd is set to the opened file descriptor and
4504** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4505** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4506** value.
4507**
4508** If SQLITE_OK is returned, the caller is responsible for closing
4509** the file descriptor *pFd using close().
4510*/
danielk1977fee2d252007-08-18 10:59:19 +00004511static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004512 int ii;
drh777b17a2007-09-20 10:02:54 +00004513 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004514 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004515
drh153c62c2007-08-24 03:51:33 +00004516 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004517 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004518 if( ii>0 ){
4519 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004520 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004521 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004522#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004523 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004524#endif
drh308c2a52010-05-14 11:30:18 +00004525 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004526 }
4527 }
danielk1977fee2d252007-08-18 10:59:19 +00004528 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004529 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004530}
4531
danielk1977b4b47412007-08-17 15:53:36 +00004532/*
drh8b3cf822010-06-01 21:02:51 +00004533** Return the name of a directory in which to put temporary files.
4534** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004535*/
drh7234c6d2010-06-19 15:10:09 +00004536static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004537 static const char *azDirs[] = {
4538 0,
aswiftaebf4132008-11-21 00:10:35 +00004539 0,
danielk197717b90b52008-06-06 11:11:25 +00004540 "/var/tmp",
4541 "/usr/tmp",
4542 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004543 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004544 };
drh8b3cf822010-06-01 21:02:51 +00004545 unsigned int i;
4546 struct stat buf;
4547 const char *zDir = 0;
4548
4549 azDirs[0] = sqlite3_temp_directory;
4550 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004551 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004552 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004553 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004554 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004555 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004556 break;
4557 }
4558 return zDir;
4559}
4560
4561/*
4562** Create a temporary file name in zBuf. zBuf must be allocated
4563** by the calling process and must be big enough to hold at least
4564** pVfs->mxPathname bytes.
4565*/
4566static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004567 static const unsigned char zChars[] =
4568 "abcdefghijklmnopqrstuvwxyz"
4569 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4570 "0123456789";
drh41022642008-11-21 00:24:42 +00004571 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004572 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004573
4574 /* It's odd to simulate an io-error here, but really this is just
4575 ** using the io-error infrastructure to test that SQLite handles this
4576 ** function failing.
4577 */
4578 SimulateIOError( return SQLITE_IOERR );
4579
drh7234c6d2010-06-19 15:10:09 +00004580 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004581 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004582
4583 /* Check that the output buffer is large enough for the temporary file
4584 ** name. If it is not, return SQLITE_ERROR.
4585 */
danielk197700e13612008-11-17 19:18:54 +00004586 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004587 return SQLITE_ERROR;
4588 }
4589
4590 do{
4591 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004592 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004593 sqlite3_randomness(15, &zBuf[j]);
4594 for(i=0; i<15; i++, j++){
4595 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4596 }
4597 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004598 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004599 return SQLITE_OK;
4600}
4601
drhd2cb50b2009-01-09 21:41:17 +00004602#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004603/*
4604** Routine to transform a unixFile into a proxy-locking unixFile.
4605** Implementation in the proxy-lock division, but used by unixOpen()
4606** if SQLITE_PREFER_PROXY_LOCKING is defined.
4607*/
4608static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004609#endif
drhc66d5b62008-12-03 22:48:32 +00004610
dan08da86a2009-08-21 17:18:03 +00004611/*
4612** Search for an unused file descriptor that was opened on the database
4613** file (not a journal or master-journal file) identified by pathname
4614** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4615** argument to this function.
4616**
4617** Such a file descriptor may exist if a database connection was closed
4618** but the associated file descriptor could not be closed because some
4619** other file descriptor open on the same file is holding a file-lock.
4620** Refer to comments in the unixClose() function and the lengthy comment
4621** describing "Posix Advisory Locking" at the start of this file for
4622** further details. Also, ticket #4018.
4623**
4624** If a suitable file descriptor is found, then it is returned. If no
4625** such file descriptor is located, -1 is returned.
4626*/
dane946c392009-08-22 11:39:46 +00004627static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4628 UnixUnusedFd *pUnused = 0;
4629
4630 /* Do not search for an unused file descriptor on vxworks. Not because
4631 ** vxworks would not benefit from the change (it might, we're not sure),
4632 ** but because no way to test it is currently available. It is better
4633 ** not to risk breaking vxworks support for the sake of such an obscure
4634 ** feature. */
4635#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004636 struct stat sStat; /* Results of stat() call */
4637
4638 /* A stat() call may fail for various reasons. If this happens, it is
4639 ** almost certain that an open() call on the same path will also fail.
4640 ** For this reason, if an error occurs in the stat() call here, it is
4641 ** ignored and -1 is returned. The caller will try to open a new file
4642 ** descriptor on the same path, fail, and return an error to SQLite.
4643 **
4644 ** Even if a subsequent open() call does succeed, the consequences of
4645 ** not searching for a resusable file descriptor are not dire. */
4646 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004647 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004648
4649 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004650 pInode = inodeList;
4651 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4652 || pInode->fileId.ino!=sStat.st_ino) ){
4653 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004654 }
drh8af6c222010-05-14 12:43:01 +00004655 if( pInode ){
dane946c392009-08-22 11:39:46 +00004656 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004657 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004658 pUnused = *pp;
4659 if( pUnused ){
4660 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004661 }
4662 }
4663 unixLeaveMutex();
4664 }
dane946c392009-08-22 11:39:46 +00004665#endif /* if !OS_VXWORKS */
4666 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004667}
danielk197717b90b52008-06-06 11:11:25 +00004668
4669/*
danddb0ac42010-07-14 14:48:58 +00004670** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004671** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004672** and a value suitable for passing as the third argument to open(2) is
4673** written to *pMode. If an IO error occurs, an SQLite error code is
4674** returned and the value of *pMode is not modified.
4675**
4676** If the file being opened is a temporary file, it is always created with
4677** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004678** is a database or master journal file, it is created with the permissions
4679** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004680**
drh8ab58662010-07-15 18:38:39 +00004681** Finally, if the file being opened is a WAL or regular journal file, then
4682** this function queries the file-system for the permissions on the
4683** corresponding database file and sets *pMode to this value. Whenever
4684** possible, WAL and journal files are created using the same permissions
4685** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004686*/
4687static int findCreateFileMode(
4688 const char *zPath, /* Path of file (possibly) being created */
4689 int flags, /* Flags passed as 4th argument to xOpen() */
4690 mode_t *pMode /* OUT: Permissions to open file with */
4691){
4692 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004693 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004694 char zDb[MAX_PATHNAME+1]; /* Database file path */
4695 int nDb; /* Number of valid bytes in zDb */
4696 struct stat sStat; /* Output of stat() on database file */
4697
dana0c989d2010-11-05 18:07:37 +00004698 /* zPath is a path to a WAL or journal file. The following block derives
4699 ** the path to the associated database file from zPath. This block handles
4700 ** the following naming conventions:
4701 **
4702 ** "<path to db>-journal"
4703 ** "<path to db>-wal"
4704 ** "<path to db>-journal-NNNN"
4705 ** "<path to db>-wal-NNNN"
4706 **
4707 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4708 ** used by the test_multiplex.c module.
4709 */
4710 nDb = sqlite3Strlen30(zPath) - 1;
4711 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4712 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004713 memcpy(zDb, zPath, nDb);
4714 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004715
danddb0ac42010-07-14 14:48:58 +00004716 if( 0==stat(zDb, &sStat) ){
4717 *pMode = sStat.st_mode & 0777;
4718 }else{
4719 rc = SQLITE_IOERR_FSTAT;
4720 }
4721 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4722 *pMode = 0600;
4723 }else{
4724 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4725 }
4726 return rc;
4727}
4728
4729/*
danielk1977ad94b582007-08-20 06:44:22 +00004730** Open the file zPath.
4731**
danielk1977b4b47412007-08-17 15:53:36 +00004732** Previously, the SQLite OS layer used three functions in place of this
4733** one:
4734**
4735** sqlite3OsOpenReadWrite();
4736** sqlite3OsOpenReadOnly();
4737** sqlite3OsOpenExclusive();
4738**
4739** These calls correspond to the following combinations of flags:
4740**
4741** ReadWrite() -> (READWRITE | CREATE)
4742** ReadOnly() -> (READONLY)
4743** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4744**
4745** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4746** true, the file was configured to be automatically deleted when the
4747** file handle closed. To achieve the same effect using this new
4748** interface, add the DELETEONCLOSE flag to those specified above for
4749** OpenExclusive().
4750*/
4751static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004752 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4753 const char *zPath, /* Pathname of file to be opened */
4754 sqlite3_file *pFile, /* The file descriptor to be filled in */
4755 int flags, /* Input flags to control the opening */
4756 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004757){
dan08da86a2009-08-21 17:18:03 +00004758 unixFile *p = (unixFile *)pFile;
4759 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004760 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004761 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004762 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004763 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004764 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004765
4766 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4767 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4768 int isCreate = (flags & SQLITE_OPEN_CREATE);
4769 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4770 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004771#if SQLITE_ENABLE_LOCKING_STYLE
4772 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4773#endif
danielk1977b4b47412007-08-17 15:53:36 +00004774
danielk1977fee2d252007-08-18 10:59:19 +00004775 /* If creating a master or main-file journal, this function will open
4776 ** a file-descriptor on the directory too. The first time unixSync()
4777 ** is called the directory file descriptor will be fsync()ed and close()d.
4778 */
danddb0ac42010-07-14 14:48:58 +00004779 int isOpenDirectory = (isCreate && (
4780 eType==SQLITE_OPEN_MASTER_JOURNAL
4781 || eType==SQLITE_OPEN_MAIN_JOURNAL
4782 || eType==SQLITE_OPEN_WAL
4783 ));
danielk1977fee2d252007-08-18 10:59:19 +00004784
danielk197717b90b52008-06-06 11:11:25 +00004785 /* If argument zPath is a NULL pointer, this function is required to open
4786 ** a temporary file. Use this buffer to store the file name in.
4787 */
4788 char zTmpname[MAX_PATHNAME+1];
4789 const char *zName = zPath;
4790
danielk1977fee2d252007-08-18 10:59:19 +00004791 /* Check the following statements are true:
4792 **
4793 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4794 ** (b) if CREATE is set, then READWRITE must also be set, and
4795 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004796 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004797 */
danielk1977b4b47412007-08-17 15:53:36 +00004798 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004799 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004800 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004801 assert(isDelete==0 || isCreate);
4802
danddb0ac42010-07-14 14:48:58 +00004803 /* The main DB, main journal, WAL file and master journal are never
4804 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004805 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4806 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4807 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004808 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004809
danielk1977fee2d252007-08-18 10:59:19 +00004810 /* Assert that the upper layer has set one of the "file-type" flags. */
4811 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4812 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4813 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004814 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004815 );
4816
dan08da86a2009-08-21 17:18:03 +00004817 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004818
dan08da86a2009-08-21 17:18:03 +00004819 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004820 UnixUnusedFd *pUnused;
4821 pUnused = findReusableFd(zName, flags);
4822 if( pUnused ){
4823 fd = pUnused->fd;
4824 }else{
dan6aa657f2009-08-24 18:57:58 +00004825 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004826 if( !pUnused ){
4827 return SQLITE_NOMEM;
4828 }
4829 }
4830 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004831 }else if( !zName ){
4832 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004833 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004834 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004835 if( rc!=SQLITE_OK ){
4836 return rc;
4837 }
4838 zName = zTmpname;
4839 }
4840
dan08da86a2009-08-21 17:18:03 +00004841 /* Determine the value of the flags parameter passed to POSIX function
4842 ** open(). These must be calculated even if open() is not called, as
4843 ** they may be stored as part of the file handle and used by the
4844 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004845 if( isReadonly ) openFlags |= O_RDONLY;
4846 if( isReadWrite ) openFlags |= O_RDWR;
4847 if( isCreate ) openFlags |= O_CREAT;
4848 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4849 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004850
danielk1977b4b47412007-08-17 15:53:36 +00004851 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004852 mode_t openMode; /* Permissions to create file with */
4853 rc = findCreateFileMode(zName, flags, &openMode);
4854 if( rc!=SQLITE_OK ){
4855 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004856 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004857 return rc;
4858 }
drhad4f1e52011-03-04 15:43:57 +00004859 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004860 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004861 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4862 /* Failed to open the file for read/write access. Try read-only. */
4863 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004864 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004865 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004866 openFlags |= O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00004867 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004868 }
4869 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004870 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004871 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004872 }
danielk1977b4b47412007-08-17 15:53:36 +00004873 }
dan08da86a2009-08-21 17:18:03 +00004874 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004875 if( pOutFlags ){
4876 *pOutFlags = flags;
4877 }
4878
dane946c392009-08-22 11:39:46 +00004879 if( p->pUnused ){
4880 p->pUnused->fd = fd;
4881 p->pUnused->flags = flags;
4882 }
4883
danielk1977b4b47412007-08-17 15:53:36 +00004884 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004885#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004886 zPath = zName;
4887#else
danielk197717b90b52008-06-06 11:11:25 +00004888 unlink(zName);
chw97185482008-11-17 08:05:31 +00004889#endif
danielk1977b4b47412007-08-17 15:53:36 +00004890 }
drh41022642008-11-21 00:24:42 +00004891#if SQLITE_ENABLE_LOCKING_STYLE
4892 else{
dan08da86a2009-08-21 17:18:03 +00004893 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004894 }
4895#endif
4896
danielk1977fee2d252007-08-18 10:59:19 +00004897 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004898 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004899 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004900 /* It is safe to close fd at this point, because it is guaranteed not
4901 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004902 ** it would not be safe to close as this would release any locks held
4903 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004904 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00004905 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004906 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004907 }
4908 }
danielk1977e339d652008-06-28 11:23:00 +00004909
4910#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004911 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00004912#endif
4913
drhda0e7682008-07-30 15:27:54 +00004914 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004915
drh7ed97b92010-01-20 13:07:21 +00004916
4917#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4918 struct statfs fsInfo;
4919 if( fstatfs(fd, &fsInfo) == -1 ){
4920 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00004921 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
4922 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004923 return SQLITE_IOERR_ACCESS;
4924 }
4925 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4926 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4927 }
4928#endif
4929
4930#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004931#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004932 isAutoProxy = 1;
4933#endif
4934 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004935 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4936 int useProxy = 0;
4937
dan08da86a2009-08-21 17:18:03 +00004938 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4939 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004940 if( envforce!=NULL ){
4941 useProxy = atoi(envforce)>0;
4942 }else{
4943 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004944 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004945 /* In theory, the close(fd) call is sub-optimal. If the file opened
4946 ** with fd is a database file, and there are other connections open
4947 ** on that file that are currently holding advisory locks on it,
4948 ** then the call to close() will cancel those locks. In practice,
4949 ** we're assuming that statfs() doesn't fail very often. At least
4950 ** not while other file descriptors opened by the same process on
4951 ** the same file are working. */
4952 p->lastErrno = errno;
4953 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00004954 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00004955 }
drh0e9365c2011-03-02 02:08:13 +00004956 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004957 rc = SQLITE_IOERR_ACCESS;
4958 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004959 }
4960 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4961 }
4962 if( useProxy ){
4963 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4964 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004965 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004966 if( rc!=SQLITE_OK ){
4967 /* Use unixClose to clean up the resources added in fillInUnixFile
4968 ** and clear all the structure's references. Specifically,
4969 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4970 */
4971 unixClose(pFile);
4972 return rc;
4973 }
aswiftaebf4132008-11-21 00:10:35 +00004974 }
dane946c392009-08-22 11:39:46 +00004975 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004976 }
4977 }
4978#endif
4979
dane946c392009-08-22 11:39:46 +00004980 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4981open_finished:
4982 if( rc!=SQLITE_OK ){
4983 sqlite3_free(p->pUnused);
4984 }
4985 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004986}
4987
dane946c392009-08-22 11:39:46 +00004988
danielk1977b4b47412007-08-17 15:53:36 +00004989/*
danielk1977fee2d252007-08-18 10:59:19 +00004990** Delete the file at zPath. If the dirSync argument is true, fsync()
4991** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004992*/
drh6b9d6dd2008-12-03 19:34:47 +00004993static int unixDelete(
4994 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4995 const char *zPath, /* Name of file to be deleted */
4996 int dirSync /* If true, fsync() directory after deleting file */
4997){
danielk1977fee2d252007-08-18 10:59:19 +00004998 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004999 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005000 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005001 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005002 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005003 }
danielk1977d39fa702008-10-16 13:27:40 +00005004#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005005 if( dirSync ){
5006 int fd;
5007 rc = openDirectory(zPath, &fd);
5008 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005009#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005010 if( fsync(fd)==-1 )
5011#else
5012 if( fsync(fd) )
5013#endif
5014 {
dane18d4952011-02-21 11:46:24 +00005015 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005016 }
drh0e9365c2011-03-02 02:08:13 +00005017 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005018 }
5019 }
danielk1977d138dd82008-10-15 16:02:48 +00005020#endif
danielk1977fee2d252007-08-18 10:59:19 +00005021 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005022}
5023
danielk197790949c22007-08-17 16:50:38 +00005024/*
5025** Test the existance of or access permissions of file zPath. The
5026** test performed depends on the value of flags:
5027**
5028** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5029** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5030** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5031**
5032** Otherwise return 0.
5033*/
danielk1977861f7452008-06-05 11:39:11 +00005034static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005035 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5036 const char *zPath, /* Path of the file to examine */
5037 int flags, /* What do we want to learn about the zPath file? */
5038 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005039){
rse25c0d1a2007-09-20 08:38:14 +00005040 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005041 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005042 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005043 switch( flags ){
5044 case SQLITE_ACCESS_EXISTS:
5045 amode = F_OK;
5046 break;
5047 case SQLITE_ACCESS_READWRITE:
5048 amode = W_OK|R_OK;
5049 break;
drh50d3f902007-08-27 21:10:36 +00005050 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005051 amode = R_OK;
5052 break;
5053
5054 default:
5055 assert(!"Invalid flags argument");
5056 }
drh99ab3b12011-03-02 15:09:07 +00005057 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005058 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5059 struct stat buf;
5060 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5061 *pResOut = 0;
5062 }
5063 }
danielk1977861f7452008-06-05 11:39:11 +00005064 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005065}
5066
danielk1977b4b47412007-08-17 15:53:36 +00005067
5068/*
5069** Turn a relative pathname into a full pathname. The relative path
5070** is stored as a nul-terminated string in the buffer pointed to by
5071** zPath.
5072**
5073** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5074** (in this case, MAX_PATHNAME bytes). The full-path is written to
5075** this buffer before returning.
5076*/
danielk1977adfb9b02007-09-17 07:02:56 +00005077static int unixFullPathname(
5078 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5079 const char *zPath, /* Possibly relative input path */
5080 int nOut, /* Size of output buffer in bytes */
5081 char *zOut /* Output buffer */
5082){
danielk1977843e65f2007-09-01 16:16:15 +00005083
5084 /* It's odd to simulate an io-error here, but really this is just
5085 ** using the io-error infrastructure to test that SQLite handles this
5086 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005087 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005088 */
5089 SimulateIOError( return SQLITE_ERROR );
5090
drh153c62c2007-08-24 03:51:33 +00005091 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005092 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005093
drh3c7f2dc2007-12-06 13:26:20 +00005094 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005095 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005096 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005097 }else{
5098 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005099 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005100 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005101 }
drhea678832008-12-10 19:26:22 +00005102 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005103 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005104 }
5105 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005106}
5107
drh0ccebe72005-06-07 22:22:50 +00005108
drh761df872006-12-21 01:29:22 +00005109#ifndef SQLITE_OMIT_LOAD_EXTENSION
5110/*
5111** Interfaces for opening a shared library, finding entry points
5112** within the shared library, and closing the shared library.
5113*/
5114#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005115static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5116 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005117 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5118}
danielk197795c8a542007-09-01 06:51:27 +00005119
5120/*
5121** SQLite calls this function immediately after a call to unixDlSym() or
5122** unixDlOpen() fails (returns a null pointer). If a more detailed error
5123** message is available, it is written to zBufOut. If no error message
5124** is available, zBufOut is left unmodified and SQLite uses a default
5125** error message.
5126*/
danielk1977397d65f2008-11-19 11:35:39 +00005127static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005128 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005129 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005130 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005131 zErr = dlerror();
5132 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005133 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005134 }
drh6c7d5c52008-11-21 20:32:33 +00005135 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005136}
drh1875f7a2008-12-08 18:19:17 +00005137static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5138 /*
5139 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5140 ** cast into a pointer to a function. And yet the library dlsym() routine
5141 ** returns a void* which is really a pointer to a function. So how do we
5142 ** use dlsym() with -pedantic-errors?
5143 **
5144 ** Variable x below is defined to be a pointer to a function taking
5145 ** parameters void* and const char* and returning a pointer to a function.
5146 ** We initialize x by assigning it a pointer to the dlsym() function.
5147 ** (That assignment requires a cast.) Then we call the function that
5148 ** x points to.
5149 **
5150 ** This work-around is unlikely to work correctly on any system where
5151 ** you really cannot cast a function pointer into void*. But then, on the
5152 ** other hand, dlsym() will not work on such a system either, so we have
5153 ** not really lost anything.
5154 */
5155 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005156 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005157 x = (void(*(*)(void*,const char*))(void))dlsym;
5158 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005159}
danielk1977397d65f2008-11-19 11:35:39 +00005160static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5161 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005162 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005163}
danielk1977b4b47412007-08-17 15:53:36 +00005164#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5165 #define unixDlOpen 0
5166 #define unixDlError 0
5167 #define unixDlSym 0
5168 #define unixDlClose 0
5169#endif
5170
5171/*
danielk197790949c22007-08-17 16:50:38 +00005172** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005173*/
danielk1977397d65f2008-11-19 11:35:39 +00005174static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5175 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005176 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005177
drhbbd42a62004-05-22 17:41:58 +00005178 /* We have to initialize zBuf to prevent valgrind from reporting
5179 ** errors. The reports issued by valgrind are incorrect - we would
5180 ** prefer that the randomness be increased by making use of the
5181 ** uninitialized space in zBuf - but valgrind errors tend to worry
5182 ** some users. Rather than argue, it seems easier just to initialize
5183 ** the whole array and silence valgrind, even if that means less randomness
5184 ** in the random seed.
5185 **
5186 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005187 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005188 ** tests repeatable.
5189 */
danielk1977b4b47412007-08-17 15:53:36 +00005190 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005191#if !defined(SQLITE_TEST)
5192 {
drh842b8642005-01-21 17:53:17 +00005193 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005194 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005195 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005196 time_t t;
5197 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005198 memcpy(zBuf, &t, sizeof(t));
5199 pid = getpid();
5200 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005201 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005202 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005203 }else{
drhe562be52011-03-02 18:01:10 +00005204 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005205 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005206 }
drhbbd42a62004-05-22 17:41:58 +00005207 }
5208#endif
drh72cbd072008-10-14 17:58:38 +00005209 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005210}
5211
danielk1977b4b47412007-08-17 15:53:36 +00005212
drhbbd42a62004-05-22 17:41:58 +00005213/*
5214** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005215** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005216** The return value is the number of microseconds of sleep actually
5217** requested from the underlying operating system, a number which
5218** might be greater than or equal to the argument, but not less
5219** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005220*/
danielk1977397d65f2008-11-19 11:35:39 +00005221static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005222#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005223 struct timespec sp;
5224
5225 sp.tv_sec = microseconds / 1000000;
5226 sp.tv_nsec = (microseconds % 1000000) * 1000;
5227 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005228 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005229 return microseconds;
5230#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005231 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005232 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005233 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005234#else
danielk1977b4b47412007-08-17 15:53:36 +00005235 int seconds = (microseconds+999999)/1000000;
5236 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005237 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005238 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005239#endif
drh88f474a2006-01-02 20:00:12 +00005240}
5241
5242/*
drh6b9d6dd2008-12-03 19:34:47 +00005243** The following variable, if set to a non-zero value, is interpreted as
5244** the number of seconds since 1970 and is used to set the result of
5245** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005246*/
5247#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005248int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005249#endif
5250
5251/*
drhb7e8ea22010-05-03 14:32:30 +00005252** Find the current time (in Universal Coordinated Time). Write into *piNow
5253** the current time and date as a Julian Day number times 86_400_000. In
5254** other words, write into *piNow the number of milliseconds since the Julian
5255** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5256** proleptic Gregorian calendar.
5257**
5258** On success, return 0. Return 1 if the time and date cannot be found.
5259*/
5260static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5261 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5262#if defined(NO_GETTOD)
5263 time_t t;
5264 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005265 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005266#elif OS_VXWORKS
5267 struct timespec sNow;
5268 clock_gettime(CLOCK_REALTIME, &sNow);
5269 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5270#else
5271 struct timeval sNow;
5272 gettimeofday(&sNow, 0);
5273 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5274#endif
5275
5276#ifdef SQLITE_TEST
5277 if( sqlite3_current_time ){
5278 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5279 }
5280#endif
5281 UNUSED_PARAMETER(NotUsed);
5282 return 0;
5283}
5284
5285/*
drhbbd42a62004-05-22 17:41:58 +00005286** Find the current time (in Universal Coordinated Time). Write the
5287** current time and date as a Julian Day number into *prNow and
5288** return 0. Return 1 if the time and date cannot be found.
5289*/
danielk1977397d65f2008-11-19 11:35:39 +00005290static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005291 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005292 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005293 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005294 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005295 return 0;
5296}
danielk1977b4b47412007-08-17 15:53:36 +00005297
drh6b9d6dd2008-12-03 19:34:47 +00005298/*
5299** We added the xGetLastError() method with the intention of providing
5300** better low-level error messages when operating-system problems come up
5301** during SQLite operation. But so far, none of that has been implemented
5302** in the core. So this routine is never called. For now, it is merely
5303** a place-holder.
5304*/
danielk1977397d65f2008-11-19 11:35:39 +00005305static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5306 UNUSED_PARAMETER(NotUsed);
5307 UNUSED_PARAMETER(NotUsed2);
5308 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005309 return 0;
5310}
5311
drhf2424c52010-04-26 00:04:55 +00005312
5313/*
drh734c9862008-11-28 15:37:20 +00005314************************ End of sqlite3_vfs methods ***************************
5315******************************************************************************/
5316
drh715ff302008-12-03 22:32:44 +00005317/******************************************************************************
5318************************** Begin Proxy Locking ********************************
5319**
5320** Proxy locking is a "uber-locking-method" in this sense: It uses the
5321** other locking methods on secondary lock files. Proxy locking is a
5322** meta-layer over top of the primitive locking implemented above. For
5323** this reason, the division that implements of proxy locking is deferred
5324** until late in the file (here) after all of the other I/O methods have
5325** been defined - so that the primitive locking methods are available
5326** as services to help with the implementation of proxy locking.
5327**
5328****
5329**
5330** The default locking schemes in SQLite use byte-range locks on the
5331** database file to coordinate safe, concurrent access by multiple readers
5332** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5333** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5334** as POSIX read & write locks over fixed set of locations (via fsctl),
5335** on AFP and SMB only exclusive byte-range locks are available via fsctl
5336** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5337** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5338** address in the shared range is taken for a SHARED lock, the entire
5339** shared range is taken for an EXCLUSIVE lock):
5340**
5341** PENDING_BYTE 0x40000000
5342** RESERVED_BYTE 0x40000001
5343** SHARED_RANGE 0x40000002 -> 0x40000200
5344**
5345** This works well on the local file system, but shows a nearly 100x
5346** slowdown in read performance on AFP because the AFP client disables
5347** the read cache when byte-range locks are present. Enabling the read
5348** cache exposes a cache coherency problem that is present on all OS X
5349** supported network file systems. NFS and AFP both observe the
5350** close-to-open semantics for ensuring cache coherency
5351** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5352** address the requirements for concurrent database access by multiple
5353** readers and writers
5354** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5355**
5356** To address the performance and cache coherency issues, proxy file locking
5357** changes the way database access is controlled by limiting access to a
5358** single host at a time and moving file locks off of the database file
5359** and onto a proxy file on the local file system.
5360**
5361**
5362** Using proxy locks
5363** -----------------
5364**
5365** C APIs
5366**
5367** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5368** <proxy_path> | ":auto:");
5369** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5370**
5371**
5372** SQL pragmas
5373**
5374** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5375** PRAGMA [database.]lock_proxy_file
5376**
5377** Specifying ":auto:" means that if there is a conch file with a matching
5378** host ID in it, the proxy path in the conch file will be used, otherwise
5379** a proxy path based on the user's temp dir
5380** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5381** actual proxy file name is generated from the name and path of the
5382** database file. For example:
5383**
5384** For database path "/Users/me/foo.db"
5385** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5386**
5387** Once a lock proxy is configured for a database connection, it can not
5388** be removed, however it may be switched to a different proxy path via
5389** the above APIs (assuming the conch file is not being held by another
5390** connection or process).
5391**
5392**
5393** How proxy locking works
5394** -----------------------
5395**
5396** Proxy file locking relies primarily on two new supporting files:
5397**
5398** * conch file to limit access to the database file to a single host
5399** at a time
5400**
5401** * proxy file to act as a proxy for the advisory locks normally
5402** taken on the database
5403**
5404** The conch file - to use a proxy file, sqlite must first "hold the conch"
5405** by taking an sqlite-style shared lock on the conch file, reading the
5406** contents and comparing the host's unique host ID (see below) and lock
5407** proxy path against the values stored in the conch. The conch file is
5408** stored in the same directory as the database file and the file name
5409** is patterned after the database file name as ".<databasename>-conch".
5410** If the conch file does not exist, or it's contents do not match the
5411** host ID and/or proxy path, then the lock is escalated to an exclusive
5412** lock and the conch file contents is updated with the host ID and proxy
5413** path and the lock is downgraded to a shared lock again. If the conch
5414** is held by another process (with a shared lock), the exclusive lock
5415** will fail and SQLITE_BUSY is returned.
5416**
5417** The proxy file - a single-byte file used for all advisory file locks
5418** normally taken on the database file. This allows for safe sharing
5419** of the database file for multiple readers and writers on the same
5420** host (the conch ensures that they all use the same local lock file).
5421**
drh715ff302008-12-03 22:32:44 +00005422** Requesting the lock proxy does not immediately take the conch, it is
5423** only taken when the first request to lock database file is made.
5424** This matches the semantics of the traditional locking behavior, where
5425** opening a connection to a database file does not take a lock on it.
5426** The shared lock and an open file descriptor are maintained until
5427** the connection to the database is closed.
5428**
5429** The proxy file and the lock file are never deleted so they only need
5430** to be created the first time they are used.
5431**
5432** Configuration options
5433** ---------------------
5434**
5435** SQLITE_PREFER_PROXY_LOCKING
5436**
5437** Database files accessed on non-local file systems are
5438** automatically configured for proxy locking, lock files are
5439** named automatically using the same logic as
5440** PRAGMA lock_proxy_file=":auto:"
5441**
5442** SQLITE_PROXY_DEBUG
5443**
5444** Enables the logging of error messages during host id file
5445** retrieval and creation
5446**
drh715ff302008-12-03 22:32:44 +00005447** LOCKPROXYDIR
5448**
5449** Overrides the default directory used for lock proxy files that
5450** are named automatically via the ":auto:" setting
5451**
5452** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5453**
5454** Permissions to use when creating a directory for storing the
5455** lock proxy files, only used when LOCKPROXYDIR is not set.
5456**
5457**
5458** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5459** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5460** force proxy locking to be used for every database file opened, and 0
5461** will force automatic proxy locking to be disabled for all database
5462** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5463** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5464*/
5465
5466/*
5467** Proxy locking is only available on MacOSX
5468*/
drhd2cb50b2009-01-09 21:41:17 +00005469#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005470
drh715ff302008-12-03 22:32:44 +00005471/*
5472** The proxyLockingContext has the path and file structures for the remote
5473** and local proxy files in it
5474*/
5475typedef struct proxyLockingContext proxyLockingContext;
5476struct proxyLockingContext {
5477 unixFile *conchFile; /* Open conch file */
5478 char *conchFilePath; /* Name of the conch file */
5479 unixFile *lockProxy; /* Open proxy lock file */
5480 char *lockProxyPath; /* Name of the proxy lock file */
5481 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005482 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005483 void *oldLockingContext; /* Original lockingcontext to restore on close */
5484 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5485};
5486
drh7ed97b92010-01-20 13:07:21 +00005487/*
5488** The proxy lock file path for the database at dbPath is written into lPath,
5489** which must point to valid, writable memory large enough for a maxLen length
5490** file path.
drh715ff302008-12-03 22:32:44 +00005491*/
drh715ff302008-12-03 22:32:44 +00005492static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5493 int len;
5494 int dbLen;
5495 int i;
5496
5497#ifdef LOCKPROXYDIR
5498 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5499#else
5500# ifdef _CS_DARWIN_USER_TEMP_DIR
5501 {
drh7ed97b92010-01-20 13:07:21 +00005502 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005503 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5504 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005505 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005506 }
drh7ed97b92010-01-20 13:07:21 +00005507 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005508 }
5509# else
5510 len = strlcpy(lPath, "/tmp/", maxLen);
5511# endif
5512#endif
5513
5514 if( lPath[len-1]!='/' ){
5515 len = strlcat(lPath, "/", maxLen);
5516 }
5517
5518 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005519 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005520 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005521 char c = dbPath[i];
5522 lPath[i+len] = (c=='/')?'_':c;
5523 }
5524 lPath[i+len]='\0';
5525 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005526 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005527 return SQLITE_OK;
5528}
5529
drh7ed97b92010-01-20 13:07:21 +00005530/*
5531 ** Creates the lock file and any missing directories in lockPath
5532 */
5533static int proxyCreateLockPath(const char *lockPath){
5534 int i, len;
5535 char buf[MAXPATHLEN];
5536 int start = 0;
5537
5538 assert(lockPath!=NULL);
5539 /* try to create all the intermediate directories */
5540 len = (int)strlen(lockPath);
5541 buf[0] = lockPath[0];
5542 for( i=1; i<len; i++ ){
5543 if( lockPath[i] == '/' && (i - start > 0) ){
5544 /* only mkdir if leaf dir != "." or "/" or ".." */
5545 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5546 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5547 buf[i]='\0';
5548 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5549 int err=errno;
5550 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005551 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005552 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005553 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005554 return err;
5555 }
5556 }
5557 }
5558 start=i+1;
5559 }
5560 buf[i] = lockPath[i];
5561 }
drh308c2a52010-05-14 11:30:18 +00005562 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005563 return 0;
5564}
5565
drh715ff302008-12-03 22:32:44 +00005566/*
5567** Create a new VFS file descriptor (stored in memory obtained from
5568** sqlite3_malloc) and open the file named "path" in the file descriptor.
5569**
5570** The caller is responsible not only for closing the file descriptor
5571** but also for freeing the memory associated with the file descriptor.
5572*/
drh7ed97b92010-01-20 13:07:21 +00005573static int proxyCreateUnixFile(
5574 const char *path, /* path for the new unixFile */
5575 unixFile **ppFile, /* unixFile created and returned by ref */
5576 int islockfile /* if non zero missing dirs will be created */
5577) {
5578 int fd = -1;
5579 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005580 unixFile *pNew;
5581 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005582 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005583 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005584 int terrno = 0;
5585 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005586
drh7ed97b92010-01-20 13:07:21 +00005587 /* 1. first try to open/create the file
5588 ** 2. if that fails, and this is a lock file (not-conch), try creating
5589 ** the parent directories and then try again.
5590 ** 3. if that fails, try to open the file read-only
5591 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5592 */
5593 pUnused = findReusableFd(path, openFlags);
5594 if( pUnused ){
5595 fd = pUnused->fd;
5596 }else{
5597 pUnused = sqlite3_malloc(sizeof(*pUnused));
5598 if( !pUnused ){
5599 return SQLITE_NOMEM;
5600 }
5601 }
5602 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005603 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005604 terrno = errno;
5605 if( fd<0 && errno==ENOENT && islockfile ){
5606 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005607 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005608 }
5609 }
5610 }
5611 if( fd<0 ){
5612 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005613 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005614 terrno = errno;
5615 }
5616 if( fd<0 ){
5617 if( islockfile ){
5618 return SQLITE_BUSY;
5619 }
5620 switch (terrno) {
5621 case EACCES:
5622 return SQLITE_PERM;
5623 case EIO:
5624 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5625 default:
drh9978c972010-02-23 17:36:32 +00005626 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005627 }
5628 }
5629
5630 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5631 if( pNew==NULL ){
5632 rc = SQLITE_NOMEM;
5633 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005634 }
5635 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005636 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005637 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005638 pUnused->fd = fd;
5639 pUnused->flags = openFlags;
5640 pNew->pUnused = pUnused;
5641
5642 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5643 if( rc==SQLITE_OK ){
5644 *ppFile = pNew;
5645 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005646 }
drh7ed97b92010-01-20 13:07:21 +00005647end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005648 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005649 sqlite3_free(pNew);
5650 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005651 return rc;
5652}
5653
drh7ed97b92010-01-20 13:07:21 +00005654#ifdef SQLITE_TEST
5655/* simulate multiple hosts by creating unique hostid file paths */
5656int sqlite3_hostid_num = 0;
5657#endif
5658
5659#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5660
drh0ab216a2010-07-02 17:10:40 +00005661/* Not always defined in the headers as it ought to be */
5662extern int gethostuuid(uuid_t id, const struct timespec *wait);
5663
drh7ed97b92010-01-20 13:07:21 +00005664/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5665** bytes of writable memory.
5666*/
5667static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005668 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5669 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005670#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5671 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005672 {
5673 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5674 if( gethostuuid(pHostID, &timeout) ){
5675 int err = errno;
5676 if( pError ){
5677 *pError = err;
5678 }
5679 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005680 }
drh7ed97b92010-01-20 13:07:21 +00005681 }
drhe8b0c9b2010-09-25 14:13:17 +00005682#endif
drh7ed97b92010-01-20 13:07:21 +00005683#ifdef SQLITE_TEST
5684 /* simulate multiple hosts by creating unique hostid file paths */
5685 if( sqlite3_hostid_num != 0){
5686 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5687 }
5688#endif
5689
5690 return SQLITE_OK;
5691}
5692
5693/* The conch file contains the header, host id and lock file path
5694 */
5695#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5696#define PROXY_HEADERLEN 1 /* conch file header length */
5697#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5698#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5699
5700/*
5701** Takes an open conch file, copies the contents to a new path and then moves
5702** it back. The newly created file's file descriptor is assigned to the
5703** conch file structure and finally the original conch file descriptor is
5704** closed. Returns zero if successful.
5705*/
5706static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5707 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5708 unixFile *conchFile = pCtx->conchFile;
5709 char tPath[MAXPATHLEN];
5710 char buf[PROXY_MAXCONCHLEN];
5711 char *cPath = pCtx->conchFilePath;
5712 size_t readLen = 0;
5713 size_t pathLen = 0;
5714 char errmsg[64] = "";
5715 int fd = -1;
5716 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005717 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005718
5719 /* create a new path by replace the trailing '-conch' with '-break' */
5720 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5721 if( pathLen>MAXPATHLEN || pathLen<6 ||
5722 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005723 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005724 goto end_breaklock;
5725 }
5726 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005727 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005728 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005729 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005730 goto end_breaklock;
5731 }
5732 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005733 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5734 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005735 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005736 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005737 goto end_breaklock;
5738 }
drhe562be52011-03-02 18:01:10 +00005739 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005740 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005741 goto end_breaklock;
5742 }
5743 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005744 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005745 goto end_breaklock;
5746 }
5747 rc = 0;
5748 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005749 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005750 conchFile->h = fd;
5751 conchFile->openFlags = O_RDWR | O_CREAT;
5752
5753end_breaklock:
5754 if( rc ){
5755 if( fd>=0 ){
5756 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005757 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005758 }
5759 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5760 }
5761 return rc;
5762}
5763
5764/* Take the requested lock on the conch file and break a stale lock if the
5765** host id matches.
5766*/
5767static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5768 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5769 unixFile *conchFile = pCtx->conchFile;
5770 int rc = SQLITE_OK;
5771 int nTries = 0;
5772 struct timespec conchModTime;
5773
5774 do {
5775 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5776 nTries ++;
5777 if( rc==SQLITE_BUSY ){
5778 /* If the lock failed (busy):
5779 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5780 * 2nd try: fail if the mod time changed or host id is different, wait
5781 * 10 sec and try again
5782 * 3rd try: break the lock unless the mod time has changed.
5783 */
5784 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005785 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005786 pFile->lastErrno = errno;
5787 return SQLITE_IOERR_LOCK;
5788 }
5789
5790 if( nTries==1 ){
5791 conchModTime = buf.st_mtimespec;
5792 usleep(500000); /* wait 0.5 sec and try the lock again*/
5793 continue;
5794 }
5795
5796 assert( nTries>1 );
5797 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5798 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5799 return SQLITE_BUSY;
5800 }
5801
5802 if( nTries==2 ){
5803 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005804 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005805 if( len<0 ){
5806 pFile->lastErrno = errno;
5807 return SQLITE_IOERR_LOCK;
5808 }
5809 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5810 /* don't break the lock if the host id doesn't match */
5811 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5812 return SQLITE_BUSY;
5813 }
5814 }else{
5815 /* don't break the lock on short read or a version mismatch */
5816 return SQLITE_BUSY;
5817 }
5818 usleep(10000000); /* wait 10 sec and try the lock again */
5819 continue;
5820 }
5821
5822 assert( nTries==3 );
5823 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5824 rc = SQLITE_OK;
5825 if( lockType==EXCLUSIVE_LOCK ){
5826 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5827 }
5828 if( !rc ){
5829 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5830 }
5831 }
5832 }
5833 } while( rc==SQLITE_BUSY && nTries<3 );
5834
5835 return rc;
5836}
5837
5838/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005839** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5840** lockPath means that the lockPath in the conch file will be used if the
5841** host IDs match, or a new lock path will be generated automatically
5842** and written to the conch file.
5843*/
5844static int proxyTakeConch(unixFile *pFile){
5845 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5846
drh7ed97b92010-01-20 13:07:21 +00005847 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005848 return SQLITE_OK;
5849 }else{
5850 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005851 uuid_t myHostID;
5852 int pError = 0;
5853 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005854 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005855 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005856 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005857 int createConch = 0;
5858 int hostIdMatch = 0;
5859 int readLen = 0;
5860 int tryOldLockPath = 0;
5861 int forceNewLockPath = 0;
5862
drh308c2a52010-05-14 11:30:18 +00005863 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5864 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005865
drh7ed97b92010-01-20 13:07:21 +00005866 rc = proxyGetHostID(myHostID, &pError);
5867 if( (rc&0xff)==SQLITE_IOERR ){
5868 pFile->lastErrno = pError;
5869 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005870 }
drh7ed97b92010-01-20 13:07:21 +00005871 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005872 if( rc!=SQLITE_OK ){
5873 goto end_takeconch;
5874 }
drh7ed97b92010-01-20 13:07:21 +00005875 /* read the existing conch file */
5876 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5877 if( readLen<0 ){
5878 /* I/O error: lastErrno set by seekAndRead */
5879 pFile->lastErrno = conchFile->lastErrno;
5880 rc = SQLITE_IOERR_READ;
5881 goto end_takeconch;
5882 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5883 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5884 /* a short read or version format mismatch means we need to create a new
5885 ** conch file.
5886 */
5887 createConch = 1;
5888 }
5889 /* if the host id matches and the lock path already exists in the conch
5890 ** we'll try to use the path there, if we can't open that path, we'll
5891 ** retry with a new auto-generated path
5892 */
5893 do { /* in case we need to try again for an :auto: named lock file */
5894
5895 if( !createConch && !forceNewLockPath ){
5896 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5897 PROXY_HOSTIDLEN);
5898 /* if the conch has data compare the contents */
5899 if( !pCtx->lockProxyPath ){
5900 /* for auto-named local lock file, just check the host ID and we'll
5901 ** use the local lock file path that's already in there
5902 */
5903 if( hostIdMatch ){
5904 size_t pathLen = (readLen - PROXY_PATHINDEX);
5905
5906 if( pathLen>=MAXPATHLEN ){
5907 pathLen=MAXPATHLEN-1;
5908 }
5909 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5910 lockPath[pathLen] = 0;
5911 tempLockPath = lockPath;
5912 tryOldLockPath = 1;
5913 /* create a copy of the lock path if the conch is taken */
5914 goto end_takeconch;
5915 }
5916 }else if( hostIdMatch
5917 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5918 readLen-PROXY_PATHINDEX)
5919 ){
5920 /* conch host and lock path match */
5921 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005922 }
drh7ed97b92010-01-20 13:07:21 +00005923 }
5924
5925 /* if the conch isn't writable and doesn't match, we can't take it */
5926 if( (conchFile->openFlags&O_RDWR) == 0 ){
5927 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005928 goto end_takeconch;
5929 }
drh7ed97b92010-01-20 13:07:21 +00005930
5931 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005932 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005933 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5934 tempLockPath = lockPath;
5935 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005936 }
drh7ed97b92010-01-20 13:07:21 +00005937
5938 /* update conch with host and path (this will fail if other process
5939 ** has a shared lock already), if the host id matches, use the big
5940 ** stick.
drh715ff302008-12-03 22:32:44 +00005941 */
drh7ed97b92010-01-20 13:07:21 +00005942 futimes(conchFile->h, NULL);
5943 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005944 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005945 /* We are trying for an exclusive lock but another thread in this
5946 ** same process is still holding a shared lock. */
5947 rc = SQLITE_BUSY;
5948 } else {
5949 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005950 }
drh715ff302008-12-03 22:32:44 +00005951 }else{
drh7ed97b92010-01-20 13:07:21 +00005952 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005953 }
drh7ed97b92010-01-20 13:07:21 +00005954 if( rc==SQLITE_OK ){
5955 char writeBuffer[PROXY_MAXCONCHLEN];
5956 int writeSize = 0;
5957
5958 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5959 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5960 if( pCtx->lockProxyPath!=NULL ){
5961 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5962 }else{
5963 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5964 }
5965 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00005966 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00005967 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5968 fsync(conchFile->h);
5969 /* If we created a new conch file (not just updated the contents of a
5970 ** valid conch file), try to match the permissions of the database
5971 */
5972 if( rc==SQLITE_OK && createConch ){
5973 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005974 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00005975 if( err==0 ){
5976 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5977 S_IROTH|S_IWOTH);
5978 /* try to match the database file R/W permissions, ignore failure */
5979#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00005980 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00005981#else
drhff812312011-02-23 13:33:46 +00005982 do{
drhe562be52011-03-02 18:01:10 +00005983 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00005984 }while( rc==(-1) && errno==EINTR );
5985 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00005986 int code = errno;
5987 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5988 cmode, code, strerror(code));
5989 } else {
5990 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5991 }
5992 }else{
5993 int code = errno;
5994 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5995 err, code, strerror(code));
5996#endif
5997 }
drh715ff302008-12-03 22:32:44 +00005998 }
5999 }
drh7ed97b92010-01-20 13:07:21 +00006000 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6001
6002 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006003 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006004 if( rc==SQLITE_OK && pFile->openFlags ){
6005 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006006 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006007 }
6008 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006009 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006010 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006011 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006012 if( fd>=0 ){
6013 pFile->h = fd;
6014 }else{
drh9978c972010-02-23 17:36:32 +00006015 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006016 during locking */
6017 }
6018 }
6019 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6020 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6021 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6022 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6023 /* we couldn't create the proxy lock file with the old lock file path
6024 ** so try again via auto-naming
6025 */
6026 forceNewLockPath = 1;
6027 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006028 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006029 }
6030 }
6031 if( rc==SQLITE_OK ){
6032 /* Need to make a copy of path if we extracted the value
6033 ** from the conch file or the path was allocated on the stack
6034 */
6035 if( tempLockPath ){
6036 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6037 if( !pCtx->lockProxyPath ){
6038 rc = SQLITE_NOMEM;
6039 }
6040 }
6041 }
6042 if( rc==SQLITE_OK ){
6043 pCtx->conchHeld = 1;
6044
6045 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6046 afpLockingContext *afpCtx;
6047 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6048 afpCtx->dbPath = pCtx->lockProxyPath;
6049 }
6050 } else {
6051 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6052 }
drh308c2a52010-05-14 11:30:18 +00006053 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6054 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006055 return rc;
drh308c2a52010-05-14 11:30:18 +00006056 } while (1); /* in case we need to retry the :auto: lock file -
6057 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006058 }
6059}
6060
6061/*
6062** If pFile holds a lock on a conch file, then release that lock.
6063*/
6064static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006065 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006066 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6067 unixFile *conchFile; /* Name of the conch file */
6068
6069 pCtx = (proxyLockingContext *)pFile->lockingContext;
6070 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006071 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006072 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006073 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006074 if( pCtx->conchHeld>0 ){
6075 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6076 }
drh715ff302008-12-03 22:32:44 +00006077 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006078 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6079 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006080 return rc;
6081}
6082
6083/*
6084** Given the name of a database file, compute the name of its conch file.
6085** Store the conch filename in memory obtained from sqlite3_malloc().
6086** Make *pConchPath point to the new name. Return SQLITE_OK on success
6087** or SQLITE_NOMEM if unable to obtain memory.
6088**
6089** The caller is responsible for ensuring that the allocated memory
6090** space is eventually freed.
6091**
6092** *pConchPath is set to NULL if a memory allocation error occurs.
6093*/
6094static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6095 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006096 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006097 char *conchPath; /* buffer in which to construct conch name */
6098
6099 /* Allocate space for the conch filename and initialize the name to
6100 ** the name of the original database file. */
6101 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6102 if( conchPath==0 ){
6103 return SQLITE_NOMEM;
6104 }
6105 memcpy(conchPath, dbPath, len+1);
6106
6107 /* now insert a "." before the last / character */
6108 for( i=(len-1); i>=0; i-- ){
6109 if( conchPath[i]=='/' ){
6110 i++;
6111 break;
6112 }
6113 }
6114 conchPath[i]='.';
6115 while ( i<len ){
6116 conchPath[i+1]=dbPath[i];
6117 i++;
6118 }
6119
6120 /* append the "-conch" suffix to the file */
6121 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006122 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006123
6124 return SQLITE_OK;
6125}
6126
6127
6128/* Takes a fully configured proxy locking-style unix file and switches
6129** the local lock file path
6130*/
6131static int switchLockProxyPath(unixFile *pFile, const char *path) {
6132 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6133 char *oldPath = pCtx->lockProxyPath;
6134 int rc = SQLITE_OK;
6135
drh308c2a52010-05-14 11:30:18 +00006136 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006137 return SQLITE_BUSY;
6138 }
6139
6140 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6141 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6142 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6143 return SQLITE_OK;
6144 }else{
6145 unixFile *lockProxy = pCtx->lockProxy;
6146 pCtx->lockProxy=NULL;
6147 pCtx->conchHeld = 0;
6148 if( lockProxy!=NULL ){
6149 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6150 if( rc ) return rc;
6151 sqlite3_free(lockProxy);
6152 }
6153 sqlite3_free(oldPath);
6154 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6155 }
6156
6157 return rc;
6158}
6159
6160/*
6161** pFile is a file that has been opened by a prior xOpen call. dbPath
6162** is a string buffer at least MAXPATHLEN+1 characters in size.
6163**
6164** This routine find the filename associated with pFile and writes it
6165** int dbPath.
6166*/
6167static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006168#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006169 if( pFile->pMethod == &afpIoMethods ){
6170 /* afp style keeps a reference to the db path in the filePath field
6171 ** of the struct */
drhea678832008-12-10 19:26:22 +00006172 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006173 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6174 } else
drh715ff302008-12-03 22:32:44 +00006175#endif
6176 if( pFile->pMethod == &dotlockIoMethods ){
6177 /* dot lock style uses the locking context to store the dot lock
6178 ** file path */
6179 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6180 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6181 }else{
6182 /* all other styles use the locking context to store the db file path */
6183 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006184 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006185 }
6186 return SQLITE_OK;
6187}
6188
6189/*
6190** Takes an already filled in unix file and alters it so all file locking
6191** will be performed on the local proxy lock file. The following fields
6192** are preserved in the locking context so that they can be restored and
6193** the unix structure properly cleaned up at close time:
6194** ->lockingContext
6195** ->pMethod
6196*/
6197static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6198 proxyLockingContext *pCtx;
6199 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6200 char *lockPath=NULL;
6201 int rc = SQLITE_OK;
6202
drh308c2a52010-05-14 11:30:18 +00006203 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006204 return SQLITE_BUSY;
6205 }
6206 proxyGetDbPathForUnixFile(pFile, dbPath);
6207 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6208 lockPath=NULL;
6209 }else{
6210 lockPath=(char *)path;
6211 }
6212
drh308c2a52010-05-14 11:30:18 +00006213 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6214 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006215
6216 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6217 if( pCtx==0 ){
6218 return SQLITE_NOMEM;
6219 }
6220 memset(pCtx, 0, sizeof(*pCtx));
6221
6222 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6223 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006224 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6225 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6226 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6227 ** (c) the file system is read-only, then enable no-locking access.
6228 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6229 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6230 */
6231 struct statfs fsInfo;
6232 struct stat conchInfo;
6233 int goLockless = 0;
6234
drh99ab3b12011-03-02 15:09:07 +00006235 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006236 int err = errno;
6237 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6238 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6239 }
6240 }
6241 if( goLockless ){
6242 pCtx->conchHeld = -1; /* read only FS/ lockless */
6243 rc = SQLITE_OK;
6244 }
6245 }
drh715ff302008-12-03 22:32:44 +00006246 }
6247 if( rc==SQLITE_OK && lockPath ){
6248 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6249 }
6250
6251 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006252 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6253 if( pCtx->dbPath==NULL ){
6254 rc = SQLITE_NOMEM;
6255 }
6256 }
6257 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006258 /* all memory is allocated, proxys are created and assigned,
6259 ** switch the locking context and pMethod then return.
6260 */
drh715ff302008-12-03 22:32:44 +00006261 pCtx->oldLockingContext = pFile->lockingContext;
6262 pFile->lockingContext = pCtx;
6263 pCtx->pOldMethod = pFile->pMethod;
6264 pFile->pMethod = &proxyIoMethods;
6265 }else{
6266 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006267 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006268 sqlite3_free(pCtx->conchFile);
6269 }
drhd56b1212010-08-11 06:14:15 +00006270 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006271 sqlite3_free(pCtx->conchFilePath);
6272 sqlite3_free(pCtx);
6273 }
drh308c2a52010-05-14 11:30:18 +00006274 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6275 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006276 return rc;
6277}
6278
6279
6280/*
6281** This routine handles sqlite3_file_control() calls that are specific
6282** to proxy locking.
6283*/
6284static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6285 switch( op ){
6286 case SQLITE_GET_LOCKPROXYFILE: {
6287 unixFile *pFile = (unixFile*)id;
6288 if( pFile->pMethod == &proxyIoMethods ){
6289 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6290 proxyTakeConch(pFile);
6291 if( pCtx->lockProxyPath ){
6292 *(const char **)pArg = pCtx->lockProxyPath;
6293 }else{
6294 *(const char **)pArg = ":auto: (not held)";
6295 }
6296 } else {
6297 *(const char **)pArg = NULL;
6298 }
6299 return SQLITE_OK;
6300 }
6301 case SQLITE_SET_LOCKPROXYFILE: {
6302 unixFile *pFile = (unixFile*)id;
6303 int rc = SQLITE_OK;
6304 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6305 if( pArg==NULL || (const char *)pArg==0 ){
6306 if( isProxyStyle ){
6307 /* turn off proxy locking - not supported */
6308 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6309 }else{
6310 /* turn off proxy locking - already off - NOOP */
6311 rc = SQLITE_OK;
6312 }
6313 }else{
6314 const char *proxyPath = (const char *)pArg;
6315 if( isProxyStyle ){
6316 proxyLockingContext *pCtx =
6317 (proxyLockingContext*)pFile->lockingContext;
6318 if( !strcmp(pArg, ":auto:")
6319 || (pCtx->lockProxyPath &&
6320 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6321 ){
6322 rc = SQLITE_OK;
6323 }else{
6324 rc = switchLockProxyPath(pFile, proxyPath);
6325 }
6326 }else{
6327 /* turn on proxy file locking */
6328 rc = proxyTransformUnixFile(pFile, proxyPath);
6329 }
6330 }
6331 return rc;
6332 }
6333 default: {
6334 assert( 0 ); /* The call assures that only valid opcodes are sent */
6335 }
6336 }
6337 /*NOTREACHED*/
6338 return SQLITE_ERROR;
6339}
6340
6341/*
6342** Within this division (the proxying locking implementation) the procedures
6343** above this point are all utilities. The lock-related methods of the
6344** proxy-locking sqlite3_io_method object follow.
6345*/
6346
6347
6348/*
6349** This routine checks if there is a RESERVED lock held on the specified
6350** file by this or any other process. If such a lock is held, set *pResOut
6351** to a non-zero value otherwise *pResOut is set to zero. The return value
6352** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6353*/
6354static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6355 unixFile *pFile = (unixFile*)id;
6356 int rc = proxyTakeConch(pFile);
6357 if( rc==SQLITE_OK ){
6358 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006359 if( pCtx->conchHeld>0 ){
6360 unixFile *proxy = pCtx->lockProxy;
6361 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6362 }else{ /* conchHeld < 0 is lockless */
6363 pResOut=0;
6364 }
drh715ff302008-12-03 22:32:44 +00006365 }
6366 return rc;
6367}
6368
6369/*
drh308c2a52010-05-14 11:30:18 +00006370** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006371** of the following:
6372**
6373** (1) SHARED_LOCK
6374** (2) RESERVED_LOCK
6375** (3) PENDING_LOCK
6376** (4) EXCLUSIVE_LOCK
6377**
6378** Sometimes when requesting one lock state, additional lock states
6379** are inserted in between. The locking might fail on one of the later
6380** transitions leaving the lock state different from what it started but
6381** still short of its goal. The following chart shows the allowed
6382** transitions and the inserted intermediate states:
6383**
6384** UNLOCKED -> SHARED
6385** SHARED -> RESERVED
6386** SHARED -> (PENDING) -> EXCLUSIVE
6387** RESERVED -> (PENDING) -> EXCLUSIVE
6388** PENDING -> EXCLUSIVE
6389**
6390** This routine will only increase a lock. Use the sqlite3OsUnlock()
6391** routine to lower a locking level.
6392*/
drh308c2a52010-05-14 11:30:18 +00006393static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006394 unixFile *pFile = (unixFile*)id;
6395 int rc = proxyTakeConch(pFile);
6396 if( rc==SQLITE_OK ){
6397 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006398 if( pCtx->conchHeld>0 ){
6399 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006400 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6401 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006402 }else{
6403 /* conchHeld < 0 is lockless */
6404 }
drh715ff302008-12-03 22:32:44 +00006405 }
6406 return rc;
6407}
6408
6409
6410/*
drh308c2a52010-05-14 11:30:18 +00006411** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006412** must be either NO_LOCK or SHARED_LOCK.
6413**
6414** If the locking level of the file descriptor is already at or below
6415** the requested locking level, this routine is a no-op.
6416*/
drh308c2a52010-05-14 11:30:18 +00006417static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006418 unixFile *pFile = (unixFile*)id;
6419 int rc = proxyTakeConch(pFile);
6420 if( rc==SQLITE_OK ){
6421 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006422 if( pCtx->conchHeld>0 ){
6423 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006424 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6425 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006426 }else{
6427 /* conchHeld < 0 is lockless */
6428 }
drh715ff302008-12-03 22:32:44 +00006429 }
6430 return rc;
6431}
6432
6433/*
6434** Close a file that uses proxy locks.
6435*/
6436static int proxyClose(sqlite3_file *id) {
6437 if( id ){
6438 unixFile *pFile = (unixFile*)id;
6439 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6440 unixFile *lockProxy = pCtx->lockProxy;
6441 unixFile *conchFile = pCtx->conchFile;
6442 int rc = SQLITE_OK;
6443
6444 if( lockProxy ){
6445 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6446 if( rc ) return rc;
6447 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6448 if( rc ) return rc;
6449 sqlite3_free(lockProxy);
6450 pCtx->lockProxy = 0;
6451 }
6452 if( conchFile ){
6453 if( pCtx->conchHeld ){
6454 rc = proxyReleaseConch(pFile);
6455 if( rc ) return rc;
6456 }
6457 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6458 if( rc ) return rc;
6459 sqlite3_free(conchFile);
6460 }
drhd56b1212010-08-11 06:14:15 +00006461 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006462 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006463 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006464 /* restore the original locking context and pMethod then close it */
6465 pFile->lockingContext = pCtx->oldLockingContext;
6466 pFile->pMethod = pCtx->pOldMethod;
6467 sqlite3_free(pCtx);
6468 return pFile->pMethod->xClose(id);
6469 }
6470 return SQLITE_OK;
6471}
6472
6473
6474
drhd2cb50b2009-01-09 21:41:17 +00006475#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006476/*
6477** The proxy locking style is intended for use with AFP filesystems.
6478** And since AFP is only supported on MacOSX, the proxy locking is also
6479** restricted to MacOSX.
6480**
6481**
6482******************* End of the proxy lock implementation **********************
6483******************************************************************************/
6484
drh734c9862008-11-28 15:37:20 +00006485/*
danielk1977e339d652008-06-28 11:23:00 +00006486** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006487**
6488** This routine registers all VFS implementations for unix-like operating
6489** systems. This routine, and the sqlite3_os_end() routine that follows,
6490** should be the only routines in this file that are visible from other
6491** files.
drh6b9d6dd2008-12-03 19:34:47 +00006492**
6493** This routine is called once during SQLite initialization and by a
6494** single thread. The memory allocation and mutex subsystems have not
6495** necessarily been initialized when this routine is called, and so they
6496** should not be used.
drh153c62c2007-08-24 03:51:33 +00006497*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006498int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006499 /*
6500 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006501 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6502 ** to the "finder" function. (pAppData is a pointer to a pointer because
6503 ** silly C90 rules prohibit a void* from being cast to a function pointer
6504 ** and so we have to go through the intermediate pointer to avoid problems
6505 ** when compiling with -pedantic-errors on GCC.)
6506 **
6507 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006508 ** finder-function. The finder-function returns a pointer to the
6509 ** sqlite_io_methods object that implements the desired locking
6510 ** behaviors. See the division above that contains the IOMETHODS
6511 ** macro for addition information on finder-functions.
6512 **
6513 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6514 ** object. But the "autolockIoFinder" available on MacOSX does a little
6515 ** more than that; it looks at the filesystem type that hosts the
6516 ** database file and tries to choose an locking method appropriate for
6517 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006518 */
drh7708e972008-11-29 00:56:52 +00006519 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006520 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006521 sizeof(unixFile), /* szOsFile */ \
6522 MAX_PATHNAME, /* mxPathname */ \
6523 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006524 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006525 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006526 unixOpen, /* xOpen */ \
6527 unixDelete, /* xDelete */ \
6528 unixAccess, /* xAccess */ \
6529 unixFullPathname, /* xFullPathname */ \
6530 unixDlOpen, /* xDlOpen */ \
6531 unixDlError, /* xDlError */ \
6532 unixDlSym, /* xDlSym */ \
6533 unixDlClose, /* xDlClose */ \
6534 unixRandomness, /* xRandomness */ \
6535 unixSleep, /* xSleep */ \
6536 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006537 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006538 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006539 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006540 unixGetSystemCall, /* xGetSystemCall */ \
6541 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006542 }
6543
drh6b9d6dd2008-12-03 19:34:47 +00006544 /*
6545 ** All default VFSes for unix are contained in the following array.
6546 **
6547 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6548 ** by the SQLite core when the VFS is registered. So the following
6549 ** array cannot be const.
6550 */
danielk1977e339d652008-06-28 11:23:00 +00006551 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006552#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006553 UNIXVFS("unix", autolockIoFinder ),
6554#else
6555 UNIXVFS("unix", posixIoFinder ),
6556#endif
6557 UNIXVFS("unix-none", nolockIoFinder ),
6558 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006559#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006560 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006561#endif
6562#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006563 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006564#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006565 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006566#endif
chw78a13182009-04-07 05:35:03 +00006567#endif
drhd2cb50b2009-01-09 21:41:17 +00006568#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006569 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006570 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006571 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006572#endif
drh153c62c2007-08-24 03:51:33 +00006573 };
drh6b9d6dd2008-12-03 19:34:47 +00006574 unsigned int i; /* Loop counter */
6575
6576 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006577 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006578 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006579 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006580 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006581}
danielk1977e339d652008-06-28 11:23:00 +00006582
6583/*
drh6b9d6dd2008-12-03 19:34:47 +00006584** Shutdown the operating system interface.
6585**
6586** Some operating systems might need to do some cleanup in this routine,
6587** to release dynamically allocated objects. But not on unix.
6588** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006589*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006590int sqlite3_os_end(void){
6591 return SQLITE_OK;
6592}
drhdce8bdb2007-08-16 13:01:44 +00006593
danielk197729bafea2008-06-26 10:41:19 +00006594#endif /* SQLITE_OS_UNIX */